Jquery Ajax Call to PHP Script with JSON Return

jQuery AJAX Call to PHP Script with JSON Return

Make it dataType instead of datatype.

And add below code in php as your ajax request is expecting json and will not accept anything, but json.

header('Content-Type: application/json');

Correct Content type for JSON and JSONP

The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.

Return JSON data from PHP script using AJAX jQuery

You can give a "json" argument to $.post to tell it that the response is JSON, and it will automatically parse the response to a Javascript object or array. In my sample code below I'm assuming it's an array, and each element is an object that contains a property that you want to show in the result; replace .someProperty with the actual property.

$("#computerForm").submit(function(e) {
e.preventDefault();
$.post(this.action, $(this).serialize(), function(info) {
var html = "";
$.each(info, function() {
html += this.someProperty + "<br>";
});
$("#result").html(html);
}, "json");
});

process.php can use $_POST['serialnumber'] when it's calling the Airtable API.

$sn = $_POST['serialnumber'];

Jquery: Ajax call to a php script returning JSON data

The issue is because the promise is executed after the request completes. This means that $('body').html(output) has already been run before you loop over the returned JSON.

To solve this you need to execute all code which depends on the response within the done() handler. Try this:

$.ajax({
url:"lista.php",
dataType:"json"
}).done(function(data) {
var output = "<ul>";
$.each(data.Conoscenti, function() {
output += "<li>" + this.Nome + " " + this.Cognome + " è un mio conoscente. È nato il " + this.Nato.Giorno + " " + this.Nato.Mese + " " + this.Nato.Anno + "</li>";
});
output += "</ul>";
$("body").html(output);
});

Not getting a response for an AJAX call to PHP (with JSON data)

How to read JSON objects from PHP and display in browser?

There are lots of comments on your code:

  • While you already getting a json return from server; you don't to parse that. Its already a json object.
  • You can set async:true to get a promise data
  • The way you loop through objects you need to do that properly. see image how to get the object path correctly.
  • You can use $ token instead of jQuery token; unless you purposely need that.
  • I am not sure if this is the best approach; but it give the needed result as explained in your question.

The code is bellow tested with some comments:

<script type="text/javascript">
loadcall("test");
// as pointed you need to call the function so it runs

function loadcall(data) {
$.ajax({
async: true,
method: 'POST',
crossDomain: true,
dataType: 'json', //your data type should be JSON not JSONP
url: 'page.php?getcodenode',
data: {
'arg': data
},
success: function(result) {
console.log(result);
// see attached image how to get the path for object
var ret = result;
var el = $('#abc');
for (en in ret.itens) {
console.log(ret.itens[en].ds);
el.append('<div id="item_' + ret.itens[en].id +
'">' + ret.itens[en].lb + ', ' + ret.itens[en].ds + '</div>');
}
},
error: function(result) {
console.log(result);
}
});
}
</script>

How to get object path from console result?

  1. Open you developer tool in your browser hit F12 (In Chrome, Firefox or Edge):
  2. Go to Console tab and find the results.
  3. Expand the results tell you get to the object you need.
  4. Right click and `copy property path'.
  5. Use the object path as needed in your code.

jquery ajax returning text of php script instead of json

Not sure if this helps or not but the following code works for me. Set up a directory with your json, your php, and an html file for basically just populating the select menu. This works fine for me and when taking a look at your code there were some js errors:

$('<option value="' + index + '">' + this['coursecode'] +/option>') is missing the '< before the option close tag

Also missing a } after you ) at the end of fail. After fixing those files your code worked for me as far as populating the dropdown, though you get js errors because registeredCourses.getSelected(); doesn't exist. Which makes me wonder if the above code is complete?

If all that doesn't help then have you looked at teh raw html that is output when you go directly to your php file, like viewing the source?

`bonk.php`
<?php
header('Content-Type: application/json');
$fileName = "courses.json";
if (file_exists($fileName))
{
$json = json_decode(file_get_contents($fileName), true);
echo json_encode($json);
}
else
{
echo "The file $fileName does not exist";
}
;
?>

`courses.json`
[
{
"coursecode": "ACCTD_001",
"cflag": "Y",
"pflag": "Y",
"dateregistered": "08/11/14",
"timeregistered": "12:55 pm."
},
{
"coursecode": "LWPRG1_004",
"cflag": "Y",
"pflag": "Y",
"dateregistered": "08/18/14",
"timeregistered": "3:30 pm."
},
{
"coursecode": "LWPRG2_005",
"cflag": "Y",
"pflag": "Y",
"dateregistered": "08/18/14",
"timeregistered": "3:32 pm."
}
]

`html file`
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

var registeredCourses = {
init: function (){
$.ajax ({
type: 'GET',
dataType: "JSON",
url: "bonk.php",
})

.done(function(data){
$.each(data, function(index, element){
$('#registeredCourses')
.append($("<option></option>")
.attr("value",index)
.text(this['coursecode']));
});
})

.fail (function(jqXHR, textStatus, errorThrown){
console.log(errorThrown, textStatus, jqXHR);
})
}
};

registeredCourses.init();
</script>
</head>
<body>
<select name="test" id="registeredCourses"></select>
</body>
</html>

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

JSON response from php on AJAX call

  • In your JS file, remove contentType: "application/json",
  • In your php file, check "include file url" and
  • Close if statement block properly

JS File:

let CurrentDate = Date();
jsonObject = {
'TrackName' : 'Material Science',
'TrackDesc' : 'Test Text Test Text Test Text Test Text Test Text Test Text Test Text ',
'Timestamp' : CurrentDate
}
$.ajax({
type:'post',
url:'addNewTrack.php',
data: {trackDetails:jsonObject},
dataType: "json",
success: function(response) {
console.log('SUCCESS BLOCK');
console.log(response);
},
error: function(response) {
console.log('ERROR BLOCK');
console.log(response);
}
});

PHP File:

<?php
header('Content-type: application/json');
include('../connection.php');

if($_POST) {
$obj = $_POST['trackDetails'];

$TrackName = mysql_real_escape_string($obj['TrackName']);
$TrackDesc = mysql_real_escape_string($obj['TrackDesc']);
$TrackAdderID = 'Admin '; //$_SESSION["userID"];
$Timestamp = mysql_real_escape_string($obj['Timestamp']);

$response_array['status'] = 'status123';
echo json_encode($response_array);
}
?>

Ajax call to php mail() script failing on success, no json data is returned

The problem is here:

function render_email($input) {
//error_log("render_email " . print_r($input,TRUE), 0);
ob_start();
include "email-template.phtml";
return ob_get_contents();
}

You've got side-effects both leaving the contents of your rendered template in the buffer, and leaving buffering enabled. You'll want to change this to:

function render_email($input) {
//error_log("render_email " . print_r($input,TRUE), 0);
ob_start();
include "email-template.phtml";
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}

jQuery ajax request with json response, how to?

You need to call the

$.parseJSON();

For example:

...
success: function(data){
var json = $.parseJSON(data); // create an object with the key of the array
alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
} ...

see this in
http://api.jquery.com/jQuery.parseJSON/

if you still have the problem of slashes:
search for security.magicquotes.disabling.php
or:
function.stripslashes.php

Note:

This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.



Related Topics



Leave a reply



Submit