Jquery not passing array via ajax - javascript

I am trying to send javascript array to php via ajax, but it is not sending, here is my code
var ArrayAmounts = new Array();
ArrayAmounts["P1"] = "16150";
$.ajax({
url:"myajax",
cache:'false',
type:'POST',
data:{Arr:ArrayAmounts},
success: function(data){
console.log(data);
},error: function(xhr, AjaxOptions, ThrownError){
ShowMessage(xhr.responseText);
}
});
but when I am making array like this:
var ArrayAmounts = new Array();
ArrayAmounts[0] = "16150";
it is passing the array, but I want the key as alphanumeric.
please help.

So you don't need an array here, you'll need to use an object like this :
var Amounts = {};
Amounts["P1"] = "16150";
$.ajax({
url:"myajax",
cache:'false',
type:'POST',
data:{Arr: Amounts},
success: function(data){
console.log(data);
},error: function(xhr, AjaxOptions, ThrownError){
ShowMessage(xhr.responseText);
}
});

Your problem is related to the kind of data you are sending because as the documentation says:
"It is converted to a query string, if not already a string. It's
appended to the url for GET-requests. Object must be Key/Value
pairs. If value is an Array, jQuery serializes multiple values with
same key based on the value of the traditional setting"
Official documentation for more details

you can declare the array like this:
var ArrayAmounts = new Array();
ArrayAmounts = ["16150"];
and then your ajax call work normally

Use like this
var ArrayAmounts = {};
ArrayAmounts.P1 = "16150";
var dataArray = {Arr: ArrayAmounts};
$.ajax({
url:"myajax",
cache:'false',
type:'POST',
data: dataArray ,
success: function(data){
console.log(data);
},error: function(xhr, AjaxOptions, ThrownError){
ShowMessage(xhr.responseText);
});

Related

How to parse JSON with multiple rows/results

I don't know if this is malformed JSON string or not, but I cannot work out how to parse each result to get the data out.
This is the data.d response from my $.ajax function (it calls a WebMethod in Code Behind (C#)):
{"Row":[
{"ID1":"TBU9THLCZS","Project":"1","ID2":"Y5468ASV73","URL":"http://blah1.com","Wave":"w1","StartDate":"18/06/2015 5:46:41 AM","EndDate":"18/06/2015 5:47:24 AM","Status":"1","Check":"0"},
{"ID1":"TBU9THLCZS","Project":"2","ID2":"T7J6SHZCH","URL":"http://blah2.com","Wave":"w1","StartDate":"23/06/2015 4:35:22 AM","EndDate":"","Status":"","Check":""}
]}
With all the examples I have looked at, only one or two showed something where my 'Row' is, and the solutions were not related, such as one person had a comma after the last array.
I would be happy with some pointers if not even the straight out answer.
I have tried various combinations of response.Row, response[0], using $.each, but I just can't get it.
EDIT, this is my ajax call:
$.ajax({
url: "Mgr.aspx/ShowActivity",
type: "POST",
data: JSON.stringify({
"ID": "null"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblResErr').html('<span style="color:red;">' + thrownError);
}
});
At the moment I have just been trying to get ID1 value and ID2 value into the console.
EDIT (Resolved): Thanks to YTAM and Panagiotis !
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
data = JSON.parse(data);
console.log(data);
}
Now the console is showing me an array of two objects, and now I know what to do with them !!
First you have to parse the string with JSON.parse
var data= JSON.parse(rowData);
Then you will get object like given below,
data = {
"Row": [
{
"ID1":"TBU9THLCZS",
"Project":"1",
"ID2":"Y5468ASV73",
"URL":"http://blah1.com",
"Wave":"w1",
"StartDate":"18/06/2015 5:46:41 AM",
"EndDate":"18/06/2015 5:47:24 AM",
"Status":"1",
"Check":"0"
},
{
"ID1":"TBU9THLCZS",
"Project":"2",
"ID2":"T7J6SHZCH",
"URL":"http://blah2.com",
"Wave":"w1",
"StartDate":"23/06/2015 4:35:22 AM",
"EndDate":"",
"Status":"",
"Check":""
}
]}
Here I am giving two options either direct retrieve data from data variable or through loop.
data.row[0].ID1
data.row[0].Project
data.row[0].ID2
and so on
OR
use loop,
var result = json.row;
for (var i = 0; i < result.length; i++) {
var object = result[i];
for (property in object) {
var value = object[property];
}
}
Hope this helps.
you may be getting a json string from the web method rather than an actual JavaScript object. Parse it into a JavaScript object by
doing
var data = JSON.parse(response);
then you'll be able to iterate over data.Row

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);
}
});

how to print values in array of deferred objects?

I have the following requests:
var req1 = $.ajax({
type: "GET",
url: url,
dataType : "xml"
});
req1.done(function (resp1) {
$(resp1).find('interest').each(function() {
var interest_id = $(this).find('id').text();
var interest_name = $(this).find('name').text();
var request = $.ajax({
type:"GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page="+ interest_name + "&redirects&prop=text",
dataType: "jsonp"
});
requestsArray.push(request);
});
$.when.apply(null, requestsArray).done(function () {
console.log("entrou");
});
});
But when i get inside of
$.when.apply(null, requestsArray).done(function () {
console.log("entrou");
});
I dont know how to reach the individual responses in requestsArray. how can i do that? i have tried and tried but nothing seems to work.
You can use the arguments object to access an unknown number of values passed to a function:
$.when.apply($, requestsArray).done(function(){
console.log(arguments); //plain arguments object
console.log([].slice.call(arguments)); //arguments turned into real array
});
See MDN docs on the arguments object
Since you are pushing $.ajaxs into your array you might consider getting rid of the additional arguments they will pass like:
var request = $.ajax({
type:"GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page="+ interest_name + "&redirects&prop=text",
dataType: "jsonp"
}).then(function(data, textStatus, jqXHR){
return data; //this will make sure textStatus and jqXHR aren't passed any further
});

AJAX/JS Syntax passing with arrays, Syntax Error

Background
I have a javascript code which passes three values dynamically into JSON for processing... After discussing a previous problem I had with a colleague, he has proposed that the best way to pass multiple variables into JSON would be to define them as an array in javascript, and then pass the object directly into the ajax/JSON. However, after a little trial and error coding, it appears the methodology is not being run correctly by the JSON processor. My question is as follows, in the following two examples, are they functionally the same, and if so, then why would the syntax fail.
Working Code
/* New Syntax: */
var data_id = $(this).data('id');
var data_action = "get";
var column_toact_on = $(this).data('column');
$.ajax({
url: 'xyz.php',
type: 'POST',
data: {id : data_id, action: data_action, column: column},
dataType: 'json',
success: function(data){
alert("Information Passed Correctly");},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus);}
});
Not Working Code
/* old Syntax: */
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObject["column"] = $(this).data('column');
dataObj["action"] = "get"; // "get" or "set"
$.ajax({
url: 'xyz.php',
type: 'POST',
data: dataObj,
dataType: 'json',
success: function(data){
alert("Information Passed Correctly");},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus);}
});
The reason your non-working code is not working..
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObject["column"] = $(this).data('column');
dataObj["action"] = "get";
You create an object, dataObj - thats fine. You assign a property on dataObject (does not exist, you mean dataObject, but the JS interpreter does not know that), which for obvious reasons wont work.
Try this instead.
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObj["column"] = $(this).data('column');
dataObj["action"] = "get";

How to retrieve JSON variables from a AJAX response

When I tried to fetch the values from a JSON response, I stucked up. Here is my code
Code:
$.ajax({
url: 'checkvotes.php',
dataType: "json",
success: function(data) {
// want to fetch UP and DOWN variables from JSON here
}
});
AJAX Response from PHP
{"sample":[{"id":"1","message":"my message","up":"200","down":"34"}]}
$.ajax({
url: 'checkvotes.php',
dataType: "json",
success: function(data) {
var up = data.sample[0].up;
var down = data.sample[0].down;
}
});
Try data.sample[0].up and data.sample[0].down. If in doubt, use this JavaScript to emulate the call:
var data = {"sample":[{"id":"1","message":"my message","up":"200","down":"34"}]};
Run that in a debugger and examine data.
var up = data['sample'][0]['up'],
down = data['sample'][0]['down']
just print a console.log(data) to inspect your json

Categories

Resources