AJAX save JSON array into multiple JS variables - javascript

I want to get multiple Values from a mySQL Query and save it into multiple JS Variables.
This is my JS file with my AJAX Code:
$.ajax({
async:false,
url: "get_data.php",
type: "POST",
data: {
d1: 'd1',a1: 'a1'
},
dataType: "JSON",
success: function (data) {
$("#result").text(JSON.stringify(data));
}
});
With $("#result").text(JSON.stringify(data)); i get this Result:
[{"d1":"2","a1":"3"}]
Now I want to save each Value into separate JS Variables (e.g: d1 into var default; a1 into var second)
How can i save my Values in seperate JS Variables?

See this
var data = '[{"d1":"2","a1":"3"}]';
var obj = JSON.parse(data);
console.log(obj[0]);
document.write("d1 = " + obj[0].d1);
document.write(" // ");
document.write("a1 = " + obj[0].a1);
Write this code in success of your $.ajax.

Related

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

How to convert array in json format in jquery

I am trying to send ids(as array) in json format for that I used JSON.stringify(ids); and stored in variable z I am using array at server side to get values.
var ids = $("#infolist li div.No").map(function() {
return this.id;
}).get();
alert(ids);
console.log(ids);
if (ids) {
var z = JSON.stringify(ids);
alert(z);
$.ajax({
url: "UpdateNotification",
dataType: "json",
data: {ids: z},
success: function(data) {
console.log(z);
alert("success " + data.st);
}
});
}
console.log(ids) is showing ["25","27","28"].
console.log(z) is showing ["25","27","28"].
My problem is it is not calling server side method.
I may be due to not proper json format of data.
How to make it correct?
EDIT
At url If I use directly
http://localhost:8084/tt/UpdateNotification?ids=%5B%2225%22%2C%2227%22%2C%2228%22%5D
No server side method is called. This is the output of JSON.stratefy(ids).
But If I use below
http://localhost:8084/tt/UpdateNotification?ids=%2225%22&ids=%2226%22&ids=%2227%22
This calles ther serverside method
No need for var z = JSON.stringify(ids);.
Just do:
// ...
data: { ids: ids },
// ...

Getting json array to create products index problems using Php, json, JS and JSON

Having a few problems creating a products index.
It looks like you're pushing down html as well in the products.php page. Make sure the output of the php that you're retrieving from only returns JSON.
Also, check the syntax on your script:
$.get({
type: "GET",
url: "products2.php",
data: 'id=' + userid,
dataType: "json",
success: function (data) {
document.getElementById("name").innerHTML = data[0];
document.getElementById("decription").innerHTML = data[1];
document.getElementById("price").innerHTML = data[2];
document.getElementById("stock").innerHTML = data[3];
}
});
You were using $rows but attempting to access data. Adding a simple console.log(data); in the success function will dump the results to the console in chrome/firefox so you can see what is being returned. (Be sure to check the network tab as well, as it can give you some tips as to why the data isn't being properly fetched.)
I've done something similar and this worked fine for me:
<?php
$array['status'] = 0;
...
echo json_encode($array);
Populate the array with whatever you need.
And then:
$.ajax({
type: "type",
url: "url",
data: {
data: data
},
success: function (data) {
console.log(data.status);
}
});

Passing array to ajax

How I can pass a list or array to ajax?
var intArray = [];
$.ajax({
url: '/User/GetGroup',
type: 'GET',
data: intArray,
traditional: true,
success: function (result) {
$(result).each(function () {
var id = this.Id;
var nome = this.Nome;
$("#Default").append($('<option></option>').val(id).html(nome));
});
}
});
Like this way, still doesn't work.
Thanks!
You can pass the array like that, or use data: JSON.stringify(intArray). In ASP.NET MVC, we use the JSON 2 javascript library, available in a Nuget package.
success: function (serverResult) {
// create an object array from json string.
var results = JSON.parse(serverResult);
for ( var item in results){
$("#Default").append($('<option></option>').val(item.Id).html(item.Nome));
}
}
I used data: { i: intArray }, and works too!

Using $.ajax to return HTML & turn it into JavaScript array

var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "html",
success: function (data) {
var dataObj = data.replace(/"/g, '"');
console.log(dataObj);
}
});
I'm grabbing the contents of an HTML page, and the contents on that page is super simple. It's just an "array", although it's plain text so when it returns, JavaScript is treating it as a string instead of an array. This is all that's on that HTML page:
[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
Without replace the "'s, a console.log spits out [{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
So my question is, how can I turn that HTML string (that's already in "array" form) into an actual array?
You can use JSON.parse
JSON.parse(dataObj);
You can parse the returned HTML fragment as JSON:
JSON.parse(dataObj);
Change "dataType" to "json" and it will convert it for you:
var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "json",
success: function (data) {
console.log(data);
}
});
If it is returning the " instead of ", then I would change the AJAX return page to make sure it is doing a proper JSON response.

Categories

Resources