Rolando
Rolando

Reputation: 62626

How to do a GET on a PHP page to get a JSON object?

How do I accomplish the following: User clicks on "Start" button on an HTML page makes a GET to a getnumber.php page, that returns the number 10 in the following form: {count: 10}

Upvotes: 0

Views: 72

Answers (6)

alex
alex

Reputation: 580

Try something like this

$.get('getnumber.php', function(data) {
   var result = eval(data);
});

If the page getnumber.php output {count: 10} then you get the result with result.count

You can also use $.getJSON method.

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175


//you jquery code
$.getJSON('getnumber.php', function(data) {
  alert(data); //returns your json_encoded number sent from getnumber.php page
});

//your php page
$arr = array("count" => 10);
echo json_encode($arr);

Upvotes: 1

maxjackie
maxjackie

Reputation: 23282

use json_decode in getnumber.php

json decode manual page

Upvotes: 0

acanimal
acanimal

Reputation: 5020

You need PHP return data in JSON format, which would be:

{"count": 10}

and indicating the returning data is JSON format with a header in the response.

From JavaScript side the returned value, the previous string, can be evalutated and converted to a JS object.

Upvotes: 0

Rafay
Rafay

Reputation: 31033

<input type="button" id="btnID"/>

$("#btnID").click(function(e){
 e.preventDefault(); //prevent the default behavior of the button, or return false as @alecgorge pointed it out
$.get("process.php",function(data){
console.log(data);
},'json');  //<-- specifying the dataType as json will parse the json return by the server
});

in the process.php

var $count=10;
echo json_encode($count);

look at

json_encode

$.get()

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Try Google.

Here is a good place to start.
Then go here and learn more.
Put them together and you should be well on your way.

Upvotes: 0

Related Questions