Jump to content

Call php functions using ajax


alicefreak

Recommended Posts

Yes, just use a flag variable to indicate what to do, for example -- using jQuery's $.post

$.post("phpfile.php",{flag: 1, var: 'test1'}, function(data) {
   if(data.ret != 'ok') {
      alert('Error: ' + data.error_msg);
   } else {
      alert('Success');
   }
},"json");
$.post("phpfile.php",{flag: 2, var: 'test2'}, function(data) {
   if(data.ret != 'ok') {
      alert('Error: ' + data.error_msg);
   } else {
      alert('Success');
   }
},"json");

in your PHP file:

<?php
if (isset($_POST['flag'])) {
   switch ($_POST['flag']) {
      case '1':
         if (isset($_POST['var']) && $_POST['var'] != 'test1') {
            exit(json_encode(array('ret'=>'not ok','error_msg'=>'Input not correct')));
         }
//
//     do case 1 work
//
         exit(json_encode(array('ret'=>'ok')));
         break;
      case '2':
         if (!isset($_POST['var'])) {
            exit(json_encode(array('ret'=>'not ok','error_msg'=>'Input not found')));
         }
//
// do case 2 work
//
         exit(json_encode(array('ret'=>'ok')));
         break;
      default:
         exit(json_encode(array('ret'=>'no ok','error_msg'=>'Invalid flag')));
      }
   }
?>

 

Note: not checked for syntax.

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.