Parsing JSON Objects in JavaScript - javascript

I have php on my server that is handling the AJAX call and returning a JSON object like so:
$dataArray = array('order_id'=>$order_id, 'response'=>'Sucessfully Added');
header('Content-type: application/json');
echo json_encode( $dataArray );
This is my AJAX call:
$('.add').ajaxForm({url: this.href, type:'post',
data: this.serialize,
dataType: 'json',
success: function(responseText){
var p = JSON.parse(responseText);
alert(p.response);
$('.popupContainer').hide();
}
});
In FireBug I can see that it reaches the line that begins with 'var p' just fine. In fact, at this point, FB tells me that the responseText is exactly what I want it to be: {"order_id":"182","response":"Sucessfully Added"}. But at that point it suddenly stops, so I must be missing something here.

There is no need to do manual parsing, since the dataType is set as json the response will be automatically parsed
$('.add').ajaxForm({
url: this.href,
type: 'post',
data: this.serialize,
dataType: 'json',
success: function (p) {
alert(p.response);
$('.popupContainer').hide();
}
});
jQuery Form
dataType
'json': if dataType == 'json' the server response will be evaluted and
passed to the 'success' callback, if specified
success
responseText or responseXML value (depending on the value of the
dataType option).

Related

Sending AJAX post request to PHP

So here is my AJAX code using JQuery:
$('#button-upload').on('click', function(){
if( sendSMSArr.length > 0 ){
$.ajax({
url: 'manager/smsendr4.php',
type: 'POST',
dataType: 'json',
data: {'distribution': sendSMSArr},
success: function(response){
}
});
}
});
The request isn't registered in the network.
Secondly, I'm not sure how can I collect this data with PHP using $_POST.
You seem to be a php newbie. Here is a snippet of code you can use to retrive the ajax data.
Here is the link to the documentation about the global variable $_POST I suggest you to read it.
Another useful link about the predefined variables in php
JS code:
$('#button-upload').on('click', function(event){
event.preventDefault();
if( sendSMSArr.length > 0 ){
$.ajax({
url: 'manager/smsendr4.php',
type: 'POST',
dataType: 'json',
data: {'distribution': sendSMSArr},
success: function(response){
console.log(response);
}
});
}
});
PHP:
<?php
if(isset($_POST['distribution'])){
# I've added a sanitization filter, but you can omit it if you don't need to pass the data to a database.
$dist = filter_var($_POST['distribution'], FILTER_SANITIZE_STRING);
# put your logics here after you got the distribution $_POST variable value.
}
?>

Getting a particular value from ajax response

I am using ajax with masonry
Ajax code: This ajax is used to get data from
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
$items = $(data);
$grid.append( $items )
.masonry('appended', $items);
$(this).find(".loading").hide();
}
}
Php Part: This is just a small or sufficient part of php file to understand the problem
$b= "sv";
echo "asjdgsajd";
echo "a";
echo $b;
now i am getting everything correctly but i want to use say value of $b for setting a attribute value and also other values as content but how can i particularly get value of $b?
Thankyou
Change the dataType to json.
$.ajax({
type: "get",
url: "some.php",
dataType: "json",
success: function(data) {
//data will hold an object with your response data, no need to parse
console.log('Do whatever you want with ' + data.b + '.');
}
In some.php do the following:
$response =array(
'b' => "sv",
'a' => "asjdgsajd",
'c' => "a"
);
echo json_encode($response);
echo $b;
The items of the associative array will end up as properties of a javascript object, that you can use in your success callback (or done function as success is deprecated).
Try using json and change your php to send the json response that way you can send more content and access them on client side as you need it.
PHP Script :
$outArr=array("b"=>"sv","content1"=>"asjdgsajd","content2"=>"a");
$jsonResponse=json_encode($outArr);
echo $jsonResponse;
In AJAX function you can access your data like this:
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
data=$.parseJSON( data ); //parse response string
b=data.b;//value of b
content1=data.content1;//value of content1
$("#exampleDiv").attr("id",b).html(content1); //set the attribute and content here for an example div
}
}
})

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

how to create correct PHP json response

Hello i have a page can calla an ajax page in json with jquery.
i just set
dataType: "json"
in ajax call and i set header in php
header("Content-type: application/json; charset=utf-8");
but when i try read my response in a client i have this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var o = JSON.parse(jsonString);
For more information
PHP file function:
function _addToWishlist($v,$db){
$ris = array();
$data = array();
$data[0]=20;
$data[1]=25;
$data[2]=30;
$ris['stato']="1";
$ris['mex']="DA IMPLEMENTARE!!!";
$ris['data']=$data;
$ris['action']="";
ob_clean();
echo json_encode($ris);
}
and thi is a php response:
{"status":"success","stato":"1","mex":"DA IMPLEMENTARE!!!","data":[20,25,30],"action":""}
in client i use this javascript:
$.ajax({
url: "common/function/include/dataLoad.php",
type: "POST",
data: datas,
async:false,
//dataType: "text",
dataType: "json",
success: function(ris) {
// Run the code here that needs
// to access the data returned
//$(this).parent
//alert (ris);
risp=ris;
//var a = JSON.parse(ris);
tryParseJSON(ris);
//return ris;
},
error: function() {
alert('Errore di rete');
}
}).done(function(){
if(divwhere!=""){
$(divwhere).html(risp);
}
if(actionAfter!=""){
eval(actionAfter);
}
});
the function for test json is here: stackoverflow
how can i do for create a correct call json? thank you very much
jQuery will automatically parse a JSON response for you - you don't need to do it again. The returned ris object is ready for you to work with as-is. Assuming the request works, there is no problem with the format of your PHP response.
success: function(ris) {
console.log(ris.status); // = 'success'
console.log(ris.mex); // = 'DA IMPLEMENTARE!!!'
},

How to alert ajax response

I've read dozens of related posts, but I still can't get this to work.
I want to alert the response in jquery I get from PHP.
PHP:
$msg=array();
if(empty($whatever)){
$msg['cenas']="Não há contas";
}else{
$msg['cenas']="Há contas";
};
echo json_encode($msg);
JS:
$.ajax({
url: 'myscript.php',
dataType: 'json',
success: function(response){
alert(response.cenas);
}
});
PHP is echoing
{cenas: "Há contas}"
But I can't get it to alert in JS.
The php should echo back {"cenas": "Há contas"}, but what did you get in the alert? Did you get an undefined? If so, try to use jQuery.parseJSON before alert. e.g:
$.ajax({
url:"myscript.php",
dataType: "json",
success:function(data){
var obj = jQuery.parseJSON(data);
alert(obj.cenas);
}
});
You should tell jQuery to expect (and parse) JSON in the response (although jQuery could guess this correctly...) and you should write your javascript correctly:
$.ajax({
url: 'myscript.php',
dataType: 'json',
success: function(response){
alert(response.cenas);
}
});
Try
$.ajax({
url:"myscript.php",
dataType: "json",
success:function(data){
alert(data.cenas);
}
});
You have a syntax error.
Check out the Docs for $.ajax

Categories

Resources