简体   繁体   中英

Call php function with jquery using ajax

I'm trying to call a php function that is defined on a php file.

On the php file I have this that will call the function

if(isset($_GET))
{
    submit();    //Do something with your GET
}

But I'm getting an error when calling the php function within the jquery. I imagine it could be a path problem. The jquery file is in js/file.js and the php function is on data/php/function.php so I try it calling it like this.

       $.ajax({
          url: "../data/php/functions.php&paperid="+$('#table-paperid').text(),
          type: "GET",
          success:function(result)//we got the response
          {
           alert('Successfully called');
          },
          error:function(exception){alert('Exception:'+exception);}
       });

But no matter what I write on the url I always get the exception error. Any ideas?

It's better practice to use a POST ajax call in this case. You should also put the "type" property before the "url" field, although, I doubt this is the source of the error. Try an ajax call that looks something like this.

$.ajax({
      type: 'post',
      url: '/some/path',
      data: { paperid : $('#table-paperid').text()},
      success: function(data) {

        var response = JSON.parse(data);

      }
    })

and your php should be modified to.

if(isset($_POST['paperid']))
{
    submit();    //Do something with your GET
}

I've done this many times with no issue so hopefully this will solve your problem.

Best of luck!

You can set the query string this way as well:

 $.ajax({
      url: "../data/php/functions.php",
      type: "GET",
      data: {paperid: $('#table-paperid').text() }
      success:function(result)//we got the response
      {
       alert('Successfully called');
      },
      error:function(exception){alert('Exception:'+exception);}
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM