PHP: how to extract ajax array response - php

I am getting ajax response in array format from php url. How to extract array response values in jQuery?
FYI:
PHP array is:
$response = array('msg' => 'Hello', 'html' => '<b>Good bye</b>');
I am getting $response array in my ajax response. i.e.
var promo = "promo=45fdf4684sfd";
$.ajax({
type: "POST",
url: baseJsUrl + "/users/calc_discount",
data: promo,
success: function (msg) { // I am getting $response here as ajax response.
//alert(msg);
// Here I want to check whether response is in array format or not. if it is in array format, I want to extract msg here and want to use response array values.
}
});
Let me know answer pls.
Thanks.

You should echo that $response with json_encode().
You should probably set dataType: 'json' too inside the object literal you send to $.ajax().
Then you can access it natively with JavaScript using the dot operator inside your success callback...
function(msg) {
alert(msg.html);
}
BTW, this line...
$response = array(['msg'] => 'Hello', 'html' => '<b>Good bye</b>');
... isn't valid PHP. Remove the brackets from the first key.

My favorite solution for this is to encode array with PHP's function json_encode() so jquery will be happy to parse it.

I presume that you mean a JSON response, like this:
{"msg":"Hello","html":"<b>Good bye<\/b>"}
This is actually a native JS object, so you can use it right away like this:
success: function(msg){
alert(msg.msg);
alert(msg.html);
}
You can also use the jQuery.each() function to loop over all properties of the JSON object if you need to:
jQuery.each(msg, function(key, val) {
alert(key + "=" + val);
});

and If you do not have control over the PHP output then you can use another method to get the result.
Another solution is using http://phpjs.org/ library. Here you can find many functions available in JS as available in php. Usage is also same as that of PHP. So I feel if you get the json_encode/json_decode from there and use that then it can solve your problem easily.
Remember you can compile your needed functions only. In your case, it is json_encode and json_decode. No need to download whole library. Url to compile your library: http://phpjs.org/packages/configure

Related

Extracted json url from example.com/myjsonsql.php to jquery mobile fail to return value

i am a new php developers i was trying to create a simple system where i use php to extract database from mysql and use json in jquery mobile.
So here is the situation,
I've created a custom .php json (to extract data from mysql) on my website and i've successfully upload it onto my website eg: www.example.com/mysqljson.php
This is my code extracting mysql data `
header('content-type:application/json');
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('mydb');
$select = mysql_query('SELECT * FROM sample');
$rows=array();
while($row=mysql_fetch_array($select))
{
$rows[] = array('id'=>$row['id'], 'id'=>$row['id'], 'username'=>$row['username'], 'mobileno'=>$row['mobileno'], 'gangsa'=>$row['gangsa'], 'total'=>$row['total']);
}
echo json_encode($rows);`
Which in returns gives me the following json # http://i.imgur.com/d4HIxAA.png?1
Everything seems fine, but when i try to use the json url for extraction on jquery mobile it doesn't return any value.
i extract the json by using the following code;
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
jsonCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
},
error: function(e) {
console.log(e.message);
}
});
}
The json.id # #current_temp and json.id.username # #current_sum dint return any result on my jquery mobile page.
I suspected i didn't extracted the json url correctly, but im not sure, could anyone help me identify the problem?
Thank you.
jsonp expects a callback function to be defined in the json being retrieved - for ecample see here.
Your data print screen is actually plain old fashioned json, not jsonp.
So I see 2 options:
change the php data to render jsonp (this assumes you have control over data source).
change your jquery request to expect plain old fastioned json (this assumes client and server are on same domain, otherwise CORS error happen), e.g,,
$.get(forecastURL)
.then(function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
})
.fail(function(e) {
console.log(e.message);
});
First of all, you don't have to use jsonp to retrieve JSON. You could just do a simple Ajax Call. jQuery convert automatically your json string to a json object if your HTTP response contains the good Content-Type. And you did this good in your PHP call.
I think your problem comes from your json data analysis in your javascript success callback. The json generated is an array containing some user objects. In your code you don't work on one item of the array but you directly call .id or .username on the array. So javascript give you undefined values.
Here is an example displaying the data for the first item (index 0) of your json array. You have after that to choose for your own purpose how to treat your array objects but it's an example:
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
success: function(json) {
console.log(json);
// See, I use [0] to get the first item of the array.
$("#current_temp").html(json[0].id);
$("#current_summ").html(json[0].username);
},
error: function(e) {
console.log(e.message);
}
});
}

JSON object properties are undefined

I'm getting a JSON object back from an AJAX call and logging the result like this:
console.log(response);
And this is the response logged in the console:
{"filename":"new.jpg","orientation":"vertical"}
However, when I
console.log(response.orientation);
I get a response that it is undefined.
Most of the answers I've read indicate that an array was returned instead of an object and that response[0].orientation should work, but that is not the case here. When I assign the same array to another variable in the console:
var obj = {"filename":"new.jpg","orientation":"vertical"}
Then obj.orientation returns the correct value.
I'm creating the JSON object in PHP:
$response=array('filename' => $newfilename, 'orientation' => $orientation);
$response=json_encode($response);
echo $response;
Is it apparent why the properties are showing undefined?
Either put:
header("Content-type: application/jason");
in the PHP, specify dataType: "json" in the AJAX call in the JavaScript, or call JSON.parse.
You will need to parse your string to get a proper JSON object.
JSON.parse(response);
will provide you with a JSON object from which you can read the properties
Can you try the following example in jsfiddle.
This is not the better way you can use JSON.parse(); or $.parseJSON(); (jquery version)
But if this is your problem, json being returned as a string this fix it and you can alter your code
http://jsfiddle.net/dadviegas/gf8Yq/
I think the ajax / php part should look like
Ajax
$.ajax({
type: "POST",
url: "link.php",
dataType: "json",
success: function(result){
alert(result.orientation);
}
});
PHP
$response=array("filename" => "$newfilename", "orientation" => "$orientation");
$response=json_encode($response);
echo $response;
Make sure that use at least 5.2 php version

Jquery variables in JSON to PHP

I'm using Jquery and PHP together to make some Ajax calls. This is similar to something I'm doing:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://example/ajax",
data: { test: test },
cache: false,
async: true,
success: function( json ){
$.each( json.rows, function( i, object ){
//Example: object.date
<?php date('g:ia', $objectDate ) ?>;
});
}
});
What I need is to pass some JSON objects to PHP, for example object.date to $objectDate and then do something with them. Is this possible?
PHP is executed on the server, JS on the client. Once the server has processed the AJAX call that's it, it doesn't know anything anymore about what happens on the client.
You are already passing data from JS to PHP with your AJAX call. If you need to process that data in PHP do it before you return the call, it makes no sense to return a JSON object only to re-process it in PHP.
In summary what you should do is:
Pass some data from client to server with an AJAX call
PHP processes these data and returns a JSON object
JS processes the JSON object and, for instance, modifies the HTML of the page.
If you need to further process newly generated data with PHP do other AJAX calls.
Also, if you need JS to use any variable generated in point 2, just return it in the JSON object, that is what it is for.
Here's a basic rundown of going from JS to PHP, and PHP to JS:
To transfer an object from Javascript to PHP (and perserve it), you need to encode your data using JSON.stringify:
var data = { message: "Hello" };
$.ajax({
data: { data: JSON.stringify(data) },
// ...
});
Then, in PHP, you can use json_decode to convert the the posted JSON string into a PHP array that's really easy to work with:
$data = json_decode($_POST['data'], true);
echo $data['message'];
// prints "Hello"
To send JSON back as the response to the browser (for your success callback), use json_encode like so:
header('Content-type: application/json');
echo json_encode(array(
'message' => 'Hello, back'
));

Send PHP Array To Javascript

///////UPDATE - I already have jquery library included to my code so if its easier with jquery than javascript let me know please.
OK. There are loads of questions on here that are sending a JavaScript array to php but only 1 which is the same as mine. Unfortunately I didn't understand the answer.
So, at the moment I have an associative array in php. I then used this code,
echo json_encode($this->_inputErrors);
I don't actualy know why i'm using it, just was mentioned a lot in other examples like this. So that then sends the data to javascript (via ajax) and if i do this code,
alert(requestText);
I get a long line of text. As I imagine i should.
So how do i then in javascript get the text back to an array?
Or Is there a better way to do this?
Many Thanks For Your Time,
Chris
var o = JSON.parse( requestText );
Include this ( https://github.com/douglascrockford/JSON-js/blob/master/json2.js ) to support old browsers.
requestText is a JSON string. You need to parse the string into an object.
You can use JSON.parse to convert the string to JSON.
var obj = JSON.parse(requestText);
If your browser doesn't have JSON, include this:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
You need to set the return type as JSON
or if using jQuery, you can use jQuery's method getJSON() to get the JSON object from the url
Somedays before, I faced the same problem. Check my solution :)
array.html
$(document).ready(function(e){
//This array is where I'll receive the PHParray
var js_array=new Array();
$("#btn").click(function(e){
$.ajax({
type: 'POST',
url: 'vector.php',
cache: false,
success: function(data){
js_array=data;
//I use this "for" to print each array item into a div called "data".
for(var i=0;i<js_array.length;i++){
$("#data").append("<p>"+js_array[i]+"</p>");
}
},
dataType: 'json'
});
});
});
vector.php
<?php
$array = array(1,2,3,4,5,6);
/*As you, I use "json_encode" to serialize the array
echo json_encode($array);
?>
I hope it can help (:
The simplest way to transform that long line of text in Javascript is using eval:
alert(eval('(' + requestText + ')'));

How can I send an array to php through ajax?

I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?
You might do that with $.post method of jQuery (for example) :
var myJavascriptArray = new Array('jj', 'kk', 'oo');
$.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){
// do something with received data!
});
Php will receive an array which will be name myphpvariable and it will contain the myJavascriptArray values.
Is it that ?
You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out JSON-PHP for parsing JSON.
You might want to take a look at Creating JSON Data in PHP
IIRC, if PHP sees a query string that looks like http://blah.com/test.php?var[]=foo&var[]=bar&var[]=baz, it will automatically make an array called $var that contains foo, bar and baz. I think you can even specify the array index in the square brackets of the query string and it will stick the value in that index. You may need to URL encode the brackets... The usual way this feature is used is in creating an HTML input field with the name "var[]", so just do whatever the browser normally does there. There's a section in the PHP documentation on array variables through the request.
You may be looking for a way to Serialize (jQuery version) the data.
jQuery 1.4 was updated to use the PHP syntax for sending arrays. You can switch it into the old style by using:
here is the synatax:
jQuery.ajaxSetting.traditional = true;
here is the example
$.ajax({
traditional: true,
type: "post",
url: myURL,
dataType: "text",
data: dataToSend, //this will be an array eg.
success: function(request) {
$('#results').html(request);
} // End success
}); // End ajax method
You can create an array and send it, as Meador recommended:
(following code is Mootooled, but similar in other libraries / plain old JS)
myArray.each(function(item, index) myObject.set('arrayItems['+index+']', item);
myAjax.send(myObject.toQueryString());
That will send to php an array called arrayItems, which can be accessed through $_POST['arrayItems']
echo $_POST['arrayItems'] ;
will echo something like: array=>{[0]=>'first thing', [1]=> second thing}

Categories