I have array in my php file:
$invoices_arr = [];
foreach ($invoices as $key=>$invoice){
$invoices_arr[$key]['id']=$invoice->get_id();
$invoices_arr[$key]['code_text']=$invoice->get_code_text();
$invoices_arr[$key]['invoice_name']=$invoice->get_invoice_name();
$invoices_arr[$key]['status_invoice']=$invoice->get_status_invoice();
$invoices_arr[$key]['attachments']=$invoice->get_attachments();
}
echo json_encode(['invoices'=>$invoices_arr]);
My ajax call:
$.ajax({
data:{lead_id:$("#lead_id").val()},
url: sJSUrlGetAllLeadInvoices,
success: function (data) {
var obj = jQuery.parseJSON(data);
$("#all_invoice_table tbody").empty();
$(obj.invoices).each(function(key,value){
$('#all_invoice_table').append('<tr><td>'+value.invoice_name+'</td><td class="invoice_status">'+value.status_invoice+'<td>attt</td><td><button id="'+value.id+'" class="edit_invoice_'+value.id+'">Edit invoice</button</td><td><button class="send_invoice_btn_'+value.id+'">Send invoice</button></td><td><img class="delete_invoice_'+value.id+'" src="/images/icons/delete.gif"></td><td class="invoice_hidden_column_'+value.id+'">'+value.code_text+'</td></tr>');
});
}
});
In field value.attachments there is php serialize array, for example, string "a:1:{i:0;s:36:"../../pdf_invoices/2017-10-10015.pdf";}" .
How can I convert this string to array in js?
I try do it:
var mas=JSON.parse(value.attachments);
But I get error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
How can I solve it? Thanks for any help.
Maybe you should unserialize inside PHP code before encode in json
You don't need to parse the result with jQuery.parseJSON because jQuery do it for. If you inspect data using console.log() you will see that is a Javascript object ready for to use.
You need to pass datatype as json.
you can use jQuery parse method for parsing json response.
datatype:json
Related
I'm having this collection of objects which are inside a html text area:
{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...
...
Is there a way to send the whole collection to node js and iterate through it to get values of objects?
My AJAX code:
$.ajax({
type: "POST",
url: "https://example.com/nodeapp",
data: '['+document.getElementById("list").value+']',
success: function(data) {
console.log(data);
}
});
I tried to do a foreach on req.body, but it doesn't seem to work:
var arr = req.body;
arr.foreach(element=>{
console.log(element.email);
})
Gives the error:
TypeError: arr.foreach is not a function
At first , you have to parse the body by using JSON.parse() function .
Like this :
var arr = JSON.parse(req.body);
arr.forEach(element=>{
console.log(element.email);
});
The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .
I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:
'[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},
{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...]'
Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:
{
"<<the array in string format>>" : ""
}
How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)
I'm trying to retrieve the JSON data given below but I'm unable to.
Since I'm using Javascript Ajax success function, when I try doing alerts with the code,
$.ajax({
type:'GET',
url:myURL,
success : function(data) {
alert(data);
//{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}
}
});
I am retrieving the below JSON data.
{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}
But when I try trying to get the value of mainIsActive using:
alert(data.object1.mainIsActive);
I am getting the error in the console:
"Cannot read property 'mainIsActive' of undefined at Object.success (:143:30)"
Can you please help? I also attached the JSON image so you can understand the structure better.
The JSON data will be available in object structure once you have parsed it using
JSON.parse(StringYouWantToParse)
This code seems to work properly:
var x = '{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}';
var data = JSON.parse(x);
alert(data.object1.mainIsActive);
I would like to update my chart using ajax but the setData method need an array and I only have a string so it doesn't work.
here is my code
$(".chooseService a").click(function() {
$("span.currentService").html($(this).html());
$.get('http://localhost:8080/dashboard/ws/charge/repartition/jour/'+$(this).html(),
function(data) {
// setData (Array<Mixed> data, [Boolean redraw])
chartDay.series[0].setData(data);
});
});
data is a formatted string like
[[1356995280000,183.0],[1356995520000,573.0],[1356995760000,243.0]]
Would someone have any idea ?
You may parse your JSON string into the variable data.
data = JSON.parse(data);
If you have trouble using the JSON method:
http://caniuse.com/json
when you return the result from the server side you can format the content to be a JSON type
header ('Content-type: text / json');
header ('Content-type: application / json');
Then you can convert this result to evaluate it properly the javascript from the client side.
jQuery.parseJSON (this.responseString);
If you want an array like this in can use this reference
I am using the Django framework to build a website.
In the Python file (views.py) I send to the Javascript function an array that has been transformed to json data
Python:
json_data=[1,2,3]
return HttpResponse(json.dumps(json_data), mimetype='application/json')
Then, in Javascript I display the json data in the html.
JavaScript:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
$('.square').append('<p> ' + json_data + ' </p>');});
};
So far everything works. However, I would like to convert the "json_data", which I believe is a string, into an array.
I tried doing this:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var array = json_data.split(',');
$('.square').append('<p> ' + array[0]+ ' </p>');});
};
Unfortunately, this doesn't work.
Can someone please explain to me what could I do to convert the "json_data" variable into an array in JavaScript?
Thanks a lot.
When you send around data in JSON format it is a string (the main data), but a string formated in such a way that it's easy to recover the data with the original types (ie, your array). Javascript and jquery have different ways to do that. Using jQuery,getJSON is probably the most direct:
http://api.jquery.com/jQuery.getJSON/
You can use your browsers javascript console to see what exactly do your JS variables look like.
"this doesn't work" it's too vague...
Anyway, if I understood your problem, you are dealing with a string, not a JavaScript array... you have to evaluate the data returned from the ajax call:
var theJavaScriptArray = eval('(' + json_data + ')');
or better... use jQuery.ajax and specify json as dataType: jquery doc
In the end, thanks to Zah I discovered the "javascript console", which I didn't know it existed.
I could see that the error was that the "json_data" variable was not a string.
So this is the solution that worked for me:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var b=json_data.toString().split(',');
$('.square').append('<p> ' + b[0] + ' </p>');
});
};
There is a shorthand in jQuery to parse the json string automatically: jQuery.getJSON()
$.getJSON('/xhr_test/json/', function(data) {
console.log(data); // Here data is already a JavaScript object
});
This is basically the same as:
$.ajax({
url: "/xhr_test/json/",
dataType: "json",
success: function(data) {
console.log(data); // Here data is already a JavaScript object
}
});
Which again is about the same as:
$.ajax({
url: "/xhr_test/json/",
success: function(data) {
var json = $.parseJSON(data); // Here data is a string
console.log(data); // And json is JavaScript object
}
});
I am using jquery 1.5. I am using getJSON method to get the json output..
$.getJSON('/products/list/', function(data) { ..... });
The json is structured like..
{"books":["title_of_books1","title_of_books2","title_of_books3"],
"discs":["title_of_discs1","title_of_discs2"],
etc....,
}
Is there a way to convert this into an array using jquery. So I can access it like books[0]
I appreciate any help.
Thanks.
Assuming your JSON syntax is correct, the data would be automatically converted to a native object by jQuery, so inside function (data) { ..... }, you would refer to data.books[0]:
$.getJSON('/products/list/', function(data) {
alert(data.books[0]);
});
use the parseJSON api of jquery.. http://api.jquery.com/jQuery.parseJSON/