I'm having an issue returning a JSON from PHP to Javascript. Below is my PHP to create the JSON:
$environment[] = array('id' => $env, 'adjacencies' => $hostnames);
foreach($hostnames as $hostname) {
$environment[] = array('id' => $hostname, 'name' => $hostname, 'data' => array());
}
return json_encode($environment);;
When I print the json_encode environment to a text file, it comes back as:
[{"id":"Dev","adjacencies":["tb23","tbwag","tbvg","tbut"]},{"id":"tb23","name":"tb23","data":[]},{"id":"tbwag","name":"tbwag","data":[]},{"id":"tbvg","name":"tbvg","data":[]},{"id":"tbut","name":"tbut","data":[]}]
It seems that this is printing out properly but when I return it to the Javascript its coming back as undefined/null. Below is the javascript with the ajax call:
var ajax = new AJAX();
var args = "id=" + $("#apps").val() + "&env=" + node.id + "&nocache=" + (new Date()).valueOf();
ajax.connect("POST", "http://" + window.location.hostname + "/project/graph/host", args, function(json) {
var output = '';
for (property in json) {
output += property + ': ' + json[property]+'; ';
}
alert(output);
});
I've obviously tried a lot of different things to get it to print out but haven't had any luck. In PHP, I've tried json_last_error and it came back as '0', which means that there isn't an issue with the JSON structure.
In the end, I'd like to use the following command in Javascript to continue building my graph:
var hostNodes = eval('(' + json + ')');
Any help is appreciated as to why I can't get this to come back!
Keep your PHP code in an unique file that receives one post parameters, then construct the json array if it set, and at the bottom you can do
echo json_encode($json);
flush();
I'm not a professional with pure javascript and I'm not familar with your approach, but you should consider using jQuery, at least I'm going to suggest one way to receive an json array so that you can easily work with it (you also make sure that the data is json):
$.ajax(
{
// Post select to url.
type : 'post',
url : 'myPHPAjaxHandler.php',
dataType : 'json',
data :
{
'select' : true
},
success : function(data)
{
// PHP has returned a json array.
var id, hostname;
for(var i = 0; i < data.length; i++)
{
id = data[i].id;
hostname = hostname[i].id;
// Construct a string or an object using the data.
}
},
complete : function(data)
{
// Optional.
}
});
Like I say, It's there for you to decide whether you pick it up or not. It can become handy for complex projects.
It looks like you're assuming that the data passed to the callback function will be your JSON already parsed into JS objects, but I don't see any indication that that would be the case; it's most likely the raw JSON data that must be parsed into JS objects using JSON.parse (NOT eval() - eval() is very dangerous, you should always prefer JSON.parse when working with true JSON data, as it will not permit XSS-style attacks as they are generally not "pure" JSON.)
Related
So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.
I'm trying to deserialize an array from an URL I've sent from a JQuery Ajax call to a PHP script in the server.
What I have done
I've been sending variables with values to the server successfully with jQuery Ajax this way:
// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();
Then I prepare the data to be sent via Ajax this way:
var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString
And send it with jQuery Ajax like this:
$.ajax({
url: "script.php",
type: "GET",
data: data,
cache: false,
dataType:'html',
success: function (html) {
// Do something successful
}
});
Then I get it in the server this way:
$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;
And I'm able to use my variables easily as I need. However, I need to do this with an array.
Main question
Reading a lot, I've managed to learn the professional way to send an array to the server: serialize it! I've learnt this way to do it with jQuery:
var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo
This seems to be right. I add this to the data as before:
var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo
How do I reconstruct (unserialize) my array in the server? I've tried the same as before:
$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;
with no success! Any ideas why? How can I get my serialized array passed this way in the server as another array which PHP can handle so I can use it?
Or am I complicating my life myself needlessly? All I want is to send an array to the server.
If you name a variable with [] in the end of it, it will create an array out of the values passed with that name.
For example, http://www.example.com/?data[]=hello&data[]=world&data[]=test, will result in the array $_GET["data"] == array('hello', 'world', 'test'); created in PHP.
In the same way, you can create an associative array in PHP: http://www.example.com/?data[first]=foo&data[second]=bar will result in $_GET["data"] == array("first" => "foo", "second" => "bar");
BTW, you might be interested in using jQuery's .serialize() or .serializeArray(), if those fit your client side serializing needs.
I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.
I have a problem with the returned array from ajax call.
the array is encrypted using json. it is as below
while ($found_course = mysql_fetch_assoc($sql)) {
$info[] = array(
'code' => $found_course['course_code'],
'name' => $found_course['course_name'] );
}
echo json_encode($info); //this is returned to javascript
then the problem is that I am unable to use the above array returned in javascript. I tried using the $.each method but to no avail. the eval() also do not work as it give output as [object object]. Can someone please help me with this.
All I want is to be able to acces the code and the name of the course saperately
Thanks.
Just loop through it with for()
for (var c in myAjaxArray){
myAjaxArray[c].code; // contains the code
myAjaxArray[c].name // contains the name
}
Make sure you set the dataType in the jQuery ajax call to "JSON" to make sure you have a json Object. Or use the $.getJSON() function.
<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
var item = data[i];
alert(item["code"] + " / " + item["name"]);
}
<script>
This should get you the data you need. Not sure how you tried using $.each but it should be in your success function on your ajax call. Also make sure the datatype is set to json.
success: function(data){
$(data).each(function(idx,val){
alert(val.code + " " + val.name);
})
}
I have gathered data with jQuery, putten it into a multidimensional array, used JSON.stringify on it and passed it to PHP by use of AJAX, for some reason json_decode keeps on giving me a Syntax error, malformed JSON error.
Heres the JSON that gets passed on to the PHP
[\"foo\",\"foobar did the baz\",[[\"bar\",\"kg\",\"200\"],[\"baz\",\"l\",\"1337\"]]]
The weird thing is that i use JSON.stringify on the multidimensional array in JS. Heres how i put it together
var dataz = [];
var arrayContainingAll = [];
$("li", "#ingredientlist").each(function() {
var tempArray = [];
tempArray.push($(".ingredientname", this).text());
tempArray.push($(".unittext", this).text());
tempArray.push($(".amounttext", this).text());
arrayContainingAll.push(tempArray);
});
dataz.push($("h1").text());
dataz.push($("#method").val());
dataz.push(arrayContainingAll);
var json = JSON.stringify(dataz);
How can i make PHP parse the multidimensional array correctly?
I have fixed it by passing on 3 different stringified arrays, but its more the curiosity of why a multidimensional array fails
The PHP to show what happens is: var_dump(json_decode($_POST['ingredients']));
because it appearantly is important to show how i post the data, heres the JS to do the ajax request
$.ajax({
url: '/api/savenewrecipe.php',
type: 'POST',
data: 'ingredients=' + json + "&name=" + $("h1").text() + "&method=" + $("#method").val(),
success: function(result) {
if (result.ok == true) {
// #todo remove this for debugging purposes
//document.location.href = '/recipe/' + result.id;
}
else {
showError("Noget gik galt!", 2000);
}
}
});
If your server uses magic quotes, you'll need to remove them:
if (get_magic_quotes_gpc()) {
$_POST['ingredients'] = stripslashes($_POST['ingredients']);
}
i am trying to use the Jquery ajax function to call a php page to run a query and return xm the only problem is i dont know how to read the Jquery API page
http://api.jquery.com/jQuery.ajax/
it gives this example
$.ajax({ url: "test.html", context: document.body, success: function(){
$(this).addClass("done");
}});
is there a better example to call a php page to run a sql query and return a json i can encode
See http://api.jquery.com/jQuery.getJSON/ . For example...
The PHP...
<?php
// users.php
$some_users = array(
array('name' => 'Nobby Clark', 'email' => 'nobby#mailinator.com'),
array('name' => 'John Doe', 'email' => 'john#gmail.com'),
);
print json_encode($some_users);
?>
The Javascript...
$.getJSON('users.php', function(data) {
var users = "";
for ( var i = 0; i < data.length; i++ ) {
users += "<p>" + data[i].name + " (" + data[i].email + ") </p>";
}
$('.userlist').html(users);
});
You would just replace the "test.html" with a PHP script that does what you want to do - look up data in a database and return it in JSON.
This is almost a duplicate of a similar question I answered earlier that should explain how to work with PHP and JSON and such, but basically you build an array with the data you want and then run it through json_encode() and output it.
Take a look at this question: jQuery Ajax: Can i store more than one "variable" on success? it has an example of sending json requests with jquery and encoding json at server-side.
If you scroll down that page you will see a bunch of examples that should fill in the blanks for you.
As for the server side stuff, use the PHP file you call to:
Connect to, then query the database for the data you want to return.
Make sure the data you want to return to the client (JavaScript) is in a PHP array.
Output the array using json_encode().
Kill the script.
Something like this:
// Query DB into an array
$data = array(
array('foo' => 'we got this from the DB'),
array('bar' => 'new row')
);
// Output as JSON
print json_encode($data);
die;