decode json as html - php

So I'm building a web application and I have an ajax request that pings a database (or database cache) and echos back a big thing of json. I'm totally new to json, and when the php pulls from the database I echo json_encode($databaseResults), then it shows up in my html page as a long string. My question is, how do I convert it and pull out the pieces I need into a nice format?
Thanks!
The Json result that was in the page looks like:
"[{\"currentcall\":\"1\",\"timecalled\":\"15:30\",\"etaTime\":\"15:35\",\"departmentID\":\"1\",\"memberID\":\"1\",\"callinnum\":\"1\",\"location\":\"Fire House\",\"billed\":\"N\",\"date\":\"2\\/12\\/11\",\"firstName\":\"Phil\",\"lastName\":\"asdf\",\"email\":\"pasdf#gmail.com\",\"homephone\":\"+19111111111\",\"cellphone\":\"+11234567891\",\"cellphone2\":null,\"workphone\":null,\"phonenumber5\":null,\"phonenumber6\":null,\"streetAddress\":\"10 asdfnt Dr\",\"city\":\"\",\"username\":\"pgsdfg\",\"password\":\"0623ab6b6b7dsasd3834799fbf2a08529d\",\"admin\":\"Y\",\"qualifications\":\"Interior\",\"rank\":null,\"cpr\":null,\"emt\":null,\"training\":null,\"datejoined\":null,\"dateactive\":null,\"state\":\"DE\",\"zip\":\"51264\",\"pending\":\"NO\",\"defaultETA\":\"7\",\"apparatus\":\"asdKE-286\"}]"
There can be multiple results... this is only one result
EDIT:
Basically, I'm trying to pass a bunch of rows in an array into an html file, and take out only the data I need and format it. I don't know if json is the best way to do this or not, just one solution I came up with. So if anyone has a better solution that would be awesome.
Edit2:
This is the jquery I have that makes the request, the php just has echo json_encode ($DBResults);
function getResponder(){
var responders = $.ajax({
type : "POST",
url: "/index.php/callresponse/get_responders",
success: function(html){
$("#ajaxDiv").html(html);
}
});
setTimeout("getResponder()", 10000);
}

As you flagged this as jquery I assume that you're using jQuery. If you're only going to get the one string you can skip the json part and use jQuery .load() like this $('#result').load('ajax/test.php'); that will load the contents from ajax/test.php into #result
However if you want to use json you can take a look over at getJSON on the jQuery documentation. You can also use the jQuery parseJSON function which will return the json an javascript object containing the jsonData.
Here's an example how you can use parseJSON
var object = $.praseJSON(jsonString); //jsonString is the string containing your actual json data
alert(object.location) //Will alert "Fire House" with the given json string
Here's an example of how you can use getJSON in the same way
$.getJSON('ajax/test.php', function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
});
If you want to pass parameters as well you can do it like this
$.getJSON('ajax/test.php',
{
Param1 : "Value1",
Param2 : "value2"
},
function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
}
);
If you are trying to send json from javascript to php you can use
$jsonArray = jsonDecode($_GET['key']);
Of course if you're using post you'll write $_POST instead.

You have to parse the data into a JSON object, then you can use properties of the object as you wish.
Without seeing the specifics, I can tell you that you'll need to use the JSON object to parse the text. See more here: http://www.json.org
var obj = JSON.parse(ajaxResponseText);

You should use php function json_decode which will give you an object or array with all the properties.
Then you should iterate recursively through this object and add the content of the properties to a string, which should be your final HTML.

Normally to display JSON response in an html element after jquery(for example) by web request, try this:
$("#box-content-selector").append(
"<pre>"+
JSON.stringify(JSON.parse(data), null, 4)+
"</pre>"
)

Related

Getting data from json through jquery

I am trying to learn how to retrieve data from a json obj that I return from PHP but I can not figure out how to get the values. My data looks something like this:
[{"user_name":"herp"},{"email":"herp.derp#gmail.com"},{"yy":"yyyy"},{"mm":"mm"},{"dd":"dd"}]
My client-side script looks something like this:
$.ajax({
type : 'POST',
url : 'serverside/get_installningar.php',
dataType : 'json',
success : function(data) {
}
});
I would like to type something like data.user_name to retrieve the user_name and so on. But is there a method for doing this? I have looked in the forum but can't find the right thing.
What you have is an array of objects and so you going to need to know where it is to get user_name,
data[0].user_name
see below for structural details,
[
{"user_name":"herp"}, // <-- data[0]
{"email":"herp.derp#gmail.com"}, // <-- data[1]
{"yy":"yyyy"}, // <-- data[2]
{"mm":"mm"}, // <-- data[3]
{"dd":"dd"} // <-- data[4]
]
As AndrewR pointed out,
This will work, but it would be better to fix the JSON format coming from PHP. {"user_name":"herp","email":"herp.derp#gmail.com","yy":"yyyy","mm":"mm","dd":"d‌​d"} and then his original plan will work.
as of jquery 1.4.1 you can do this natively
jQuery.parseJSON
Do that on the data.responseJSON to convert to JS object.
See How do I convert a JSON string to a JavaScript object in jQuery?
Use data.parseJSON();. It returns an object exactly the way you want it.
You are actually returning an array not a json object
Your data needs to look like this:
{{"user_name":"herp"},{"email":"herp.derp#gmail.com"},{"yy":"yyyy"},{"mm":"mm"},{"dd":"dd"}}
Try installing Firebug to debug the return value of your page if its a properly formatted JSON.
use it like:
console.log(data[0].user_name);
For a easy acces members of your json, try virtualising it in a nice format so you can understand where you have array and where you have object.
[] means array
{} means object
I recommand a chrome extension: JsonView
and for example, take a JSON request like this.
Just open it in a tab and it will be nicely formated.
Also it shows you in the bottom left corner how to access what you are hovering over.

how to pass javascript array to php

I want to pass array myWorkout to 'play_workout.php'.
I want 'play_workout.php' to open and display the contents of myWorkout (for this example).
(Once I see that this is working I will parse the data from myWorkout and write it back to a database).
I'm not getting any errors in firebug, but play_workout is not being opened nor is is capturing the array object myWorkout.
I would appreciate a second glance at this.
Thanks as always!
page workout_now.php
<div id="playworkout"><button onClick="playWorkout()">Play Workout</button></div>
JAVASCRIPT
function playWorkout(){
var arr = $("#dropTargetframe > li").map(function(){
return $(this).attr('data-id');}).get();
var myRoutine = arr;
var myWorkout = new Array();
for (var i in myRoutine){
if (myRoutine[i])
myWorkout.push(myRoutine[i]);
}
//array appears like ["4", "5", "1", "4"]
JSON.stringify(myWorkout);
encodeURIComponent(myWorkout);
var url = "http://localhost/RealCardio/play_workout.php";
$.get(url, myWorkout);
page play_workout.php
<?php
...
$arrayWorkout = json_decode($_REQUEST['myWorkout']);
print_r($arrayWorkout);
...
?>
Assuming, that as in your comment the array elements doesn't contain any special chars, just numbers, simply do
var myWorkoutPost=myWorkout.join('x');
Transport this to the server the way you want (form hidden field, AJAX, ..) and in PHP do
$myWorkout=explode('x',$_REQUEST['myWorkoutPost']);
Both PHP and Javascript use JSON encoding so I would say the best way would be to JSON encode the array and then POST it as a hidden field to the PHP page and use JSON decode.
http://www.php.net/manual/en/function.json-decode.php
Encode this array to JSON, send it to php script and recieve it with $_POST.
Finally, decode JSON in php script.
A work flow for almost every structured values 99% of the time it will do.
Use JSON.stringify([1,2,3]) it will give you a string "[1,2,3]".
Encode it with encodeURIComponent("[1,2,3]") you'll have something like this "%5B1%2C2%2C3%5D"
Now it's save to be sent to PHP or any other server side language try to use XMLHttpRequest or better jQuery.get() to send the values to PHP.
In php you'd do this:
- $arrayOfValues = json_decode($_REQUEST['name_of_parameter']);
- print_r($arrayOfValues);
Normally you'd need to include JSON library to support old browsers. More info on JSON.

Is it possible to send variables back from PHP to AJAX after AJAX to PHP request?

I have an AJAX request that fetches some info from a SQL database in PHP.
The problem is, I need to send it back to AJAX in variables. Not to just echo it all out on screen.
Is this possible? If so, how would I go about doing something like this?
Thanks.
Yes, you could json_encode the variable you want to send back to client.
echo json_encode( array('variable' => 'your value' ) );
The client will receive the data through a callback when the request is completed. Without more clarification on specifics that's all i can offer, with some more details i can provide code samples depending on whether you're using a JavaScript library such as jQuery or doing a raw XHR request.
Edit: so in jquery to retrieve the variable above you would do the following.
$.getJSON('yourfile.php', function(data){
console.log( data.variable );
});
If I understand you right, you'll want to build a php array and use json_encode to dump the array out as your response. Then in JS you can use the resutling JSON text to form an object.
ajaxpage.php
$resultArray = buildArrayOfItems('Select * from products order by price');
//I usually have my sql records returned directly as an array.
//that's all buildArrayOfItems does
die(json_encode($resultArray));
The PHP should yield something like this
results
{[
{
"id" : "2643",
"name" : "Leather Jacket",
"price" : "249.99"
},
{
"id" : "2645",
"name" : "Suede Jacket",
"price" : "289.99"
},
...
]}
and your JS will look like this (if you're using jQuery)
JS
$.getJSON('ajaxPage.php', {'someVariable':'someValue'}, function(obj){
console.log(obj.count); //will show number of resulting items
console.log(obj[0].id); //will show id of first item (2643)
});
//If you do not use jQuery, you'll need to use eval() or something evil like that
//to convert the string to an object
This site has a great example regarding what you're trying to achieve. http://ditio.net/2008/07/17/php-json-and-javascript-usage/
In short you'll want to use php's json_encode() to convert an array into a json compatible string and each that back to the client.
If you're using jQuery then you'll need to dataType property of $.ajax() to "json", from there you can interact directly with the response as a json object.
If you're using the standard XmlHttp.
var json = JSON.parse(xmlHttp.responseText);
You can always return something like:
echo "code you need to send back to AJAX &&& response text"
Then you can subdivide it into 2 variables with text.split("&&&").

How to return and process an array returned by a php file using ajax?

I've a php file which processes a query and returns an array.
How do i get these and array and parse them and display them using ajax.
I call the file using ajax. Its used to display the matching products while typing a text box with the price...
responseText doesn't return anything...
Your data needs to be encoded in a format that JavaScript can understand, like JSON. You want to serialize the PHP array and return that as the HTTP Response, more information on how to JSON serialize data can be found here. Once the data is serialized, you can parse it in the ResponseText as though it were a JavaScript object (i.e. you can pull data like this: ResponseText[0].some_key)
I should note that jQuery makes this very, VERY easy. Like... this easy:
var url = '/json-data.php?id=2';
$.getJSON(url, function(data) {
$("#target").text(data.some_key);
}

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