I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});
Related
I am trying to Displaying PHP curl json array data in javascript.
if I echo
// curl output
$response = curl_exec($curl);
echo $response;
I will be having this data in the format below as my output
{"items":[{"id":"1","food":"rice","Amount":"100","condition":"paid"},
{"id":"2","food":"beans","Amount":"200","condition":"paid"},
{"id":"3","food":"yam","Amount":"50","condition":"not paid"},
{"id":"4","food":"tomatoes","Amount":"100","condition":"paid"},
{"id":"5","food":"potato","Amount":"700","condition":"paid"}]}
Question is how can I display the data in Javascript?
I have tried the code below but am having error "Undefine".
Can someone help me out?
Below is the code of my output in Javascript.
function loadData(){
$.post('json.php',
function(response){
$.each(JSON.parse(response),
function(i,v){
$('.info').append('<li><div class="msg-lhs"><span>'+v.id+'</span> <span>'+v.food+'</span> <span>'+v.Amount+'</span> <span>'+v.condition+'</span></div></li>');
});
$('.info').animate({scrollTop: $('.info').prop("scrollHeight")}, 500);
});
I don't know what is really messed up with your code, but I came up with a slightly different approach that works fine.
Note: assuming that you're getting data from your curl request fine.
just parsed your result outside the loop iteration and using forEach loop.
var response = '{"items":
[{"id":"1","food":"rice","Amount":"100","condition":"paid"},\
{"id":"2","food":"beans","Amount":"200","condition":"paid"},\
{"id":"3","food":"yam","Amount":"50","condition":"not paid"},\
{"id":"4","food":"tomatoes","Amount":"100","condition":"paid"},\
{"id":"5","food":"potato","Amount":"700","condition":"paid"}]}';
var parsed = JSON.parse(response)
parsed.items.forEach(function(v) {
$('.info').append('<li><div class="msg-lhs"><span>'+v.id+'</span>
<span>'+v.food+'</span> <span>'+v.Amount+'</span>
<span>'+v.condition+'</span></div></li>');
});
$('.info').animate({scrollTop: $('.info').prop("scrollHeight")}, 500);
Here is fiddle
I'm using the following code to send a form to a php processor:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
I presume that this sends the form to my php script with all the form values in json format but I then don't know how to then access this json and turn it back into the array i need to process in my PHP script.
Does anyone know how I access this variable in my processor script so I can process the data?
Also, what is the best way for me to view the data being posted so I can work out what to do with it, when I send the data the processor is obviously not displayed, is there a way to echo out/write the information received by the script to I can view it?
You can easily access to the json as an array called "$_POST" in your php.
for example, if you send the form as a json structured like this:
{
"name":"userID",
"psw":"password123"
}
in your php script there will be the variable $_POST with this structure:
$_POST = Array (
"name" => "userID",
"psw" => "password123"
)
EDIT
In a comment you asked me how to display the data received from the server,
that's quite simple,
in your php script just write this:
echo json_encode($_POST);
so that you output the $_POST array in the json format,
then in your script write this:
$.post($(this).attr('action'), $(this).serialize(),
function(data){ //"data" argument will contain the output from the server (that is the encoded $_POST array printed as json with the php code as showed above)
console.log(data); //log data
}
); //as you can see, I've deleted "json", becouse it's unuseful
So confused about how to connect frontend and backend?
Suppose I've got an object obj and var jsonText = JSON.stringify(obj);
how can I send this jsonText to backend (locally, non remote server, no database), using php to get this data and then save the content as a single new JSON file?
Thanks a lot!
You need to query your data from a database or from somewhere else in PHP. Then, you can echo it with PHP in a JSON format. In a second step, you can use jQuery or plain JavaScript to make an Ajax call to this PHP file and make something with it.
PHP (data.json.php):
<?php
header('Content-Type: application/json');
$output = array();
// query the data from somewhere
$output['data'] = "1234";
echo json_encode($output); // json_encode creates the json-specific formatting
?>
JavaScript (jQuery):
$.ajax({
url: "data.json.php",
success: function(result){
console.log(result);
}
});
The code is untested, but I think you should get the idea.
I am having trouble using the json object echoed from php to javascript. In the php file I define
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo($json);
and then in javascript file I want to access this object.
$("#test_btn").click(function() {
$.get("serverside.php", function(data, status) {
console.log("data " , data["a"]); //undefined
console.log(JSON.parse(data)); // error
});
});
I get undefined for data["a"] and an error for JSON.parse. How should I use the returend data?
Based on your comment (echoing several json strings), you should do the following:
Initialize an empty results array;
Read your file and put it in an array or object using json_decode();
Add this array / object to your results array;
At the end, use json_encode() to encode and echo out your results array.
You must make a JSON.parse(data) before attempting to access to data['a'], and send a header from PHP that implicitly say the browser that the data output is going to be a JSON.
header ('Content-Type: application/json');
The problem might be that PHP is returning a string that looks like JSON.
In JS it might help to JSON.parse(data) to convert from string to JSON object, then you can access it.
$("#test_btn").click(function() {
$.get("serverside.php", function(data, status) {
$json = JSON.parse(data);
console.log("data " , $json["a"]); // should now return 1
});
});
you need to put json_encode or parse it in javascript
JavaScript jQuery post:
var animals = {
animalsArray: [],
tripId: <?php echo $_GET['id']; ?>
};
$('.student-check').each(function() {
animals.animalsArray.push($(this).attr('id'));
});
var sendMe = JSON.stringify(animals);
$.post("saveChanges.php", sendMe, function(response) {
console.log(response);
}, "json");
PHP handler:
echo json_encode(print_r($_POST, true));
// Array
// (
// )
Why is the array empty? I'm posting data but the response returns an empty array.
You are encoding the data as JSON, which isn't a format PHP handles natively for form submissions.
Remove var sendMe = JSON.stringify(animals); and pass animals to $.post instead of sendMe. jQuery will encode it using one of the standard formats supported by HTML forms and PHP.
Alternatively see this question for how to get the raw request body.
Also:
echo json_encode(print_r($_POST, true));
json_encode and print_r are both functions that take a data structure and express it as a string. Use one or the other, not both.