Object Jsonp array undefined value - javascript

I need help....I have this code:
var req = $.ajax( {
url:'http://zz33.infoucrso.com/WSCategorias.svc/cargarCategoria?callback=?',
dataType : "jsonp",
data: { nombre: val},
timeout : _timeOut
});
req.success(function(datos)
{
ProcesarCategorias(datos);
});
So I receive a object JSON and pass that object to the function ProcessarCategotias that have the next code:
function ProcesarCategorias(datos) {
var categoria = JSON.stringify(datos);
alert(categoria);
}
So that show an alert with the next information: {"IdCategoria":2,"Nombre":"Música"}, but I need to access only
the value of Nombre, if I do categoria[0] this show me an "{", If I do categoria["Nombre"] shows me an undefinied. I saw other questions but that doesn't work for me.
So thanks

Exchange
JSON.stringify(datos)
for
JSON.stringify(datos['Nombre'])

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.

jQuery autocomplete multiple fields

I have the below AJAX response which is an object containing a food item and price.
{
"pizza": "100.00",
"Burger": "45.00",
"Ice Cream": "25.00",
"Chips": "20.00",
"Peanut Butter": "50.00"
}
I'm trying to build a form wherein the user enters an item and the 'price' input field gets automatically filled. I went through the jQuery documentation and I'm confused as to how I can get the Item inputbox to only look for the 'food' items (or keys) in the array.
I'm getting a this.source is not a function in my console. I'm aware of the reason where I'm going wrong (I believe its due to the fact that they keys are different food items as opposed to 'label').
Here is my js
$(document).ready(function(){
var myItems = getData();
$('#Item').autocomplete({
source: myItems,
focus: function(event,ui){
$('#Item').val(ui.item.Item);
return false;
},
select : function(event,ui){
$('#Rate').val(ui.item.Price);
}
});
});
function getData(){
var myItems = {};
$.ajax({
type : 'GET',
async: false,
url : 'http://127.0.0.1:8000',
data : {},
contentType: "application/json",
crossDomain:true,
success : function(json){
for(i = 0; i <json.length; i++){
myItems[json[i].Item] = json[i].Price;
//below doesn't work in loop
// myItems['Item'] = json[i].Item;
// myItems['Price'] = json[i].Price;
}
},
error : function(response){
console.log('error')
}
});
// console.log('Is this working '+ myItems);
console.log(myItems);
return myItems;
};
Please let me know how I can solve this issue.
The source option when you create the autocomplete needs to be either an Array of strings with the values, a String for a url with a JSON response that holds the values or a function callback which takes a pair of request and response parameters.
The way you have assigned var myItems = getData(); means the myItems is not one of these types. It will currently be an empty object because it is assigned before your Ajax call will complete.
Assuming you only need to load the data once, create the autocomplete in the success callback for your Ajax request;
$(document).ready(function(){
getData();
function getData(){
$.ajax({
type : 'GET',
async: false,
url : 'http://127.0.0.1:8000',
data : {},
contentType: "application/json",
crossDomain:true,
success : function(json){
var myItems = {};
for(i = 0; i < json.length; i++){
myItems[json[i].Item] = json[i].Price;
}
$('#Item').autocomplete({
source: myItems,
focus: function(event,ui){
$('#Item').val(ui.item.Item);
return false;
},
select : function(event,ui){
$('#Rate').val(ui.item.Price);
}
});
},
error : function(response){
console.log('error')
}
});
};
});
I actually tried going about this another way. i managed to pull all keys into a single array and use that as the source. the second box gets filled based on the value of the first box on the select event.
$(document).ready(function(){
var myItems = getData();
var keys = [];
for(var k in myItems){
keys.push(k);
}
$('#Item').autocomplete({
source: keys,
select : function(e,ui){
var value = myItems[ui.item.value];
$('#Rate').val(value);
}
});
});
function getData(){
var myItems = {};
$.ajax({
type : 'GET',
async: false,
url : 'http://127.0.0.1:8000',
data : {},
contentType: "application/json",
crossDomain:true,
success : function(json){
for(i = 0; i <json.length; i++){
myItems[json[i].Item] = json[i].Price;
}
},
error : function(response){
console.log('error')
}
});
// console.log(myItems);
return myItems;
};

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

Passing arguments in jquery ajax resulting in undefined

I'm new to jQuery. I'm creating a cascading dropdown using jquery ajax. So based on the changed value of first dropdown, the second script fetches values from database from second dropdown.
<script>
$(document).ready(function () {
$("#builder_group").change(function () {
var selected_builder = $(this).val();
alert(selected_builder);
$.ajax({
type: 'POST',
url: 'getGroupzCode.php',
data: 'selected_builder',
datatype: 'json',
success: function (data) {
// Call this function on success
console.log(data);
var yourArray = JSON.parse(data);
console.log(yourArray);
$.each(yourArray, function (index, yourArray) {
$('#builder_group1').append($('<option/>', {
value: yourArray.id,
text: yourArray.name,
}));
});
},
error: function () {
displayDialogBox('Error', err.toString());
}
});
});
});
</script>
Problem is when I alert the selected value from first dropdown it works i.e alert(selected_builder) works , but when I try to pass it to the script it is showing as undefined in PHP script. How can I solve this.
Don't pass it as a string.
data: selected_builder,
You're passing a string as your data. Try passin selected_builder without the surrounding ', like this:
data: selected_builder,
Pass the variable name instead of string.
data: selected_builder,
data: 'selected_builder'+data
It should be key value pair
When passing as a json string (for sending using jQuery ajax), let native javascript stuff do it for you. Pass your data as a correct JSON string to be interpreted by your target.
data : JSON.stringify({ selected_builder : selected_builder})
This will allow your receiving method to get the data as a parameter named selected_builder.

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]},

Categories

Resources