The array is getting overwritten - javascript

I have a nested loop. in the inner most loop I am creating the array and when the control comes out of the inner loop, then I am coppying the entire array formed in the inner loop to the new array.
The problem is that the values are getting over written in the end.
The data I have will go for 2 outer loop and each loop will have 5 and 24 inner loops respectively.
But in the end the total data I get is the data from the last loop.
Here is the js code:
$(document).ready(function(){
$.ajax({
url: "Sample.xsd",
dataType: "html",
success: function(data){
var xmlObj = $.parseXML(data);
var buff = $(xmlObj).find("xs\\:complexType");
var xmlObj1 = []; var buff1 = [];
var j = 0;
$(buff).each(function(i){
buff1.splice(0, buff1.length);
$this = $(this);
$this.find("xs\\:element").each(function(index){
buff1[index] = $(this).attr('name');
});
xmlObj1[j] = buff1;
console.log(xmlObj1);
j++;
});
console.log(xmlObj1);
},
error: function(err){
}
});
});
If you want I can attach the xsd file as well. But I dnt think its important.
Thank you.

Honestly I think you are overdoing it. The following should give you the expected result:
$(function() {
$.ajax({
url: "Sample.xsd",
dataType: "html",
success: function(data) {
var xmlObj = $.parseXML(data), xmlObj1 = new Array(),
buff = $(xmlObj).find("xs\\:complexType");
$(buff).each(function(i) {
var buff1 = new Array();
$(this).find("xs\\:element").each(function(ii) {
buff1[ii] = $(this).attr('name');
});
xmlObj1[i] = buff1;
});
console.log(xmlObj1);
},
error: function(err) {
console.log(err);
}
});
})
jsFiddle based on similar idea.

Try to reassign it as empty to the array value after it is assigned before it starts a new loop.

You can make buff1 as a local variable to the $(buff).each loop.
$(document).ready(function(){
$.ajax({
url: "Sample.xsd",
dataType: "html",
success: function(data){
var xmlObj = $.parseXML(data), xmlObj1 = [];
var buff = $(xmlObj).find("xs\\:complexType");
$(buff).each(function(i){
var buff1 = [], $this = $(this);
$this.find("xs\\:element").each(function(index){
buff1.push($(this).attr('name'));
});
xmlObj1.push(buff1)
});
console.log(xmlObj1);
},
error: function(err){
}
});
});

Related

AJAX sending array data as JSON object

I have a form and i wanted specific elements of the form which I got and stored the values in an array.
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var item_name = miniform.elements['itemId'].value;
var quantity = miniform.elements['quantityId'].value;
var amount = miniform.elements['amountId'].value;
var total = amount * quantity;
var cart = ["Item: ",item_name,"Quantity: ",quantity,"Amount: ",amount,"Total: ",total];
I would then like to convert this array into a JSON object and send it to a php file through ajax but its not working. Here is my ajax code:
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.stringify(cart),
success: function(){
console.log('Message Sent');
}
});
What could be the problem??
look the comma, it should be {"key":value, "key":value..} not {"key":,value, "key":,value..}
var cart = {"Item" : item_name, "Quantity" : quantity, "Amount" : amount, "Total" : total};
you are doing wrong .
please use this way
var cart = {"Item ":item_name,"Quantity ":quantity,"Amount ":amount,"Total ":total};
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.parse(cart),
success: function(){
console.log('Message Sent');
}
});
If you want to post the array Then you can use this way.
cart = [];
cart[0] = item_name;
cart[1] = quantity;
cart[2] = amount;
cart[3] = total;
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data:{cart:cart},
success: function(){
console.log('Message Sent');
}
});
Don't build it manually
Instead of building your Object or Array manually, which is prone to errors, do it like this:
Object
// Define your empty Object
var cart = {};
// Assign its properties
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = amount * quantity;
Array
Or if you prefer to have an array:
// Define your empty array
var cart = [];
// Assign its properties
cart['item_name'] = miniform.elements['itemId'].value;
cart['quantity'] = miniform.elements['quantityId'].value;
cart['amount'] = miniform.elements['amountId'].value;
cart['total'] = amount * quantity;
Now you have your cart Object or Array ready and you can call JSON.stringify on it:
JSON.stringify(cart);
You could just send the entire form using formdata(). Is there a reason you don't?
Anyway, it doesn't work because you are not creating a json object, but a normal array. There's a difference. You can actually just put the json directly into the ajax call and you don't have to stringify it.
var cart = {};
cart['Item'] = item_name;
cart['Quantity'] = quantity;
cart['Amount'] = amount;
cart['Total'] = total;
$.ajax({
url: 'https://www.google.com',
type: "POST",
//Datatype causes it to automatically become json and will expect json back
//return json back from php through json_encode($myArray);
dataType: "json",
data: cart,
success: function() {
alert('Message Sent');
}
});
in short: You used the wrong braces :)
I just changed it to an easier way of managing objects. The problem with your previous object was that it was built wrong. Should be something like:
var cart = {"Item":item_name,"Quantity": quantity,"Amount":amount,"Total":total};
I found a solution to my problem and I combined some your responses to find the answer.
$('#miniform').on('submit',function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var cart = {};
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = cart.amount * cart.quantity;
var jsonString = JSON.stringify(cart);
$.ajax({
url: url,
type: type,
data:{data:jsonString},
success: function(){
console.log('Email Sent');
},
error: function(error){
throw new Error('Did not work');
}
});
return false;
});

How to get data with $.ajax() jquery and display to the HTML webpage

I need help in retrieving data from https://jsonplaceholder.typicode.com/. Here is my AJAX call:
$.ajax({
url: root + '/posts/',
data: { userId: 1 },
type: "GET",
dataType: "json",
success: function(data) {
$("#posts").html("<p><h3>" + data[0].title + "</h3></p>");
console.log(data);
$("#posts").append("<p>" + data[0].body + "</p>");
console.log(data);
}
});
How can I set the data: userId to not only 1 but a range of values like 1 to 5 or 1 to 10? And how do I append all of them by displaying in my html file?
Simple click way
HTML:
<div data-action="getUsers" data-users="1,2,3,4,5">Get Users</div>
JS:
$(function(){
$("[data-action=getUsers]").on("click", function(){
// get userId someway
var $this = $(this);
var data = $this.data();
var users_string = data.users;
var userIds_str_array = users_string.spilt(","); // this will turn a string into an array of strings split by given char
var userIds_int_array = [];
var length = (userIds_str_array.length - 1);
// convert to ints, might be overkill, strings might be fine, this is your call
for(let i = length; i--;){ // short hand for-loop, use if order doesnt matter
let value = userIds_str_array[i];
let test_val = parseInt(value);
// short hand if
// return true to skip iteration
isNaN(test_val) === false ? userIds_int_array.push(value) : return true;
}
// make sure you are not wasting your time.
if(userIds_int_array.length > 1){
return GetUserFromPosts(user, function(responce){
if(responce.users){
if(responce.users.length > 0){
// func call
return doSomethingWithUsers(responce.users);
}else{
return false; // no users in array
}
}else{
return false; // there was probably a 500 error
}
});
}
else
{
return false // no users in array
}
})
})
function GetUserFromPosts(userId_arr, callback){
var data = {userId: userId_arr}; // I assume your api can accept an array, if not, you have to do seperate calls for each one.
$.ajax({
url: root + '/posts/',
data: data,
success: function(data) {
console.log(data);
return callback(data);
}
});
}

Uncaught TypeError: Cannot use 'in' operator to search for

I have this ajax json function where I use to send request and pull json response data (refer below)
//global array
var coaum_creation_date = [];
var coaum_arrears = [];
var coaum_wupdate= [];
var coaum_completed = [];
var coaum_pending = [];
var coaum_overdue = [];
//chart rendering
function get_coaum_chart(){
$.ajax({
url: $("body").attr("data-link") + "/get-coaum-chart",
type: 'post',
dataType: 'json',
data: { request : 'get coaum chart'},
beforeSend: function(){
},
success: function(response){
if(response.success){
console.log(response);
//clear the array objects
coaum_creation_date = [];
coaum_arrears = [];
coaum_wupdate= [];
$.each(response.chart_data, function(index, value){
coaum_creation_date.push(value.creation_date);
coaum_arrears.push(parseInt(value.arrears));
coaum_wupdate.push(parseInt(value.with_updates));
});
}
}
});
}
get_coaum_chart();
and there is the json response along the error (refer to the image below)
any ideas, clues, recommendations, suggestions, help?
Just guessing here, but it can be because you can use $.each on Objects, but your response.chart_data seems to be a JSON string.
Try using $.parseJSON() (doc):
$.each($.parseJSON(response.chart_data), ...
Hope it helps.

Append Order - jQuery

I am trying to get the string to order by how it is displayed (red,blue,orange,black). For some reason, it will append the order randomly. For Example: it would output (blue,orange,red,black). Any help would be great. Thanks.
var tCookie = "red,blue,orange,black";
var Cookies = tCookie.split(',');
if (Cookies) {
for (var i = 1; i <= Cookies.length; i++) {
var dataString = "TabId="+Cookies[i]+"";
$.ajax({
type: "POST",
url: "includes/tab.php",
data: dataString,
cache: false,
success: function(html){
$("#Dynamic_Tab").append(html).children(':last').hide().fadeIn("fast");
}
});
}
}
You could have a list of requests and responses, and start appending when all are done, so that the order is always correct:
var deferreds = [],
results = [];
for (var i = 1; i <= Cookies.length; i++) {
(function(i) { // to freeze i
var dataString = "TabId="+Cookies[i]+"";
deferreds.push($.ajax({
type: "POST",
url: "includes/tab.php",
data: dataString,
cache: false,
success: function(html){
results[i] = html; // insert at the synchronous position
}
}));
})(i);
}
$.when.apply($, deferreds).then(function() {
$.each(results, function(i, html) {
$("#Dynamic_Tab").append(html).children(':last').hide().fadeIn("fast");
});
});
You can use deferred objects here to only append the HTML after all of the AJAX requests come back:
//create array to store XHR objects that will resolve when the AJAX requests return
//also create an object to store the AJAX responses
var jqXHRs = [],
responses = {};
//iterate through each of the cookie indexes
$.each(cookies, function (index, value) {
//create the dataString and cache the value of this index so it can be used in the success callback for the AJAX request associated with this index
var dataString = "TabId=" + value,
thisValue = value;
//store an empty string in the output variable for the current index, this keeps it's place in-line
responses[thisValue] = '';
//do the AJAX request and store it's XHR object in the array with the rest
jqXHRs[jqXHRs.length] = $.ajax({
type : "POST",
url : "includes/tab.php",
data : dataString,
cache : false,
success : function (html) {
//now that the AJAX request has returned successfully, add the returned HTML to the output variable for this index
responses[thisValue] = html;
}
});
});
//wait for all of the XHR objects to resolve then add all the HTML to the DOM
$.when(jqXHRs).then(function () {
//all of the AJAX requests have come back and you can now add stuff to the DOM
var $element = $("#Dynamic_Tab");
$.each(responses, function (index, value) {
$element.append(value).children(':last').hide().delay(index * 250).fadeIn(250);
}
});
The .delay() is so that each new row will fade in, in order.

Problem understanding javascript multi-dimension arrays

I want to get some values out of TinyMCE textboxes, along with IDs. Then post these via ajax to the server.
jQuery 1.4 and JSON library are loaded
var send_data = [];
$('.contact_check').each(function(i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts[' + this_id + '][message]');
var content = addslashes(msgbox.getContent());
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});
var encoded = JSON.stringify(send_data);
$.ajax({
type: 'POST',
url: 'http://localhost/test.php',
data: encoded,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() {
alert('jay');
}
});
Firstly,
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
does not seem to work. It says send_data[i] undefined. I've also tried:
send_data[this_id] = escape(content);
That does not seem to work either. The JSON string returns as []. What am I doing wrong?
You're not really making a multi-dimensional array. You're making an array of objects. Either way, before you can set an attribute or array element of something at send_data[i], you have to make send_data[i] be something.
send_data[i] = {};
send_data[i]['id'] = this_id;
send_data[i]['content'] = escape(content);
or, better:
send_data[i] = {
id: this_id,
content: escape(content)
};
You have to make each send_data[i] an object first:
$('.contact_check').each(function (i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts['+this_id+'][message]');
var content = addslashes(msgbox.getContent());
send_data[i] = {};
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});

Categories