How to retrieve json encoded data after an Ajax post - javascript

I am using an ajax post to submit data for validation and storing in a database. If the data fails server-side validation error messages are then json encoded and sent back like this:
$errorArray = array();
if (!empty($nameErr)) {
$errorArray["nameErr"] = $nameErr;
}
if (!empty($emailErr)) {
$errorArray["emailErr"] = $emailErr;
}
if (!empty($phoneErr)) {
$errorArray["phoneErr"] = $phoneErr;
}
if (!empty($commentErr)) {
$errorArray["commentErr"] = $commentErr;
}
$data = json_encode($errorArray);
echo $data;
Then in the success callback of my ajax post I will displayt these errors, my question is how do I access these messages that are sent in the json encode function?
I have tried
error.response['nameErr']
and
error.response('errorArray["nameErr"])
but neither seem to work?

I think what you want is to have a header declaration in your PHP so that returning text is read as json.
In this case, you also need to set your ajax data type as json so it is prepared to receive json.
The success function of your ajax request simply does an if statement and if data.Error is false, you've got a problem and you can go ahead and read the data.ErrorMessage you yourself have recorded server side.
JavaScript:
var requestObject = { Property1 = "Hi" };
$.ajax({
url: myUrl,
method: "post",
data: requestObject,
dataType: "json",
success: function( data )
{
if( data.Error )
{
HandleError( data.ErrorMessage );
}
else
{
// Do stuff with data.Response
}
}
error: function( e )
{
alert( JSON.stringify( e ) ); // This usually relates to server side errors, 404 not founds etc... so this function will not magically know that your validation failed... Although you could perhaps throw a PHP fatal error...
}
});
PHP:
if( $_POST[ "Property1" ] != "sausage" )
{
header('Content-Type: application/json'); // This line will make your ajax be okay with the json response
$response = array(
"Error" => TRUE,
"ErrorMessage" => array( "Hey that doesn't equal sausage" ),
"Response" => false
);
echo json_encode( $response );
}
In your case, have an array of errors and fill them up as bits are not correctly passed... for example:
$errors = array();
if( /* condition */ )
$errors[] = "Error message 1";
if( /* condition */ )
$errors[] = "Error message 2";
if( count( $errors ) > 0 )
$response = array(
"Error" => TRUE,
"ErrorMessage" => $errors,
"Response" => false // Nothing to send back because there were errors
);
echo json_encode( $response );
P.S
If you're having issues getting the error messages or response you desire. Don't forget to check out the network tab in your favourite Developer Toolbar... Mines IE11 so here's an example of that:

I think, you mean to parse json in javascript.
For that you need to do:
JSON.parse('json');
Or
If you are using jquery, you can also do:
$.parseJSON('json');
Both will return you objects parsed from JSON.

This is a simple json all:
$.getJSON("serverpage.php", { form_data })
.done(function (data) {
console.log(data);
});
})
.fail(function (jqxhr, textStatus, error) {
console.log(error);
});

Related

PHP array to JavaScript array using json_encode()

How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.
JavaScript code:
$.ajax({
method:"POST",
url:'php.php',
data:"",
dataType:'json',
success:function(data){
var y1=data;
console.log(data.name);
}
});
PHP code:
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//assign vars after formatting to avoid a wrong login with correct
//username and password
$username = trim($_POST["user"]);
$customer_array = array();
$customer1 = array(
'name' => '3',
'city' => 'Houston'
);
$customer_array[] = $customer1;
$customer2 = array(
'name' => '2',
'city' => 'Boston'
);
$customer_array[] = $customer2;
$customer3 = array(
'name' => "1",
'city' => "Bossier City"
);
echo json_encode($customer_array);
}
I am just going to summarize my comments into an answer, first I would just turn off the json return for trouble shooting. You can parse the json after fact anyway:
$.ajax({
// Do "type" here
type:"POST",
url:'php.php',
// Send something to check in the script
// This is optional, but I like to do it...
data: {
"action":"get_name_city"
},
success:function(data){
// Do a try, just incase your parse fails
try {
// Parse the json here
var getJson = JSON.parse(data);
console.log(getJson);
console.log(data);
}
catch(Exception) {
// Show any errors that might get thrown
console.log(Exception.message);
}
}
});
PHP:
# Check the action is set and is named
if(isset($_POST["action"]) && $_POST["action"] == "get_name_city") {
$username = trim($_POST["user"]);
$customer_array = array();
$customer1 = array(
'name' => '3',
'city' => 'Houston'
);
$customer2 = array(
'name' => '2',
'city' => 'Boston'
);
$customer3 = array(
'name' => "1",
'city' => "Bossier City"
);
$customer_array[] = $customer1;
$customer_array[] = $customer2;
$customer_array[] = $customer3;
# Just die here
die(json_encode($customer_array));
}
# Die with error so there is some feedback to your ajax
die(json_encode(array('error'=>'No data was sent.')));
As has been mentioned, there are multiple options for passing the data from PHP:
add the Content-Type header with value application/json before sending the return from json_encode() to echo():
header('Content-Type: application/json');
echo json_encode($customer_array);
Parse the return from the PHP using JSON.parse()
success:function(data){
var y1=data;
var data = JSON.parse(data);
So pick one of those approaches. One might argue that the first is more semantically correct, since JSON data is being sent.
Additionally, the success callback of the AJAX request is attempting to access the property name of the data returned. However, the data returned should be an array of objects, each which has a property name. One approach to logging the name of each property is to use Array.forEach() and send the name of each element in the array to console.log().
data.forEach(function(dataItem) {
console.log(dataItem.name);
});
See a demonstration of this in this phpfiddle.
You where almost there. Your AJAX requests accepts JSON but your PHP does not output JSON (it does but not in the correct way), you'll have to set the appropriate Content-Type header:
header('Content-Type: application/json');
echo json_encode($customer_array);
Your AJAX request should now be able to use the properly formatted JSON as the data variable (and console.log it).

AJAX post php response

So i have this code that posts to a php file,
var values = {
'socketid': data.socketid,
'id': memberid.value
};
console.log(values);
$.ajax({
url: "continue.php",
type: "POST",
data: values,
});
but i am unsure how to get each seperate value from the php file continue.php, do i ruse $_REQUEST or something, im just not sure if i have to parse or anything, could i get an example on how i can do this
Since you are using POST method just:
$socketid = $_POST['socketid'];
$id = $_POST['id'];
$_REQUEST is to check both $_GET and $_POST at the same time but it is not necessay in your code
$_POST should work fine since your request is of type POST
Your continue.php will get values in the following way:
<?php
$socket_id=$_POST['socketid'];
id=$_POST['id'];
?>
For simple post use $.post() it's a shorthand for $.ajax() for POST request.
var values = {
'socketid': data.socketid,
'id': memberid.value
};
$.post('continue.php', values, function (response) {
var res = JSON.parse(response);
if (res.results == true) {
console.log('Data updated');
}else {
console.log('Data not updated');
}
})
In your PHP
<?php
$socket_id = $_POST['socketid'];
$id = $_POST['id'];
// here update your data/ use
// then send response to javascript
// echo json_encode(['results' => true]); for success
// echo json_encode(['results' => true]); for fail

Returning php associative array from function to ajax call with json_encode() not and object

This is my first post so i apologize if i leave something out or don't explain myself very well. All this code is in the same php file
My ajax call
$.ajax(
{
type: "POST",
url: window.location.href,
data: {func: 'genString'},
datatype: 'json'
})
.done(function ( response )
{
console.log( response );
console.log( repose.string );
});
Which falls into an if statement on the page
if ( isset ($_POST['func'] && $_POST['func'] == 'genString')
{
exit(json_encode(myFunction()));
}
The function run on the page
function myFunction()
{
/* Would generate a string based on the database */
$arr = array('rows' => 1, 'string' => 'My test string');
// Changes values in the array depending on the database
return $arr;
}
This function is run to generate the array when the page itself is loaded and use the string portion to display the it and the rows part to set the height of a text area in the browser however when the ajax is called
console.log(respose) this logs
{"rows":1,"string":"My test string"} instead of an object
However when i try logging or using the string
console.log( response.string );
it shows up as undefined
I have done this previously and it has worked and returned an object which i can use in js with response.string. I have tried to use JSON_FORCE_OBJECT this had no effect on the result
Right now, the response is just being treated as a string (datatype). That's why response.string isn't working.
You can just tell by adding this:
console.log( typeof response );
So don't forget to put:
header('Content-Type: application/json');
Inside you if block:
And you have a typo on the if block (isset and response):
if ( isset ($_POST['func']) && $_POST['func'] === 'genString' ) {
header('Content-Type: application/json');
exit(json_encode(myFunction()));
}
On the JS typo also:
console.log( response.string );
^^
Well, it is a grammatical errors.
The request option
datatype: 'json'
should be
dataType: 'json'

JQuery Ajax Get different type of variable in javascript compare with PHP

In my php code, I echo object type of variable. However, in JQuery ajax success return data is in the form of String data. I am using JSON.parse(data) to parse data into JSON form. But I can't do it due to the format of return string data. May I know how can I return JSON object in php and at the same the in my JQuery $ajax function will get the JSON object also and not string. The following is my code.
Javascript:
$(document).ready(function callAjax(){
$.ajax({
type: "GET",
url: "php/test.php",
cache: false,
success: function(data){
console.log( data);
interval = setTimeout(callAjax, 1000);
}
})
});
PHP:
<?php
require('test2.php');
$messages = get_msg();
if (is_array($messages) || is_object($messages)){
foreach($messages as $message){
$array = array('chat_id' => $message['chat_id'],
'sender_name' => $message['sender_name'],
'chat_body' => $message['chat_body'],
'chat_time' => $message['chat_time']);
$object = (object) $array;
echo json_encode(gettype ($object));
}
}else{
echo "Nothing";
}
?>
Add dataType:'json' inside your ajax call
You have to let him know what kind of data you are getting from the ajax call.Further more, send an array if your condition fails , something like this
json_encode(array('state'=>'nothing'));
php code
require('test2.php');
$messages = get_msg();
if (is_array($messages) || is_object($messages)){
foreach($messages as $message){
$array = array('chat_id' => $message['chat_id'],
'sender_name' => $message['sender_name'],
'chat_body' => $message['chat_body'],
'chat_time' => $message['chat_time']);
$object = (object) $array;
echo json_encode(array('state'=>gettype($object)));
}
}else{
echo json_encode(array('state'=>'nothing'));
}
Javascript
$(document).ready(function callAjax(){
$.ajax({
type: "GET",
url: "php/test.php",
cache: false,
dataType:'json',
success: function(data){
try {
data = jQuery.parseJSON(data);
}
catch (err) {
data = typeof data == 'object' ? data : jQuery.parseJSON(data);
}
console.log(data.state);
interval = setTimeout(callAjax, 1000);
}
})
});

Parsing Mandrill JSON Response with jQuery / Javascript

I have a php script which is sucessfully connecting to and sending an email through the Mandrill API. As dumb as it sounds, I can't figure out how to parse the following JSON reponse:
Array
(
[0] => Array
(
[email] => matt#mattblum.com
[status] => sent
[_id] => eedced1b58e24668907024e937afeabd
[reject_reason] =>
)
)
Full ajax call is:
$.ajax({
type: 'POST',
url: 'mandril.php',
data: formData.serialize(),
success: function(returnedData) {
var response = returnedData;
status = response[0]['status']; // I've also tried different combos of this
if(status == "sent") {
msgs('Message sent!');
var alreadySent = true;
} else {
msgs(response);
}
},
error: function(e) {
console.log(e);
}
The code I've tied to read the 'status' element:
console.log(response[0]['status']);
console.log(response[0][1]);
console.log(response[0][0]['status']);
console.log(response[0][0][1]);
Another thing I don't understand is that:
var response = returnedData;
console.log(response[0]);
Returns a capital 'A' and nothing else.
I'm sure it's something dumb that I'm doing but any help is greatly appreciated.
Matt,
Looks like your PHP array syntax is being captured as text and sent as a response to your post. If you specify JSON on the Mandrill/PHP side (and the ajax/jquery side) your jquery call should be able to parse the response.
console.log(response[0]) is returning 'A' because that's the first character of the string.
Add 'json' on the query side and json_encode($response) on the php side.

Categories