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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.