javascript, array of string as JSON - javascript

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.

Related

Empty Array AJAX

So I have searched around a bit in hopes of finding a solution to my problem, but have had no luck.
I am basically trying to pass data into the ajax function, but when it passes it to my php file it only returns an empty array (Yes there are a few topics on this, couldn't find any to fit my needs) , here is the console output: Array ()
Its odd because just before the ajax function I log the data, and it prints out each section with no problems.The posting URL is accurate, works fine straight from my form. I have tried to use response instead of data passed through the function, but no luck their either.
Thanks in advance!
Here is the JS file
$(document).ready(function() {
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = [];
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data); /////THIS LINE HERE ACTUALLY PRINTS DATA
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
return false;
});
});
And here is my PHP
<?php //removed the issets and other checkers for ease of readability
print_r($_POST);
?>
UPDATE: I have tried to add method:"POST" to my ajax function and it still seems to be printing out blank arrays... Maybe I should convert everything to GET?
jQuery ajax() uses GET as default method. You need to mention method: POST for POST requests.
method (default: 'GET')
$.ajax({
url: url,
method: "POST",
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
Or you can also use post().
EUREKA!!! Wow, the mistake was much simpler than I thought, figured it out solo! Thank you everyone for the tips! Finally got it
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {}; // THIS NEEDS TO BE CHANGED TO BRACKETS!!

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

Arrays are null after passing them with Ajax to the next page

Function:
$("#123").click(function(){
var oberpunkte = new Array();
$('input:checkbox[class=oberpunkte]:checked').each(function() {
oberpunkte.push($(this).attr('name'));
});
var unterpunkte = new Array();
$('input:checkbox[class=unterpunkte]:checked').each(function() {
unterpunkte.push($(this).attr('name'));
});
var kategorie = $("input:radio:checked[name='kategorie']").val();
$.ajax({
TYPE: 'POST',
url: 'selected.php',
data: { oberpunkte:oberpunkte, unterpunkte: unterpunkte, kategorie: kategorie},
success: function (data){
console.log(data);
$('#sumadd').html(data);
}
});
});
});
php:
$oberp = $_POST['oberpunkte'];
$unterp = $_POST['unterpunkte'];
$katid = $_POST['kategorie'];
var_dump($oberp);
var_dump($unterp);
echo($katid);
I also alerted my Arrays before the $.ajax Method. They aren't null.
If I echo the passed Arrays I get the Value null.
I also searched Stackoverflow for similar questions and didn't find a solution which solved my problem.
I bet there is an easy mistake, I just can't figure it out.
MY Div where the output will be:
echo("<div id='sumadd'></div>");
The Output:
NULL NULL
Arrays:
Console.log ->
Object's methods are case sensitive try to change "TYPE" to "type" in $.ajax() method.
Pass data to ajax as arrays:
data: { oberpunkte:[oberpunkte], unterpunkte: [unterpunkte], kategorie: [kategorie]},

jQuery post() with serialize and extra data

I'm trying to find out if it's possible to post serialize() and other data that's outside the form.
Here's what I thought would work, but it only sends 'wordlist' and not the form data.
$.post("page.php",( $('#myForm').serialize(), { 'wordlist': wordlist }));
Does anyone have any ideas?
You can use serializeArray [docs] and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});
$.post("page.php", data);
Try $.param
$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));
An alternative solution, in case you are needing to do this on an ajax file upload:
var data = new FormData( $('#form')[0] ).append( 'name' , value );
OR even simpler.
$('form').on('submit',function(e){
e.preventDefault();
var data = new FormData( this ).append('name', value );
// ... your ajax code here ...
return false;
});
When you want to add a javascript object to the form data, you can use the following code
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
if (data.hasOwnProperty(key)) {
postData.push({name:key, value:data[key]});
}
}
$.post(url, postData, function(){});
Or if you add the method serializeObject(), you can do the following
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});
In new version of jquery, could done it via following steps:
get param array via serializeArray()
call push() or similar methods to add additional params to the array,
call $.param(arr) to get serialized string, which could be used as jquery ajax's data param.
Example code:
var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
// ...
}
$.ajax({
type: 'POST',
url: 'test.php',
data:$("#Test-form").serialize(),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&moreinfo=MoreData';
},
success:function(data){
// json response
},
error: function(data) {
// if error occured
}
});
You can use this
var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);
You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.
Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:
var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);
I like to keep objects as objects and not do any crazy type-shifting. Here's my way
var post_vars = $('#my-form').serializeArray();
$.ajax({
url: '//site.com/script.php',
method: 'POST',
data: post_vars,
complete: function() {
$.ajax({
url: '//site.com/script2.php',
method: 'POST',
data: post_vars.concat({
name: 'EXTRA_VAR',
value: 'WOW THIS WORKS!'
})
});
}
});
if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!
Hope this helps.

Categories

Resources