I am trying to get the quantity of raw materials along with the raw material id. I send recipe id and in response I am getting array like this
[54,"Vanilla Cake Mix",2000] [126,"Water",1200] [1,"Refined Soyabean Oil",200]
Where 54 is Raw Material ID,
Vanilla Cake Mix is Raw Material Name,
And 2000 is Quantity
How do I access each value of this?
My Jquery code is
`$.ajax({
type:"POST",
url:"api_consumption.php",
data: "product_recipe_id="+product_recipe_id+"&quantity="+value,
dataType: "json",
success: function(html)
{
//I want to access the values received in json array format.
}
});`
My PHP code is
$array = array($raw_material_id, $raw_material_name, $raw_material_quantity);
echo json_encode($array);
I tried the each loop but failed.
Sample Output:
When I comment this code dataType: "json",
and alert(html), I get this
Sample Output
If you only need to alert the data, you can just simply convert the data:
success: function(html)
{
let data = JSON.parse(html);
alert(data);
}
But I believe you will need it in a textbox or dropdown, that's when you can loop through each data.
success: function(html)
{
let jsonData = JSON.parse(html);
let data = '';
$.each(jsonData, function(key, value){
data+= '<option value="'+jsonData[key][0]+'">'+ jsonData[key][0] +
' - '+ jsonData[key][1] +' - '+ jsonData[key][2] +'</option>';
});
$('#dropdown-id').html(data);
}
Related
I am a jQuery beginner and hope someone can help me with this and also provide me some explanations.
I have an Ajax call that returns a JSON encoded string with two values for each item, an itemID and an itemVal - an example looks as follows (using console.log):
console.log(data) result:
string(225) "[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"},...]"
The number of items here varies but if an itemID is listed than there is always a corresponding itemVal.
itemID is a unique integer, itemVal is plain text.
Everything works so far but here comes my problem:
For each itemID here I have to do something with the corresponding itemVal, e.g. say just log it to the console or alert it for testing.
I know there are various approaches for this like jQuery.each, $.each, for, foreach etc. but since I just started recently I am not sure how I can iterate through this resp. how I can select the single itemIDs from it.
I tried different approaches, incl. $.parseJSON(data) which failed and it seems the problem is that my input before being decoded is a two-dimensional array instead of a one-dimensional one (I hope I am using the right terms here) which caused them to either return an error or to alert every single character of my string.
Update - failing example as per the answer below
$.ajax({
type: "post",
url: "ajax.php",
cache: "false",
data: {
node: 'fetchCountries',
itemIDs: itemIDs // a list of integers
},
success: function(data){
console.log(data);
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
console.log(value.itemVal);
});
}
});
Update 2 - My PHP:
case "fetchCountries":
$intval_itemIDs = array_map("intval", $_POST["itemIDs"]);
$itemIDs = implode(",", $intval_itemIDs);
$stmt = $conn->prepare("SELECT itemID, en FROM Countries WHERE itemID IN(" . $itemIDs . ") ORDER BY itemID");
$stmt->execute();
$result = $stmt->get_result();
while($arrCountries = $result->fetch_assoc()){
$countries[] = array("itemID" => $arrCountries["itemID"], "itemVal" => $arrCountries["en"]);
}
var_dump(json_encode($countries));
break;
Expected outcome (for testing):
console.log("China");
console.log("France");
console.log("Germany");
// ...
Can someone help me with this ?
Many thanks,
Tim
You have a JSON string representing an Array, which you are parsing into an actual Array. Then you are looping through the array, pushing each element into a new Array (arr).
Perhaps there is some confusion. Hopefully this will shed some light.
// Considering the following JSON string:
var data = '[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}]';
// You can create an Array from this like so:
var theArray = JSON.parse(data);
// Now you have an array with each item being an `object`
// with an "itemId" and an "itemVal". You can loop through
// this array and look at each object like so:
theArray.forEach(function (obj) {
console.log(obj.itemID + ': ' + obj.itemVal);
});
WhistleBlower, I have tested your code on my browser. It worked. Why don't you use header("Content-type :application/json"); too. So, you will not have to parse your JSON string.
var data = '[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}]';
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
console.log(value.itemVal);
});
You're not parsing a string, you're parsing an already-parsed object
just use it directly
var data=[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}];
$.each(data,function(key,value){
console.log(value.itemVal);
});
or/
var arr = JSON.parse(JSON.stringify(data));
$.each(arr, function (key, value) {
console.log(value.itemVal);
});
Update 1:
I think so your php file like
<?php
$array = array( array( 'itemID' => 1, 'itemVal' => 'India'), array( 'itemID' => 2, 'itemVal' => 'usa'), array( 'itemID' => 3, 'itemVal' => 'china'), array( 'itemID' => 4, 'itemVal' => 'uk'));
echo json_encode($array);
//[{"itemID":1,"itemVal":"India"},{"itemID":2,"itemVal":"usa"},{"itemID":3,"itemVal":"china"},{"itemID":4,"itemVal":"uk"}]
?>
your script should be
$.getJSON( "your.php", function( data ) {
console.log(data);
$.each(data, function (key, value) {
console.log(value.itemVal);
});
});
OR
$.ajax({
type: "post",
url: "your.php",
cache: "false",
dataType: 'json',
data: {
node: 'fetchCountries',
itemIDs: youval // a list of integers
},
success: function(data){
console.log(data);
var arr = JSON.parse(JSON.stringify(data));
$.each($(arr),function(key,value){
console.log(value.itemVal);
});
}
});
OR
$.ajax({
type: "post",
url: "your.php",
cache: "false",
dataType: 'json',
data: {
node: 'fetchCountries',
itemIDs: youval // a list of integers
},
success: function(data){
console.log(data);
$.each($(data),function(key,value){
console.log(value.itemVal);
});
}
});
As simple as this!
$.each($(data),function(key,value){
console.log(value.itemVal); //place alert if you want instead of console.log
});
iterate through the obtained result and get itemVal value of each item
DEMO HERE
UPDATE
Add dataType option to your ajax and return type from php should be json and I hope you are doing that!
$.ajax({
type: "POST",
url: "ajax.php",
cache: "false",
dataType:'json', //Add this
data: {
node: 'fetchCountries',
itemIDs: itemIDs // a list of integers
},
success: function(data){
console.log(data);
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
console.log(value.itemVal);
});
}
});
and return from your php should be echo json_encode(result);
Thanks to everyone for the help with this.
Since all other approaches made sense to me but still failed I did some more research on this and finally found what was causing this.
The issue was indeed on the PHP side and the accepted answer on the following post did the trick - since I added this to my PHP everything else on the JS side is working fine and I don't even need the dataType: "JSON" there:
dataType: "json" won't work
As per this post the solution for my case is the following - kudos to Jovan Perovic:
<?php
//at the very beginning start output buffereing
ob_start();
// do your logic here
// right before outputting the JSON, clear the buffer.
ob_end_clean();
// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>
Thanks again.
My experience with jQuery is very limited, and im on a very steep learning cure.
I have a dynamic form which is generated based on main and sub menu, placing marker points in each row which has an inputfield, I have managed to create a loop which looks for all the marker points and return the field_name and the field_value of any input field.
$('td[edit="1"]').each(function(i, el) {
field_name = $(el).attr('fieldname');
field_val = $('#'+field_name).val();
alert(field_name + " = " + field_val);
});
What I am having trouble with now, is converting this in to an array or JSON and pushing it to a PHP file which can then pick up the results.
Here is an example of how I currently submit a forms data to a PHP file, however is not dynamic as I have to specify which fields and values I want to send.
$.ajax({
type: "POST",
url: "form.php",
data: {
title : title,
age : age
}).done(function(data) {
results = $(data).find('data').html();
}).fail(function() {
alert("error");
}
);
If i have clearly understand your problem then You will have to use serialize method of jquery to send fields to php file. You can do like
data:$('form').serialize(),
It will send all the fields to php file.
As data you can user Jquery on the form to create an array of all the data:
https://api.jquery.com/serializeArray/
$.ajax({
type: "POST",
url: "form.php",
data: $('#idOfForm').serializeArray()
}).done(function(data) {
results = $(data).find('data').html();
}).fail(function() {
alert("error");
});
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)
Below is my AJAX code. I've written the questions in the comments.
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data: datastr,
success: function(arrayphp) {
//here one by one text is being received from php from within a loop
//each text item is getting displayed as link here
//it is OK that text is getting displayed as link
//BUT the problem is that all the text returned from php are getting displayed as
//one link i.e between one "<a></a>"
//I WANT THAT EACH TEXT SHOULD BE DISPLAYED AS SEPERATE LINKS
//AS EACH TEXT IS GETTING RETURNED FROM WITHIN SEPARATE ITERATIONS OF PHP LOOP
var link = $('<font color="red">' + arrayphp + '</font>');
linkclass = link.attr("class");
$(".searchby .searchlist").append(link);
}
});
What to do?
Php throws everything at once to the ajax success function... You need to use json_encode on the php array and echo it to pass it as json array.
<?php
$return = array();
foreach($array as $key=>$value){
//Do your processing of $value here
$processed_value = $value;
array_push($return, $processed_value);
}
echo json_encode($return);
?>
In the ajax call set the dataType as "json" for it to parse the data passed from php as json array. Loop across the array received by using jquery each.
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data: datastr,
dataType: "json",
success: function(arrayjson) {
$.each(function(arrayjson, function(i, processed_value) {
var link = $('<font color="red">' + processed_value + '</font>');
linkclass = link.attr("class");
$(".searchby .searchlist").append(link);
});
}
});
I want to post an array using Jquery Ajax to php. Is this possible ?
Thanks
EDIT:
I tried following :
type: "POST",
url: "path",
data: "styles=" + strstyles + "&templateId=" + custTempId, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
but, styles hold no data. I spent a lot of time, before adding data type to the declaration. What can be the reason for "styles" being posted as null ?
Second Edit
I want to post style sheet dom object and save the class names and properties to DB. With the above edit, adding datatype did not help. I think it is b'coz the string is not in json format as follows -
{"a":1,"b":2,"c":3,"d":4,"e":5}
As the my string has double quotes, it is not following the format, and I think that's the reason, I'm getting an empty array. How can I handle this ?
With jQuery it is very easy:
$.ajax({
type: "POST",
url: location.href,
data: data,//data is array
dataType: "json",
success : function () {
// Something after success
}
});
You can use in following way too
$.ajax({
type: "POST",
url: location.href,
data: ({'data[]' : array}),//array is array
dataType: "json",
success : function () {
// Something after success
}
});
if you don't want to use JSON, PHP can automatically create arrays from Html forms
so you could do something like this:
type: "POST",
url: "path",
data: "styles[key1]=" + strstyles.val1 + "&styles[key2]=" + strstyles.val2 + ... + "&templateId=" + custTempId
...
that is if you want to have an associative array in php, but if you want just an array you could do
data: "styles[]=" + strstyles.val1 + "&templateId=" + custTempId
In POST call you dont use & , So your code should be
something like
type: "POST",
url: "path",
data: {styles: strstyles , templateId: custTempId}, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
is that point clear?
So coming to my solution,
you should download JSON parser from http://www.mediafire.com/?x6k3su7bbdrcta8.
Create object strstylesOBJ, code: var strstylesOBJ = {};
insert your strstyles array into strstylesOBJ and stringify it then pass to it in your post call
strstylesOBJ.styles = strstyles;
strstyles = JSON.stringify(strstylesOBJ);
In PHP code you refecth your array using $strstyles = json_decode($_POST['styles']);
do var_dump($strstyles) and please tell what was the output.
regards
Ayaz Alavi