Multiple AJAX in one window.onload - asp.net-mvc

I'm sure this question must have been asked before but I'm really struggling
to find the answer anywhere so have finally given up and will consult
the stackoverflow community - hopefully there's someone out there who's seen
it all before and can help me out!
I have a webpage which needs to make some function calls as the page loads. It is an ajax method which calls the Json method from the controller which supplies the data that will be used to draw the chart.
I've successfully displayed one chart on my page but still need to display two more charts. Is it possible to have multiple ajax methods on window.onload function?
Here is my code so far.
window.onload = function () {
$.ajax(
{
datatype: "json",
type: "POST",
url: "/CRM/GetIndustryTypeData",
data: JSON,
success: function (data) {
IndTypePieChart(data);
},
error: function () { alert("Error"); }
});
}

Stephen Muecke's answer will work 100%. Get rid of window.onload = function(){ and have any number of $.ajax() calls - positioned at the bottom of the page or wrapped in $(document).ready(){
}).

Related

jquery mobile 1.4 not updating content on page transition

From the index page, a user clicks a navigation link, the data attribute is passed via ajax, the data is retrieved from the server but the content is not being updated on the new page.
Been stuck for hours, really appreciate any help!
js
$('a.navLink').on('click', function() {
var cat = $(this).data("cat");
console.log(cat);
$.ajax({
url: 'scripts/categoryGet.php',
type: 'POST',
dataType: "json",
data: {'cat': cat},
success: function(data) {
var title = data[0][0],
description = data[0][1];
console.log(title);
$('#categoryTitle').html(title);
$('#categoryTitle').trigger("refresh");
$('#categoryDescription').html(description);
$('#categoryDescription').trigger("refresh");
}
});
});
Im getting the correct responses back on both console logs, so I know the works, but neither divs categoryTitle or categoryDescription are being updated. I've tried .trigger('refresh'), .trigger('updatelayout') but no luck!
This was not intended to be an answer (but I can't comment yet.. (weird SO rules)
You should specify in the question description that the above code IS working, that your problem occurs WHEN your playing back and forth on that page/code aka, using the JQM ajax navigation.
From what I understood in the above comment, you're probably "stacking" the ajax function every time you return to the page, thus getting weird results, if nothing at all.
Is your example code wrapped into something ? If not, (assuming you use JQM v1.4) you should consider wrapping it into $( 'body' ).on( 'pagecontainercreate', function( event, ui ) {... which I'm trying to figure out myself how to best play with..
Simple solution to prevent stacking the ajax definition would be to create/use a control var, here is a way to do so:
var navLinkCatchClick = {
loaded: false,
launchAjax: function(){
if ( !this.loaded ){
this.ajaxCall();
}
},
ajaxCall: function(){
// paste you example code here..
this.loaded = true;
}
}
navLinkCatchClick.launchAjax();

Ajax call on ruby on rails

I have a ajax call using ruby on rails. I'm getting a success but I don't know how to use the data result of the ajax call.
$.ajax({
url: "/search/get_listing?listing_id" + id,
dataType: 'JSON',
success: function(data) {
var listing = JSON.parse(data);
$("#modalPrice").html(data.city);
}
});
Controller:
#listings_data = Listings.find_by(id: params[:id])
render :json => #listings_data.to_json
Using data.city won't work. I'm expecting to get the values retrieve from the model by simply putting . on the variable
var listing = JSON.parse(data);
Still no luck. Help guys. Thanks!
JSON.parse is Ruby code, API of JSON gem. How can you guys use that in Javascript :)
jQuery can process JSON object data directly. Just use:
success: function(data) {
$("#modalPrice").html(data.city);
}
For example, you can render in the controller:
render :json => { :city => #listings_data }
On the JS:
success: function(data) {
var listing = data.city;
}
I'm having similar problems everytime I use AJAX in rails since the response seems to differ depending on how you return the value or how you are handling the success in JS. Try this:
success: function(data, status, xhr) {
var listing = JSON.parse(xhr.responseText);
$("#modalPrice").html(data.city);
}
I usually use Firebug (Firefox Plugin) to set a breakpoint in my success handlers to check the arguments where exactly the response is in. Sometimes it's in the first value, sometimes in some other and then it may be xhr.response or even xhr.responseText. It's confusing me every time.
To use Firebug for this, press F12 on your page, select the 'Script' pane and find the code you want to check. Click next to the row number of your code where you want your breakpoint. In this case, you could've chosen the var listing line. When the code is executed (after your click), the browser will stop there and you can check the passed arguments on the right side.

Using Ajax/jsonp to receive data from Web Api

I've built a simple web service using the Web Api and I want to consume it from a simple mVC view using jQuery. I'm developing on localhost and consuming the service from Azure, which is why I'm using jsonp.
When I run my jQuery I view in Fiddler and the request is successful and json sent back but the .Ajax function returns these errors:
NaN, parsererror, and callback was not called
<script>
$(function () {
var callback = function(data) {
alert(data);
};
$.ajax({
url: 'http://itjobsdirect.azurewebsites.net/api/values/getbytitle?title=developer',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'callback',
success: function (data) {
$('#main').text(data);
},
error: function(jqXHR, textStatus, error) {
alert(jqXHR.status + jqXHR.message);
alert(textStatus);
alert(error);
}
});
});
</script>
I found this question: JsonP with Web Api is it still relevant?
Thanks for your help!
Yes, the link to that question you have there is still relevant.
ASP.NET Webapi doesn't ship with a default formatter that understands the dataType of 'jsonp' and so the solution here is to add a custom JsonpMediaTypeFormatter (as shown in the answer for the questions you have linked).

Jquery: How to clear an element before appending new content?

This is my jquery code
$.ajax({
url: "PopUpProductDetails.aspx",
cache: false
}).done(function (html) {
$("#dialog").append(html);
});
The first time, it works just fine. It display the content of the PopUpProductDetails.aspx page. But, after that, If I click again, I get twice the same content, and so forth. I believe the problem is that I need to clear the dialog element first, before appending new content.
How do I do that?
.append() appends html to the end of existing html string, use .html() to replace what's currently inside of #dialog.
Inside the function clear the dialog first and then fill up with the content
$.ajax({
url: "PopUpProductDetails.aspx",
cache: false
}).done(function (html) {
$("#dialog").html("");
$("#dialog").html(html);
});
You can use .empty() first, then use .append() in one line :)
like this:
$.ajax({
url: "PopUpProductDetails.aspx",
cache: false
}).done(function (html) {
$("#dialog").empty().append(html);
});
in case you need to clear the dialog first use .empty() which is faster than .html("")
see Jquery Difference .html("") vs .empty()

jQuery UI AutoComplete Plugin - Questions

I have an ASP.NET MVC 3 Web Application (Razor), and a particular View with the jQuery UI AutoComplete plugin (v1.8).
Here's the setup i currently have:
$('#query').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Search/FindLocations",
type: "POST",
dataType: "json",
data: { searchText: request.term },
success: function (data) {
response($.map(data, function (item) {
return { name: item.id, value: item.name, type: item.type }
}))
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
// don't know what i should do here...
}
})
},
select: function (event, ui) {
$.get('/Search/RenderLocation', { id: ui.item.name }, function (data) {
$('#location-info').html(data);
});
},
delay: 300, minLength: 3
});
The AutoComplete returns locations in the world, basically identical to Google Maps auto complete.
Here are my questions:
1) What are the recommended settings for delay and minLength? Leave as default?
2) I thought about putting [OutputCache] on the Controller action, but i looks as though the plugin automatically does caching? How does this work? Does it store the results in a cookie? If so when does it expire? Is any additional caching recommended?
3) I've noticed if i type something, and whilst the AJAX request is fired off, if i type something else, the dialog shows the first result momentarily, then the second result. I can understand why, but it's confusing to the user (given the AJAX request can take 1-2 seconds) but i'm thinking about using async: false in the $.ajax options to prevent multiple requests - is this bad design/UX?
4) Can you recommend any other changes on my above settings for improving performance/usability?
1) It really depends on your usage and your data.
2) You should use [OutputCache]. If there's any caching happening on the plugin, it's only going to be for each user, if you use caching at the controller action level, it'll cache one for all users. (again, this might actually be bad depending on your usage, but usually this is good to do)
3) This questions kind of hard too because of the lack of context. If ajax requests are 1-2 seconds and there's no way to make this shorter, you really should be a pretty big delay in so that users aren't sending off many requests while typing out a long word (if they type slow).
4) sounds like you need to look at your /search/FindLocations method and see where you can do caching or pref improvements. Give us a look at your code in here and I can try to suggest more.

Resources