Create dynamic list of dates in jQuery - javascript

In javascript I need a plain list of dates like (for a jquery datepicker):
["16-5-2013", "24-5-2013", "25-5-2013", "26-5-2013"]
Because this list is dynamic I want to use this ajax call:
var disabledDays = $.ajax({
type: 'GET',
url: "/disabled-days",
});
In Django I wrote this test view which returns the data in json:
def disabled_days(request, soort):
from django.http import HttpResponse
import json
soort = ["16-5-2013", "24-5-2013", "25-5-2013", "26-5-2013", "27-5-2013"]
return HttpResponse(json.dumps(soort), mimetype="application/json")
Is json here the way to pass the data? I find the date list in the responsText, but I am unable to access this data.
For example I tried to iter over the items like:
for (i = 0; i < disabledDays1.length; i++) {
item = results[i];
disabledDays.push(item);
}
This results in an empty list.
The responsetext is (encoding is json):
["16-5-2013", "24-5-2013", "25-5-2013", "26-5-2013"]
When I do a console.log() I see this info:
GET http://localhost:8080/disabled-days
200 OK
39ms
jquery-1.9.1.js (regel 8526)
Object { readyState=1, getResponseHeader=function(), getAllResponseHeaders=function(), meer...}
Below is the solution Anh TĂș gave (not working yet):
var disabledDays1 = $.ajax({
type: 'GET',
url: "/disabled-days",
});
var disabledDays = []
for (i = 0; i < disabledDays1.length; i++) {
item = results[i];
if(typeof(responsetext)==string){responsetext= JSON.parse(responsetext);} $.each(responsetext,function(i,item){disabledDays.push(item);});
}
console.log(disabledDays);

I think you're handling the ajax request wrong. Normally you declare a callback function when the request success that and process the data received like this:
var disabledDays = []
$.ajax({
type: 'GET',
url: "/disabled-days",
success: function(data){
// data is the response json
disabledDays = data
// do whatever it needs to be done with disabledDays,
// it should be the array of dates.
// the process should be inside this method because of asynchronous
// javascript method execution
}
});
Hope it helps!

Related

AJAX returns Undefined error when displaying an Array of objects using jQuery in PHP on console

I am trying to read a JSON through jQuery and AJAX and some objects like the SUM(amountbet) object in the Array are returning as "undefined"on console.
The above image shows the SUM(amountbet) object as undefined on the console.
But when I am trying to access the "SUM(amountbet)" object it returns me "undefined" on console but when returning the horsename object the value is displayed perfectly. What am i doing wrong here?
Here is my AJAX, jQuery code where i am trying to display each objects in that Array comming from an SQL Query:
$(document).ready(function(){
var racenumberr = $(this).attr("RaceNumber");
var data = new FormData();
data.append("RaceNumber", racenumberr);
$.ajax({
url:"ajax/horses.ajax.php",
method: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function(response) {
console.log("Horse Information Displayed In Array",response);
var len = response.length;
for (var i = 0; i < len; i++) {
var horsename = response[i].horsename;
var totalbetting = response[i].totalbetting;
var totalpayout = response[i].payout;
console.log("Horse Names",horsename);
console.log("Horse Payouts",totalbetting); // <-- object is displayed undefined on console
}
}
})
});
object totalbetting is not defined, SUM(amountbet) create json object and convert value to integer

How to find the length of Success Data in Jquery Ajax?

I am retrieving list from ajax, when it become success, I wants to add those list values to DropDownList Items, So I want to iterate the data until last value and then add it to DropDownList
Here is my code What i tried
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "GPCreateCheque.aspx/getOpenRequestNo",
dataType: "json",
success: function (data) {
alert(data.length);
for (var i = 0; i<data.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
},
error: function (result) {
alert("Error");
}
})
In alert box it is showing undefined
UPDATE
I return the list<string> from [webmethod]
use data.d.length
alert(data.d.length);
for (var i = 0; i<data.d.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
You need to do data = JSON.parse(data); before treating your data like an array. It's just a string up to that point.
Update: if your data is not the array itself, but instead an object that contains an array named d, you need to work with that. It depends on your data structure.
Check the response from network tab in Chrome Developer Console or similar tool. May be response code is 200 but response data is missing.
On the other hand you want to itarete data in for loop but you try to append data.d[i]. If you want to append data.d[i] you have to itarete data.d in for loop.

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.

From an ajax json request, how can dynamically add the objects to an array so that I can loop through them?

This is what I have so far, essentially I'd like to use the data to instantiate a new info-window from google maps api dynamically from the data response. I know so far that I'm pushing objects to an array(which are two different data types), but if that's the only wrong here. Then how can I dynamically add the response into an object so I can retrieve data with a loop?
var i, venues, allVenues=[];
$.ajax({
url: 'url',
dataType: 'json',
data: 'data'
async: true,
success: function(data) {
venues = data['response']['groups'][0]['items'];
JSON.parse(venues);
for(i in venues){
allVenues.push(venues[i]);
}
};
/*Do something realistic with data other than logging it to console*/
console.log(allVenues);
You do it right, but not in the right place. jQuery.ajax will not wait for the response, but will invoke a 'success' callback when the request is answered.
Try this:
var i, venues, allVenues=[];
$.ajax({
url: 'url',
dataType: 'json',
data: 'data'
async: true,
success: function(data) {
venues = data['response']['groups'][0]['items'];
// The following line of code does nothing, because you
// did not store it's return value. Fortunately it wasn't
// even needed
//
// JSON.parse(venues);
for(i in venues) {
allVenues.push(venues[i]);
}
// or
// allVenues.push.apply(allVenues, venues);
// or in ES6
// allVenues.push(...venues);
// or the following will create a new array instance and save it in the allVenues variable
// allVenues = allVenues.concat(venues);
/*Do something realistic with data other than logging it to console*/
console.log("Here are your updated venues:");
console.log(allVenues);
}
});
console.log("These are your old venues:");
console.log(allVenues);
EDIT:
You can check that the identity of the allVenues array didn't change by printing it to the console every second:
setInterval(function(stored) {
console.log(stored);
console.log(stored === allVenues);
}, 1000, allVenues);
EDIT:
To update an array to contain only the items of another array, you can use:
allVenues.length = 0;
allVenues.push.apply(allVenues, venues);
or
allVenues.length = venues.length;
for (var i in venues) {
allVenues[i] = venues[i];
}

Sorting value fetched by jquery ajax call into javascript multidimensional array

I'd like to store a value that is correctly fetched via (NON ASYNC) ajax call (from facebook graph api) back to my javascript multidimensional array.
Everything works fine until the part when the data that I get from facebook api has to be stored to my previously defined 2d-array (and afterwards printed on the page via jquery append). I simply can't figure out where's the problem.
Here's the code sample:
Defining 2d array and its values:
fbpages = new Array (13);
i=0;
for (i=0;i<=12;i++) fbpages[i]=new Array(4);
fbpages[0][0] = "http://graph.facebook.com/120830347930692?callback=?";
fbpages[0][1] = "Kupi";
fbpages[0][2] = "/vijesti/tag/kupi/";
fbpages[0][3] = 0;
fbpages[1][0] = "http://graph.facebook.com/214014840762?callback=?";
fbpages[1][1] = "Kolek";
fbpages[1][2] = "/vijesti/tag/kolek/";
fbpages[1][3] = 0;
etc...
Fetch the data for every page using the URL from the array fbpages[x][0] and store it back to the same array, to the field fbpages[x][3]:
y=0;
for (y=0;y<=12;y++){
pageURL = fbpages[y][0];
fetchData(y,pageURL);
};
function fetchData (index,fbpageurl) {
$.ajax({
type: "GET",
url: fbpageurl,
dataType: "json",
async: false,
success:function(data){fbpages[index][3]=data.likes;}
});
};
Data printing works fine.
Thanks in advance!

Categories

Resources