Atirag
Atirag

Reputation: 1740

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?

Upvotes: 0

Views: 100

Answers (2)

Jose Rojas
Jose Rojas

Reputation: 3520

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);}
   });

Upvotes: 1

ThomasK
ThomasK

Reputation: 300

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!

Upvotes: 2

Related Questions