holyredbeard
holyredbeard

Reputation: 21208

Sending a get variable to php file through getJSON?

Is it possible to send a parameter (eg. a get variable) with getJSON to a php file, and if so how to do it?

The code below doesn't work, but hopefully it shows what I try to accomplish.

var url = "http://www.address.com/"

$.getJSON('http://anotheraddress.com/messages.php?url=+escape(url))', function(data) {
    // code here
});

Upvotes: 1

Views: 9029

Answers (4)

Robin
Robin

Reputation: 21884

You can pass your data as the second parameter:
jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] ) (doc)

url = "http://www.address.com/"
$.getJSON({
  "http://anotheraddress.com/messages.php",
  { url: escape(url) },
  function(data) {}
})

Upvotes: 1

Starx
Starx

Reputation: 78971

Your jquery might look something like this

$.getJSON("messages.php", 
{
   data1: value1,
   data2: value2,
   url: escape(url)
},
function(data) { 
    alert(data.yourval);
});

The only thing you should remember while using getJSON is that, the php page message.php should return JSON string as a response. SO you have do something like this at the end of the file.

echo json_encode($responseArray); // Remember not to echo or output anything or the JQuery will not execute

Upvotes: 3

Cyclonecode
Cyclonecode

Reputation: 30001

Try changing your code to:

$.getJSON('http://anotheraddress.com/message.php?url='+escape(url), function(data) {
   // code here
});

Now you can access the url variable in your message.php file like this:

$url = $_GET['url'];

Upvotes: 2

James Thorpe
James Thorpe

Reputation: 32202

$.getJSON accepts another parameter for data:

var url = "http://www.address.com/"

$.getJSON('http://anotheraddress.com/messages.php', { url: escape(url) }, function(data) {
    // code here
});

Upvotes: 3

Related Questions