How can I create a JSON object dynamically? - php

I would like to create a JSON object dynamically. The JSON object will have to be as the follows:
{
$capa:[$fila['test_name'],...etc],
.
.
.etc
};
The key and value will be retrieved through a MySQL query.
This is what i'm doing:
$array_container= array();
while($fila=mysqli_fetch_assoc($sql)){
$format_org=str_replace(" ","_",$fila["organization"]);
$format_eval=str_replace(" ","_",$fila["EvaluationType"]);
$format_test=str_replace(" ","_",$fila["test_name"]);
$CapaEnviar=$format_org.$format_eval;
$array_container[] = array($CapaEnviar => $fila['test_name']);
}
echo json_encode($array_container,true);
Using the previous code, I can retrieve a JSON object with duplicate keys.
This code is an answer for an AJAX request, so once the JSON object has been created correctly, I will send back this JSON object in order to retrieve the key and value, so I will have to retrieve separately the key and value.

From your comment,
...the results of this array is as the follows: [{"TEST1":"valueT1"},{"TEST1":"otherValue"}] and what i'm looking for is to have a json like this: [{"TEST1":['valueT1','otherValue']}] as you can see, i want to avoid duplicates keys.
Solution:
In your while loop, change this line
$array_container[] = array($CapaEnviar => $fila['test_name']);
to
$array_container[$CapaEnviar][] = $fila['test_name'];
Update:
how i can retrieve this key and their values through ajax?
Since you're expecting a json object from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, loop through the json result to get (key, value) pairs
Here's the reference:
jQuery.ajax()
So your AJAX skeleton code should be like this:
$.ajax({
type: 'POST',
url: 'yourpage.php',
dataType: 'json',
cache: 'false',
beforeSend: function(){
},
success: function(data){
$.each(data, function(key, value) {
alert("Key:" + key + ", value: " + value);
});
},
error: function(){
// error
}
});

Related

json_decode returns NULL, json_last_error throws 0

I'm passing a simple JSON array with 4 words to PHP. I want to store that array in a database after I serialize it. Since it's an Ajax call I can only investigate any echoed values by json_encode and alerting them in AJAX success function.
Here's my code:
var jsonString = JSON.stringify(ans);
//if I alert jsonString - it shows the proper array
$.ajax({
type: "POST",
url: "script.php",
data: jsonString,
cache: false,
success: function(data){
alert(data);
},
error: function(){
alert("error");
}
});
That's what I do in PHP with the array:
$answerAr = json_decode($_POST['data']);
$answers = serialize($answerAr);
If I echo the json_encode($answerAr) it alerts NULL in Ajax and $answers turns into 'N;'
Json_last_error returns 0.
If you're posting data directly to PHP, you'll have to use php://input and parse that; data given in JSON isn't form data, and wont auto-populate the request superglobals ($_GET, $_POST).
$data = json_decode(file_get_contents("php://input"));
Most frameworks do this transparently for you and populate a request object with data in it. You should probably check if the request sends JSON data in the body via headers (Content-Type, Accept: application/json, etc)
Alternatively, you can change your AJAX call to give it an array key:
$.ajax({
data: {data: jsonString},
// etc
});
Which will then be accessible as $_POST["data"]
Change your ajax data attribute to like this and try
data: {json: jsonString}
and in the php script you can access it by
$answerAr = json_decode($_POST['json']);

How can I return an array/json object containing json objects through an ajax php call?

Basically what I'm trying to do is returning the results of a mysql query. I know how to put each row of the query results into its own JSON object, now I'm just struggling with a way so that if there's multiple lines of results to return it to my jquery.
In my jquery I call the $.ajax() function and I don't have any issues with that. My problem lies within the success part, where I want to be able to do something like the following:
$.ajax ({
type: "POST",
url:"select.php",
data: {columns : "*",
table : "tbUsers",
conditions : "" },
success: function(results) {
foreach (results as obj)
{
JSON.parse(obj);
$("#page").html(obj.id + " " + obj.name);
}
}
});
I want to be able to iterate through the result variable like an array of JSON objects. The results variable is a string that consists of All the output of the php file. So let my question rather then be, how can I change it so that the function gets an array or how do I change it into one?
My php file currently returns something like this:
[{"0":1, "1":"name1", "id":1, "name":"name1"} , {"0":2, "1":"name2", "id":2, "name":"name2"}]
From the php you can use
echo json_encode($result); // result may contain multiple rows
In your success callback you can use
success: function(results) {
var htmlStr = '';
$.each(results, function(k, v){
htmlStr += v.id + ' ' + v.name + '<br />';
});
$("#page").html(htmlStr);
}
A Demo to help you understand.
Try something like:
$.ajax ({
type: "POST",
url:"select.php",
data: {columns : "*",
table : "tbUsers",
conditions : "" },
dataType: "json",
success: function(results) {
for( var i in results) {
$("#page").html(results[i].id + " " + results[i].name);
}
}
});
Note the dataType: "json" - This will parse it all into a JSON object(s) for you.
quote from your question
I know how to put each row of the query results into its own JSON
object
you need to send one big json string instead of multiple smaller ones. You'll not able to loop through the response because it is not a single json string (it are multiple json strings).
also it is better to chain the ajax callbacks because using them as options will be removed from jquery in the future.
$.ajax({
url: ' your/url ',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
http://api.jquery.com/jQuery.ajax/
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
your code for their eventual removal, use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
You can just return one big JSON result. Because each of your JSON objects can be wrapped in another.
The JSON you return would then be an array of objects (whatever they may be)
{ "objects": [(first object), (second object), ... ] }
Then in your success function, you can iterate over each object and update the page:
var obj = JSON.parse(results);
jQuery.each(objs, function(i, obj) {
$("#page").html(obj.id + " " + obj.name);
});
return Because wrapped success Then in your success function,you can iterate over each object and update the page You can just return one big JSON result.Because each of your JSON objects can be wrapped in another. The JSON you return would then be an array of objects (whatever they may be)

jquery : pass an array in ajax

I have a form with several identical fields:
<input type="text" id="qte" value="" name="qte[]">
How transmetre the array in my file processing?
I noticed that the array sent ajax became a string.
$("#form_commande").submit(function(event){
var qte = $("#qte").val();
if(qte== '')
{
$('#qte_message').html("KO QTE");
}
else
{
$.ajax({
type : "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
success : function(){
$('#form_commande').html('<p>OK</p>');
},
error: function(){
$('#form_commande').html("<p>KO</p>");
}
});
}
return false;
}
Get value in jquery like:
$("#form_commande").submit(function(event){
var qte_array = new Array();
$('input[name="qte[]"]').each(function(){
qte_array.push($(this).val());
});
if(qte_array.length== 0)
{
$('#qte_message').html("KO QTE");
}
else
{
$.ajax({
type : "POST",
url: $(this).attr('action'),
data: {qte:qte_array},
success : function(){
$('#form_commande').html('<p>OK</p>');
},
error: function(){
$('#form_commande').html("<p>KO</p>");
}
});
}
});
and get it in php like:
$qte = $_POST["qte"];
here qte an array
This returns the input textbox object:
$("#qte");
This returns the value of the input textbox object:
$("#qte").val();
Remember you asked for DOM object by id, and this by definition returns only one.
Please read this topic:
JQuery - Reading an array of form values and displaying it?
In short you should iterate with tag name="qte[]" instead of using ids. In DOM you cannot have two different objects with different ids.
var qte_array = new Array();
$('input[name="qte[]"]').each(function(){
qte_array.push($(this).val());
});
After this you have all the values of qte[] array in one object - qte_array. You can later serialize this array to JSON and then pass it as a string.
ALTHOUGH - you shouldn't need to do all those things. You can send ajax request directly with your form, all those data in these inputs will be transferred anyway. You just need to handle them correctly server-side.
id is unique, you can't have more fields with the same ID.
By the way you should convert values to JSON and pass them to Ajax

Splitting a JSON Array with JQuery that has been returned by PHP

I am new to JQuery and the whole JQuery to PHP back to JQuery process.
So i have a simple ajax JQuery script:
$.ajax({
type: "POST",
url: "includes/calc.php",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
This goes to a PHP script and then I return a value, using a simple echo
echo $newprice;
The success function above uses this as 'data'. This all works and is fine.
But what if I want to return more than one value.
I think I can used json_encode();
As I understand it something like:
$dataset = array($var1, var2, var3);
echo json_encode($dataset);
But say I have two values, how do i put them both into the JSON and then how do I split them on the other end.
So say 'data' is an array, how do I tell JQuery to split it?
Sorry if this is simple
If you specify the dataType option for .ajax() as json, jQuery will automatically parse the JSON string returned by the call into an appropriate javascript object/array.
So your call might look like this:
$.ajax({
type: "POST",
url: "includes/calc.php",
dataType: "json",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
Now, let's say the response from your PHP script is a JSON string representing an object like this:
{"key1":"value1","key2":"value2"}
In your success handler you can simply access this as an object like this:
success: function(data){
alert(data.key1);
alert(data.key2);
}
Or, if the returned JSON string represents an array like this:
["value1","value2"]
Then you can access the array values in the success handler like this:
success: function(data){
alert(data[0]);
alert(data[1]);
}
If you do not want to add the dataType option, you can also opt to manually parse the returned JSON string into an object/array like this:
success: function(data){
var dataObj = JSON.parse(data);
alert(dataObj.key1);
alert(dataObj.key2);
}
$.ajax({
type: "POST",
url: "includes/calc.php",
datatype : 'json',
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data.firstvalue);
alert(data.secondvalue);
}
})
please look at that datatype. now the respose need to be json.
In your php user json_encode instead of echo.
$firstvalue = 'your first value';
$secondvalue = 'your second value';
echo json_encode(array('firstvalue' => $firstvalue,'secondvalue' => $secondvalue));
There are many ways to organize data in a JSON object. The simplest is to return a linear array of strings or numbers. Use http://jsonlint.com/ to test your data to see if it's valid JSON, or just feed a PHP array (linear or associative) into json_encode.
If data is a JSON linear array, you can treat it like any other JavaScript array in your success callback:
var first = data[0]; // first element
var second = data[1]; // second element
implode your php variables with a symbol or any custom data
like
$var[0] = '1st variable';
$var[1] = '2nd variable';
$var[2] = '3rd variable';
echo implode('_SPLIT_',$var);
Now in jquery success function
split the response with 'SPLIT'
as
var response = data.responseText.split('_SPLIT_');
var variable1 = response[0];
var variable2 = response[1];
var variable3 = response[2];
and assign as your wish

POST, AJAX, and PHP : JSON submission

Ok, so here is my JS/jQuery code, my rate.php file simply has a print_r($_POST) in it. The problem is, the $_POST is accepting rated as the string "Array", rather than the actual array as I have defined it. How do I correct this code so PHP will recognize the JSON input as a proper array, rather than a string?
var rated = {"key" : key , "value" : value};
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: {
"rated" : rated
},
success: function(data) {
alert(data);
}
});
This is the output message I'm getting:
Array
(
[rated] => Array
)
Fatal error: Only variables can be passed by reference in .../ajax/rate.php on line X
EDIT: There are actually more variables that rated, but none of them are arrays (thus there isn't an issue with them), so I cut them out of the code above for brevity sake.
When passing JSON data to your php script through ajax I would recommend string encoding the JSON data and then parsing it on the server side.
var rated = {"key" : key , "value" : value};
var rated_encoded = JSON.stringify(rated);
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: {
"rated" : rated_encoded
},
success: function(data) {
alert(data);
}
});
Then you should be able to access the POST variable in your PHP script using $_POST as with any other scalar value. Once you have the JSON string 'rating_encoded' on the server-side, parse it to an associative array using PHP's json_decode().
if(isset($_POST["rated"])){
$rated_json = $_POST["rated"];
$JSONArray = json_decode($rated_json, true); //returns null if not decoded
//Values can now be accessed like standard PHP array
if($JSONArray !== null){
$key = $JSONArray["key"];
$value = $JSONArray["value"];
}
}
I've found that this method is very effective for transferring javascript object data to the server and vice versa (using PHP's json_encode() to translate PHP arrays into valid javascript objects)
It is a proper array, just not what you expect it to be. What you likely want can be achieved by simply passing rated to the data parameter as is. I.e.
var rated = {"key" : key , "value" : value};
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: rated,
success: function(data) {
alert(data);
}
});

Categories