How can I take count of element in my database with ajax/json in asp.net? With GET method? So far I've got this:
// GET: /People/
public JsonResult Index()
{
var count = db.People.ToList().Count;
return Json(count);
}
in javascript:
function check_count() {
var how_many=$.ajax(
{
type:'GET',
url:'/People/',
success: function(data){
alert('successful');
}
});
}
What you have looks OK, except for one little thing:
var how_many = $.ajax({
// ...
});
The AJAX call returns a "promise", it lets you chain things together, handle errors etc.
The reason for this is that AJAX calls are async, you start them and they (hopefully) will finish some time in the future. The line with your alert('successful'); is the code that will be run once the call is finished.
Change that code to handle your data, perhaps try the following:
$.ajax({
type: 'GET',
url: '/People/',
success: function(data) {
console.log(data);
// this is like a break point, so you can inspect things
debugger;
}
});
As long as you have debugging enabled in your browser you'll be able to check what data was returned and work out what code you want from there.
Related
Consider the following code sample from my grid controller:
loadData: function (filter) {
var data = $.Deferred(); // This line is hit.
var rsp = null;
$.ajax({
type: 'GET',
contentType: 'application/json: charset=utf-8',
url: loadRoute,
data: filter,
dataType: 'JSON'
}).done(function (response)
{
// This function is never invoked.
debugger;
rsp = response;
data.resolve(response);
});
return data.promise();
},
When I debug this code, a breakpoint set on the first line of loadData is successfully hit; however, the debugger statement inside done is never hit. I can't see any obvious reason why.
Can anyone see what I am doing wrong here?
As far as I can tell this method must return a promise, which I am doing. Further, I have to resolve the data returned from the AJAX call to unpack it, which I am also doing (provided I can hit done).
FWIW, the server side code is invoked (loadUrl) and returns without error. But because I can't get into done, I can't inspect the data.
I've never done this type of manipulation of AJAX calls (to stop/abort/cancel or ignore? already running AJAX calls before the execution of a new one) before so I really don't understand how to do that and would appreciate some direction.
I have a page in my app where I make a number of AJAX calls to fill dynamically the data in my table (Object Name, Object Fit, Object Progress) when the page loads. For example, there are 5 rows in the table. So I call
$.post("/getFit", {objectId: objectId}, function (result) { manipulation with result }
and
$.post("/getProgress", {objectId: objectId}, function (result) { manipulation with result }
5 times each in the loop -- one for each of the objects.
The first column of my table has links to more detail on the object, and clicking on them I call another AJAX:
$(document).off('click', '.js_object').on('click', '.js_object', function (e) {
var objectId = $(this).attr("id")
$.post("/viewObject", {objectId: objectId}, function (result) {document.getElementById("main_window_content").innerHTML = result; });
})
The problem is that the browser will not render the results of the last AJAX call (/viewObject) until it has received the results of all of the previous calls (/getFit x5 and /getProgress x5).
As a result, a user that wants to drill into the detail on an object needs to wait until the AJAX calls for the other objects are complete before they see anything.
So I struggle with how to stop/abort/cancel (or ignore?) "/getProgress" and "/getFit" so we can fully execute "/viewObject" and view the results of it.
I would very much appreciate your help.
Use xhr.abort() to kill the xhr requests as shown in the below code in JS. I believe there is ajax.abort(); in JQuery
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
If you want execute one ajax after another, and you need all requests to work to show the final result, you can use .done():
$.ajax({
url:'/getFit',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /getProgress
$.ajax({
url:'/getProgress',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /viewObject
$.post("/viewObject"....
})
});
That way you only show /viewObject if the others calls were successfull
I'm trying to store ajax result into variable. When I use console.log it gives my html tag that I wanted, But when I trying set into global variable it said undifined.
How I can store ajax result into global variable
var result;
$.ajax({
url: "person.html",
success: function(data){
//result=data;
console.log(data);
}
});
//console.log(result);
Ajax is asynchronous, meaning that the code to find out what result IS is running at the same time that the console log of result, which is why you're getting undefined, because result hasn't been set by the time the value is being console logged.
The only way I know of to console log the result would be to either do it within the ajax success function or to have the ajax success function call a subsequent function that contains the console log. It's the only way to be sure that a value has been returned before you console log it.
Examples:
EXAMPLE 1:
var result;
$.ajax({
url: "person.html",
success: function(data){
result=data;
console.log(result);
//Note that in this instance using the variable 'result' is redundant, as you could simply console.log data like you're already doing.
}
});
EXAMPLE 2:
var result;
$.ajax({
url: "person.html",
success: function(data){
result=data;
subsequentFunction(result);
}
});
function subsequentFunction(result){
console.log(result)
}
// Note that if you're doing something simple with result that this could be a bit long winded and unnecessary.
It all depends on how much you're wanting to do with the result as to which option would be better.
Note: There is also a property of an ajax call called 'async' that you can set to false which forces it to be synchronous, but this is generally considered a bad idea as it will prevent any other code from running until the result is returned and locking the browser.
$.ajax returns a promise, meaning that your code KNOWS it's going to receive a response, but because it's dependent on an external source, it doesn't know when this response will come in.
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
See above link for more information on the subject.
ajax requests are async so your console.log(result) is running before getting response of your request. you should do something like this
var result;
$.ajax({
url: "person.html",
success: callback(data)
});
function callback (data){
result=data;
console.log(result);
}
You will not see anything beacuse the data is not populated yet. In your specific case you actually need to wait for the response. You can achieve it by using the following snippet.
$(document).ready(function(){
var data = $.parseJSON($.ajax({
url: 'person.html',
dataType: "json",
async: false
}).responseText);
var myProp = data.property; // Here you can access your data items
});
Another approach should be like you can push your data in an array and can access it in another function like this:
var result =[];
$(document).ready(function()
{
$.ajax({
url: 'person.html',
async:true,
dataType: "json",
success: function(data)
{
result.push(data);
}
});
});
NewFunction()
{
console.log(result);
}
I want to read the contents of a local file using JavaScript/jQuery. I understand this is often discussed, but my example is a little different because I want to return the contents after the fetch is done rather than manipulate HTML.
I don't want to talk about security issues and local files because this code is meant to run within my own browser (Chrome, which I start with the --allow-file-access-from-files flag).
I have the following function to get the data...
function readData() {
$.ajax({
type: "GET",
url: "data.xml",
async: false, // this does not change the outcome
dataType: "xml",
success: function(xml) {
// Got the data, find entries and return them.
console.log("Returning data");
var doc = $(xml).find('entry');
// This is where most examples manipulate dom, I want to
// return the data instead
return doc;
}
});
}
Now I want to do...
var xmlDoc = readData();
// undefined, why?
and have the document in the variable. Instead I get undefined. It seems that the function returns before the file is fetched. Or maybe I have a problem with variable scope?
Does anyone know how to accomplish this? Yes, I am sure I want to use JavaScript even though I am doing this locally.
The stackoverflow answer regarding handling of $.ajax calls has a good example of a nice way this can be used. This example can be slightly modified to give you something close to what you are looking for.
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'xml',
beforeSend: showLoadingImgFn
})
.always(function() {
// remove loading image maybe
})
.fail(function() {
// handle request failures
});
}
The examples of implantation of the above method is:
xhr_get('/index').done(function(data) {
// do stuff with index data
});
xhr_get('/id').done(function(data) {
// do stuff with id data
});
You might want to something like:
function readData() {
var returnData;
xhr_get('data.xml').done(function(data) {
returnData = data;
});
return returnData;
}
Hope that helps.
I've just started working with JavaScript for non-trivial things, so this is probably straightforward...
What I'm trying to accomplish: iterate on an array of product references, fetch the JSON for each reference, and return an array of all the product information (with a hash-like structure indexed by reference).
What I've tried:
function fetchProductData(references){
var product_data = new Object();
references.forEach(function(ref){
$.ajax({
url: "http://localhost:3000/products/find.js?reference=" + ref,
dataType: "jsonp",
type: "GET",
processData: false,
contentType: "application/json",
success: function(data) {
product_data[ref] = data;
}
});
});
alert('before return: ' + product_data);
return product_data;
};
$(document).ready(function(){
var products = fetchProductData(references);
alert('products : ' + products);
});
Here's what I don't understand: the first time I call alert to display the array contents, the array is empty. However, on the second call, the array is populated with the data I want.
In other words, the "products :" alert displays the data I want in the code above. But if I comment the "before return: " alert, it no longer does. Why is this?
So my question is: how can I have jQuery make several $.ajax call to fetch product information, collect that information in an array, and return that array so I can use it elsewhere in my code?
Also, why is the data in the variable magically accessible after it is referenced in an alert?
The "A" in "AJAX" stands for "asynchronous" :). Your program doesn't wait for the call to complete before going on to the next iteration, meaning you'll probably not get all of your data. Also the alert has the same problem. Operation to concat 'before return:' to the string add just enough time to get some data in the variable. On a faster machine you might find you never get data.
I think you really need to rethink your approach. It's not a good idea to have multiple AJAX requests in a loop. It will greatly increase latency of the page. Pass all your parameters once using JSON, then have your server side script loop through that and return a single response in JSON.
function fetchProductData(references){
// make sure your "references" is a JSON object
$.getJSON('http://server/side/url', {'json':references}, function(product_data) {
// do something with product_data (alert them, put them in an array, etc)
});
}
function fetchProductData(references, cb){
var length = 0;
var product_data = new Object();
references.forEach(function(ref){
length++;
$.ajax({
url: "http://localhost:3000/products/find.js?reference=" + ref,
dataType: "jsonp",
type: "GET",
processData: false,
contentType: "application/json",
success: function(data) {
product_data[ref] = data;
if (++count === length) {
cb(product_data);
}
}
});
});
};
$(document).ready(function(){
var products = fetchProductData(references, function(products) {
alert('products : ' + products);
});
});
Use a callback on your asynchronous operation.
The reason it appears to work with the alert call is because alerting a message gives ajax enough time to populate your array. The return statement is only triggered after you click OK on the alert box giving your code a window of 250ms to populate the array with data.
You are executing you ajax query in async mode. And you want a sync result. Try to add:
async: false
Hope this helps.
your $.ajax call is asynchronous, so what is happening is that the first time you make the call, your javascript makes the call, moves on to the next line (alert) and then loops. You're data hasn't returned at that point yet. What you can do to remedy this is to set the async: false option in your $.ajax call.
This is an asynchronous operation. The only sure way to know when the data is ready is in the callback function: success: function () {...}, which gets called when the data has finally returned. Put your alert in there.