December 30, 2011

Sending a get variable to php file through getJSON?

Question by holyredbeard

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

Answer by James Thorpe

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

Answer by Starx

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!