How to pass the data as object in jquery ajax - javascript

I want to receive the value thought iterator, when I use
$('#someModal').find('input[name=nameProBangHHModal]').val(data[0].TenNhanQuyCach);
it works as expected.
But when I use an iterator, the return shows [object Object].TenNhanQuyCach - not the data returned.
I try to search for other topic but I'm stuck on this. How to get the data returned in array[data[0]] with the value from the iterator method?
Thank you for your time!
$.ajax({
url: 'someurl to retrive data',
type: 'POST',
data: {id:id},
success: function(data,status) {
var tenCot = ['nameProBangHHModal','valueBangHHModal',];
var tenCotTrongCsdl = ['TenNhanQuyCach','DonViTinh',];
console.log(tenCotTrongCsdl[0]);
for (i=0;i <= tenCot.length - 1;i++) {
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0]+'.'+tenCotTrongCsdl[i]');
}

oh i find out the answer after search topic for array: this one: How can I access and process nested objects, arrays or JSON?.
and find out that need to use [] for variable, not the ".".
this one work for me:
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0][tenCotTrongCsdl[i]]);

Related

How do I map a variable to object

I'm new to JSON and jQuery/JavaScript.
How would I pull in a object so that I can use it within jQuery, I've tried 2 attempts
var placements = document.querySelector(placements)
var message = document.querySelector(placements.message)
$.ajax({
type: 'GET',
url: 'https://raw.githubusercontent.com/kieranbs96/developer-exercise/master/data/recommendations.json',
async: false,
dataType: 'json',
success: function (data) {
$("header").append(placements.message);
}
});
Below is the JSON I'm trying to pull in:
{
"placements":[
{
"message":"If you like this, you might be into these",
"items":[
{
"id":"029148",
"name":"Woodblock Play Suit",
"price":"46.00"
},
{
"id":"0294526806",
"name":"Smock Dress",
"price":"39.00"
},
{
"id":"0297180006",
"name":"Cami",
"price":"9.00"
},
{
"id":"0298473606",
"name":"Asymmetric Wrap Cami Dress",
"price":"46.00"
},
{
"id":"0297155306",
"name":"Casual Stripe Tee",
"price":"16.00"
}
]
}
]
}
Marked as duplicate - the other question did not solve my problem - it has been solved by an answer to this question.
You haven't included what the error is or the expected output, but here's two potential errors.
You aren't utilizing the data object returned from your AJAX request.
The value associated with the placements key on your JSON object is an array of objects. Therefore, to access the message key, you'll need to traverse the array.
This is likely what your code should look like:
$("header").append(data.placements[0].message);
First off, you're missing the data object within your append function.
Second, you're missing the key notation of data.placements considering the fact that placements is an array.
You can either use data.placements[0].message to get your preferred data, or, if placements will be extended with more objects in the future, map through your objects like this:
data.placements.map(function(obj, index){
if(index == 0){
$("header").append(obj.message);
}
})
Not necessary if your array will always have a length of 1 of course

".replace() is not a function" when trying to use inside ajax success

This is what I'm doing:
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors = data;
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
This is the error:
Uncaught TypeError: supervisors.replace is not a function
If I do this:
$('#divSupervisorList').text(data);
The the result on screen is this:
John Foo, Jane Bar
What I want is:
John Foo
Jane Bar
But I'm having trouble replacing the , with a <br />. At first I tried:
$('#divSupervisorList').text(data.replace(",", "<br />"));
And when that didn't work, I went to using a string that is declared before the ajax call. I also tried using .split() but got the same error.
Not sure what I'm doing wrong.
UPDATE:
As many have pointed out, my return data is not a string, but an object:
(4) ["Adam Brown", "Karl Walser", "Jeremy Smith", "Nathan Graham"]
0 : "Adam Brown"
1 : "Karl Walser"
2 : "Jeremy Smith"
3 : "Nathan Graham"
So, now I gotta figure out how to split this array into a string :-)
My guess is that the data param is actually an array, not a string, and you're seeing it with commas only because JS is sneakily stringifying it that way. You could combine them in a string using the join method for arrays:
supervisors.join('<br />')
However, if you try to use "<br />" in jQuery's text function, it will get escaped. You can use the html function instead. So,
$('#divSupervisorList').html(supervisors.join('<br />'));
The data you are having in response is a Json and not a string.
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors =JSON.stringify( data);
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
Read more:. [https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify].
To replace commas inside each member of your array, you need to map .replace() on the array values:
let result = data.map(function(o){return o.replace(',','<br />')});
To join the members of the array, separating them with a <br />, you need .join():
let result = data.join('<br />');
Note there are no actual commas separating the array members, that's just a conventional way of displaying array values so humans can read and understand them, but there's nothing to replace. All you need to do is join the members with the separator of your choice (<br />) which, by default, is a comma.
So this would also give you the same result:
let result = data.join().replace(',','<br />');
... because .join() would glue the strings using , and .replace() would replace them with <br />s.
According to the jQuery docs:
[dataType is] "json": Evaluates the response as JSON and returns a JavaScript object
So your data is actually an object. You need to access the relevant string property, e.g. data.supervisors.replace(...) - depending on your object model.
I recommend adding a console.log(data) call to your success callback and checking the developer console in your browser by pressing F12 to investigate the source of your issue.
Update: The output of above call to console.log hints at data being an array. Thus, you need to replace
$('#divSupervisorList').text(data.replace(",", "<br />"));
with
$('#divSupervisorList').html(data.join("<br />"));

Split Json data into multiple data using Jquery

$.ajax({
type: 'POST',
url: 'url',
data: val,
async: false,
dataType: 'json',
success: function (max) {
console.log(max.origin);
}
});
Then i am getting an output which is
["test,origin"]
I want to split it like .
test
origin
Please suggest me .
Much appreciated
If your returned value of max.origin really is ["test,origin"], you have to do something like this
var data = max.origin[0].split(',');
so that data will contain a list of the elements that are comma-separated. However, if your max.origin is in the form of ["test", "origin"], you can simply select each/all items by going through a for-loop and (optionally) print them out:
for (var i = 0; i <= max.origin.length; i++) {
console.log(max.origin[i]);
}
If you know that you only get the two elements (test and origin) each time, #void's answer is a good approach.
max.origin[0].split(",")[0] will give you test
max.origin[0].split(",")[1] will give you origin

json result display first value

I have found several posts similar to this topic but nothing I have tried has actually worked. My question is simple and should be easy to answer. My return json object will have one key and one value. For my code below, the alert shows "[{"DISCOUNT":1}]" and all I am trying to do is parse out the "1" and display it. Ultimately, I want to plug that value into a variable and use for multiplication, but I can't even get the darn number to display by itself. My code is below:
function codeMatchTest() {
if ($('#dbReturnString').val() == '') {
alert("Please enter a discount code.");
} else {
$.ajax({
type: "POST",
url: "PROMO.svc/MatchCode",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
success: function (json) {
alert(json.d);
/*alert (json.d.discount); // getting "undefined"
$.each(json.d, function (key, value) {
var discount = value;
});
alert("Success: " + discount); //getting "undefined" */
},
error: function () {
alert("There was an error with your request.");
}
});
}
}
I have found no good references on how to actually use the data in a json object. My json object will only consist of a single key and value and I will only ever need to use the value.
Also, I have tried several iteration using $.each and none work. Based on the jquery documentation, it should be very easy but I am having not luck.
If your alert is showing "[{"DISCOUNT":1}]" that means you have an object within an array.
try alert(json.d[0].DISCOUNT);
JSON parsed objects are case sensivetive, plus its seems that json.d contains a string (wich seems to be in json) rather than an object. Try:
var discount = JSON.parse(json.d);
discount = discount[0].DISCOUNT;
success: function(json) {
alert(json.d[0]["DISCOUNT"]);
}
First comment on your code, you are reinventing what jQuery does.
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
It should just be
data: { codeInput: $('#dbReturnString').val().toLowerCase() },
Now to get the data it is simple, you are returning an array with an object in it.
Let us look at it as a regular variable and not an Ajaqx call.
var json = [{"DISCOUNT":1}];
So you got an array? How do you get the object inside of it? You reference the index. Since you said there will only be one index being returned, than use [0] to access it.
success: function (json) {
alert(json[0].DISCOUNT);
To access the first item from the json you may use
alert(json.d[0].DISCOUNT);
Because json.d is an array and it contains one object which is 0 index. So, json.d[0] will select the first item/object from the array and using .DISCOUNT you can access the object's property. It's also possible to access the property like
alert(json.d[0]["DISCOUNT"]);
Try this way
You can use JSON.parse(json.d) / json.d
var data = json.d;
for(i=0;i<data.length;i++) {
alert(data[i].fieldname);
}

jQuery $.ajax method only sends one item from my serialized array

My tomcat log is only showing one item being passed in..
var itemArr = ["someItem", "someItem2", "someItem3"];
$.ajax({
type: "POST",
url: "myServlet",
data: $.param({item: itemArr})
});
The array contains around 20 elements.
Also if i do:
var params = $.param({item: itemArr});
alert(params);
All the values come out formatted as item=someitem&item=someitem2..etc etc
But the ajax post only outputs the first item from the array. I want them all passed through to the server in the request.
Any help would be much appreciated.
EDIT:
Using version 1.3.2 also tried with 1.4.4 - same problem
I think your $.param() call should just be this:
var itemArr = ["someItem", "someItem2", "someItem3"];
$.ajax({
type: "POST",
url: "myServlet",
data: $.param(itemArr)
});
EDIT: Nick is onto something there...
From the jQuery.param() documentation:
// <=1.3.2:
$.param({ a: [2,3,4] }) // "a=2&a=3&a=4"
// >=1.4:
$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4"
EDIT AGAIN
Maybe something like this will work for you, to emulate the 1.4 behavior:
var itemArr = ["someItem", "someItem2", "someItem3"];
var paramed = decodeURIComponent($.param({ 'item[]': itemArr }));
Demo here: http://jsfiddle.net/Ender/EHd78/1/
Oh right I missed the first sentence, yes you will only get one item passed to your server it should be an array.
This from firebug when I make that request,
item[] someItem
item[] someItem2
item[] someItem3

Categories