My questions keep getting abandoned even though I am replying, so I am going to remake my question in the hopes that someone can see my error and help me out. I will try to be as thorough as possible.
Step 1: I have an array named divisionsLarge in the following form:
divisionsLarge = [{ "car":"Toyota", "color":"blue", "numberTires":"four" }, { "car":"Honda", "color":"red", "numberTires":"four"}, etc. etc. ... ]
(This data is fictional, but it's the process that is wrong somewhere (also ignore the fact that numberTires is being stored as a string instead of a int, it's fictional folks :P)
Anyway, I have 92 of the above entries, all with the same keys: car, color, and numberTires.
Now, I go through the array with the following function loop in order to build an array with just car & numberTires key:
var divisions = [];
for (var i = 0; i < divisionsLarge.length; i++) {
if(divisionsLarge[i].numberTires != "two"){
var obj = { "car": divisionsLarge[i].car,
"numberTires": divisionsLarge[i].numberTires};
divisions.push(obj);}
}
Ok, at this point, I THINK everything is good to go. If I use the console in FireBug and type in divisions[0] I get a beautiful object that consists of, for example,
Object { car = "Toyota", numberTires = "four"}
(I think there are still "" around the car & numberTires entries, this is just how FireBug displays the object, I could be wrong)
Now here's what I need help with. I've created more .ajax queries than I can count. I've used JSON.stringified, I've not used JSON.stringified, I've used json_decode(), I've just done print_r($_POST)...I've done so many things that I am completely unable to analyze what is affecting what in order to diagnose what the problem might be. It seems my .ajax POSTS might be wrong, it seems my PHP might be wrong. So here are the questions I would GREATLY appreciate being answered:
1) Is the divisions array being created by the javascript considered JSON, or in a format easily converted to JSON?
2) What does my AJAX call need to be? I have tried so many AJAX calls that I have NO idea what is considered right/wrong. Also, please use divisions and not the snippet of the array I provided above, as the divisions array is dynamically generated by what's contained in divisionsLarge.
3) What does my divisions.php PHP file need to look like? Right now it has an HTML skeleton around it with <script></script> tags that reference divisionsLarge.js and divisions.js [do these need to be in one .js file?] I have seen blank pages and Array() for so long that I'm even doubting the rest of the PHP file now.
4) How do I get, for example, the color value of the first index? This seems rudimentary but most examples that I see are just querying an array of just one object, e.g. echo $_POST["color"], but I have multiple entries of color, so I'm not sure how to just ask for the first one. I would like to know this mostly because I have had such bad success with testing whether the array is working or not - I have lost all faith in print_r($_POST) and var_dump($json).
Okay, First your questions. Then the code:
1.- Divisions is not considered JSON, it is just an object array. All javascript objects can easily be turned into JSON using JSON.stringify(); Look at the code below.
2.- Look at the code below.
3.- I am not sure what kind of processing you need in your PHP. The code below assumes you are posting this to another page, where you will do some processing and output something, that you can use in the complete function.
4.- Look at the code below.
I think this is what you want to do:
Javascript
divisionsLarge = [{ "car":"Toyota", "color":"blue", "numberTires":"four" }, { "car":"Honda", "color":"red", "numberTires":"four"}];
var divisions = [];
for (var i = 0; i < divisionsLarge.length; i++) {
if(divisionsLarge[i].numberTires != "two"){
var obj = { "car": divisionsLarge[i].car,
"numberTires": divisionsLarge[i].numberTires};
divisions.push(obj);}
}
//I am just going to send one of your array elements as a JSON object.
var postData = JSON.stringify(divisions[0]);
var url = "url where you want to post your data";
$.ajax(url, {
type: "POST",
data: { "jsonBeingSent" : postData },
success: function(data) {
//Do whatever you need to do with your PHP output here.
//If you are using something like my php sample then you will be receiving a JSON object(s)
}
});
Now, on your PHP you probably want something like this:
<?php
//You may want to do some checking about the sender, and so on.
$receivedData = json_decode($_POST['jsonBeingSent']);
//You should see something like this if you print_r $receivedData
// object(stdClass) {
// [car] => ...
// [numberTires] => ...
// }
//So you could access the car value like this
echo $receivedData->{'car'};
//Do your processing and then, if you are using an array or object you can use `json_encode()` to output your data.
?>
Hope that helps.
Related
Assume I have this object in JavaScript which is built like this:
var obj = {};
var fields = ['table_name[field_name]', 'tale_name[field_name_2]']
for(var i; i < fields.length; i++){
obj[fields[i]] = someBulkOfData;
}
when logged in the console, obj will output
{
table_name[field_name] : {...},
tabke_name[field_name_2] : {...}
}
This works all fine, until I pass the object through PHP by jQuery.ajax().
When I receive my request in PHP, the array looks as follow:
[
['table_name[field_name'] => ...,
['table_name[field_name_2'] => ...
]
So what happens here is that somewhere between sending the AJAX-request and receiving the data in PHP, the last square bracket of every key dissappears.
Could someone explain to me why this happens, and if there is a neat way to solve this problem?
I have one criteria for the solution, and that is that I cannot change the keys (as in something like 'table_name\[field_name\]').
have you tried using $.serialize()?
use serialize to turn a javascript object into a string that can be transmitted with AJAX easily - like this:
var ajaxableString = $(obj).serialize();
You could solve that issue by restructuring your JS object:
{
table_name : {
field_name_1 : {...},
field_name_2 : {...}
},
another_table : {
...
}
}
That way you avoid that weird naming convention.
Also, I suspect you are hiding something from us. There is something (an operation) between the this and PHP, maybe somewhere in your AJAX code, that you are not telling us. Maybe you are serializing this object into a string and passing the string as one query parameter to the server. This serialize step might be the cause.
But just to be sure, you can check the Net section of the debugger and check the request headers if the data sent is formatted perfectly.
As far as I know, jQuery.ajax accepts a JS object as data, and perfectly converts it into querystrings. By that, you don't need to serialize it manually.
The solution is, thanks to #fab , to encode the data with JSON:
$.ajax({
data : {
obj:JSON.stringify(obj)
},
...
});
In PHP:
json_decode($_REQUEST['obj']);
This will output a perfectly nice stdClass object, with preserved keys.
It's embarrassing to have to ask, but I freely admit I'm an unseasoned Javascript developer, and I just can't figure this out. Hopefully, this will be dead simple for someone else, and I want to thank everyone here ahead of time for the help this site continually provides me.
A couple days ago, I asked this question, and am no longer getting that error. But I've run into a wall trying to actually access the data stored in the variable. My JSON looks like this:
[
{"id":"1","name":"Bob","haircolor":"Brown"},
{"id":"2","name":"Carol","haircolor":"Red"}
]
It's going into a variable like this:
var people=[];
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
people.push(data);
});
Thanks to initializing people as an array, I no longer get any error messages. But I can't access the contents of people, either. people.length returns a 0, and people[0] and people[1] are undefined.
It's there, I know it's all there, but I'm having a devil of a time figuring out where.
people only gets values after the ajax event happens.
Call some callback function after you put the data into the people array.
Try with this: http://jsfiddle.net/hUq7k/
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
$.each(data, function(i, people){
console.log(people.id); //<------this should output "1, 2"
});
});
make sure you are getting the response data.
The following should work, if the server is actually returning the expected JSON:
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
var people = data;
alert("people.length: " + people.length);
if (people.length > 0) {
alert("people[0].id: " + people[0].id);
}
});
The following should not work, i.e., people will be undefined, because $.getJSON is an asynchronous method and this code is attempting to access people before the AJAX operation has completed.
var people;
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
people = data;
});
alert("people.length: " + people.length);
if (people.length > 0) {
alert("people[0].id: " + people[0].id);
}
I have a PHP page that processes some information when a button is pressed. One of this information is to process a query. I then want the results of the query to be put into a table in another page. I know how to put query results into a table, but I don't know how to pass them row by row to a table on another page. Can anyone help or point me in the right direction?
If I understood this correctly, you'll need AJAX (and, by requirement, JavaScript) for this. What you want to do is call your generation function and have it return a format that you can parse (JSON, XML, you name it).
From there, you'll append it to your table using JavaScript's DOM manipulation functions.
The generation part
Assume that you're getting your data in an array format as follows:
$row = array('column 1','column2');
You'll be getting tons of rows like these, or just one - we'll write the script to handle both cases without requiring a rewrite. Every time you get a row, add it to a non-associative array , call it $RowArray. So, on every row, you'll be calling $RowArray[] = $row;.
You now have the PHP side almost done - all you need to do now is to echo it back to the client. Make sure you echo nothing else but this: echo json_encode($RowArray);. This will format and serialize your array to be a perfect JSON object.
The JavaScript side
We'll assume jQuery for simplicity. Your aim will be to read the JSON object and add rows to a table. We'll assume that the table has ID #MyTable.
The AJAX call is done as follows:
$.ajax({
url: "your_url.php",
dataType: "json",
type: "post",
success: function(d) {
// Your code here
}
});
The success handler will be triggered when the object has been successfully parsed, and the variable d will be the object. This object will be a JavaScript array where each element is an object. All you need to do now is to loop through d and create a row per entry!
success: function(d) {
for(var i=0; i < d.length; i++) {
var newRow = $("<tr></tr");
for (var k in d[i]) {
newRow.append($("<td></td>").text(d[i][k]));
}
newRow.appendTo($("#MyTable"));
}
}
Voila, dynamic AJAXified table in six lines!
ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})
Not really looking for code examples here, just concepts.
I have three sections on a page now that are being updated via three separate AJAX calls to PHP scripts, which return JSON. What would be the easiest way to condense these three calls into one larger call and receive the responses back on the client in JSON? How would I separate the responses on the client so I can manipulate the response data based on what information is sent back?
I like Cris' method, but think I can provide a little improvement. As you already have 3 seperate entities, to reduce the need for recoding everything, you could do something along the lines of combining you PHP into one file via include 'page.php' and sending an object back via JSON with properties named for what each of them do (lets say "names", "dates", and "fuzzyThings"). Your client code to send the request would then simply have all the arguments your 3 functions sent individually being sent in one request. The returned JSON would then look something like this (put your objects/arrays/whatever in the commented areas):
{
"names" : {/*stuff needed for names goes in here*/},
"dates" : {/*stuff needed for dates goes in here*/},
"fuzzyThings" : {/*all fuzzy things goes in here*/}
}
Once you get this to the client side, as I assume each may already have a function (or set of functions) to deal with it's return data, you should be able to call them in this manner:
function handler(retText) {
var returnedObject = eval(retText);
doStuffWithNames(returnedObject.names);
doStuffWithDates(returnedObject.dates);
playWithFuzzyThings(returnedObject.fuzzyThings);
}
Also, on the PHP end you can make a unified PHP page (without recoding anything hopefully) via:
<?php
echo '{';
echo '"names":{';
include 'names.php';
echo '},';
echo '"dates":{';
include 'dates.php';
echo '},';
echo '"fuzzyThings":{';
include 'fuzzyThings.php';
echo '}';
echo '}';
?>
Note: You may need to edit the 3 php pages so that they will check the $_POST correctly and without interfering with the functionality of the other pages if you have not already, I prefer the method of if(isset($_POST['whatever'])) { ... } to check that everything was sent correctly, this way, you can include as many as you want, and if there is nothing to do with a php file (i.e. you are not using that section on that page), then it will return a blank property, and you simply will not use it (basically making it a "one-size-fits-all" type of thing).
Hope it works for ya!
You can format your JSON like this:
"user" : [ {
"name" : "Harry",
"hobby" : "Skating"
}, {
"name" : "Dave",
"hobby" : "Scuba Diving"
} ],
"news" : [ {
"date" : "3/13/05",
"title" : "Blah",
"postedby" : "Mike",
} ]
And now in your AJAX response:
var data = eval('('+ xhr.responseText +')'); // Ajax response
var user = data.user[0].name; // Harry
var user2 = data.user[1].name; // Dave
var title = data.news[0].title;
You can use a for loop to traverse the data. In the example above you should now see how you can use PHP to format your JSON with multiple categories (user, news, ect.) and return back everything with only one call. If you would like a more elaborate example please refer to this article as well as this.
I think you have to make a JSON format according to those 3 sections on the page, ID them so that after response you can populate them to those sections.
I personally like the json method but if you're new to json or don't feel comfortable working with it for any reasons there's a jQuery plugin designed specifically for this purpose called jQuery Taconite Plugin
In Rails community there's a third way called RJS which is not that much hot nowadays and feels a little obsolete but still has its own fans. I'm curious if anybody has ported RJS to PHP or not?
this is workimg for me
php code:
//for test
$categoryName = "category";
$idcategory = "1";
$json = "{'productcategory':[{'categoryname':'".$categoryName."','idcategory':'".$idcategory."'}]}";
echo $json;
javascript:
var str = xmlhttp.responseText.trim();
var json = JSON.stringify(eval("(" + str + ")"));
var obj = JSON.parse(json);
alert(obj.productcategory[0].idcategory);
alert(obj.productcategory[0].categoryname);