Only IE 11 losing focus on ajax call sometimes ASP.NET MVC4 - javascript

I am using a boostrap dialog box to pull in a list with a quantity. After I submit my form, and open the dialog box to check to see if the quantity has updated, it seems to be stale data. I have a call with ajax to the controller and then back to the database to pull in updated info. But when I set a breakpoint in the controller (on server side) it never hits. IT ONLY kicks out of the issue when I set a breakpoint to the function calling ajax within developer tools and debugger. I don't see any console errors either.
I don't have an issue with Firefox, just IE11.. here is the code:
<script type="text/javascript">
function LocationModal() {
$("#GetLocBtn").attr("disabled", "disabled");
var partNumber = $("#PartNum").val();
var Condition = 'Z';
var urlQry;
var receiveIsChecked = document.getElementById('Receive').checked;
var src = 'removed for security';
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { partNumber: partNumber, CCODE: Condition },
beforeSend: function () {
},
success: function (data) {
$("#LocationModalContainer").html(data.LocationModal);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
};

The problem is indeed that IE caches the results of Ajax calls. You can prevent that behavior either by adding cache: false to every call, like you've discovered, or setting it globally via ajaxSetup before you make any calls.
$.ajaxSetup({
cache: false
});
The use of ajaxSetup is discouraged in the jQuery documentation, but might be a good solution for you if you don't use any plugins that might rely on the normal behavior and want to quickly make sure none of your own ajax calls is cached.
Personally, I have my doubts about how real the interference risk mentioned in the documentation is when it comes to the cache setting, since basically you just make IE behave like other browsers.

Related

asp.net webservice jquery populate textbox

I want to get 3 values from a web service by providing current URL and current user. My webservice accepts 2 parameter URL and user. Web service works fine.
Now I want to put this 3 values in 3 different textboxes using jquery.in txtOrgCity = city, in txtPin = pin, in txtCountry = country
bellow is code for txtOrgCity
$(document).ready(function () {
$('#txtOrgCity').val({
source: function (request, response) {
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
when I run it gives me [object object] in text box.
How do I define to grab City for txtOrgCity, pin for txtOrgPin, country for txtOrgCountry in response(data.d).?
and do I need to duplicate the same code for other 2 text boxes or any better way.?
Given code is just for some txtbox autocomplete and it works perfectly so I just wanted it to modify a bit for my need. $('#txtOrgCity').val was $('#txtOrgCity').autocomplete
Any help would be appreciated.
--
Thanks
I recommend that you open this up in google chrome. Open up your developer tools (press f12) and, open up resources and select the page you are currently working on. Then use the find box to search for your javascript method which fires the ajax and put a break point inside the success part of your ajax call. Now run your code and wait to hit the break point. Now you can see what is inside your data.d object. Do not resume and keep debugging. Open up your console tab and type data.d. you should see an intelicence option box with all the variables inside your data.d object. You should see the variable for city, pin and country in whatever way you named them when you deserialized your data and returned it as json to your ajax call.
If, for example, you write data.d.city in your console it should write out the corresponding value. The same goes for any other json variable your service passed back to the browser.
With that information it is easy enough to use jquery and do what you want with the data. So in the succes part of your ajax call you can write:
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
p.s. im writting on a phone.
For your example you should not write out the same code two more times. Do not call ajax inside a jquery .val(), that is wrong. Make a new function which handles your ajax, call it from the page load or anywhere you need :
function loadData(//put your user parameter in here if you need){
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
},
error: function (err) {
//welldone for handling your error message. Many people neglect this. As a developer that is like coding blindly. At the very least you can console.log(err); if you don't want the user to see
alert(err);
}
});
}
Instead of $('#txtOrgCity').val({})
In your .ready function make the AJAX call first.
Store d.OrgCity, d.OrgPin & d.OrgCountry into some local JavaScript variables. In the Ajax call success use these values to deposit into textboxes like
$('#txtOrgCity').val(d.OrgCity)
You are after JSON.stringify(). So where you specify your .val() You want .val(JSON.stringify());

JSON call giving value that is not actually in the .json file

I am a little new when it comes to JSON and Javascript , so please excuse me if if this is a stupid question, but I have run into a problem that is starting to drive me insane.
On a webpage I am including two scripts; jQuery and a file called "scripts2.js". In the same directory as scripts2.js, I have a JSON file; "settings.json". From within my "scripts2.js" file I am running he following code inside of a function.
var settingsPath = settings.json;
jQuery.getJSON(settingsPath, function (data){
jQuery.each(data, function(index){
console.log("!"+data[index].name);
/*unrelated other stuff */
});
});
Previously the settings.json file looked like this
[
{"name":"Standard Black"},
{"name":"Gold"},
{"name":"Silver"}
]
So naturally when I looked in the Chrome Dev Console the log would print out
!Standard Black
!Gold
!Silver
However, when testing what would happen upon editing my settings.json file I changed "name":"Gold" to "name":"Test".
[
{"name":"Standard Black"},
{"name":"Test"},
{"name":"Silver"}
]
After the json updates I tried refreshing the page but my console log is still printing out
!Standard Black
!Gold
!Silver
...
I am at a loss. I have no idea why the data being retrieved with jQuery.getJSON() is sending the data of my old settings.json even after the changes has been saved. I have perused my .php file (which is generating the HTML) , as well as my included javascript and there is no other mention of another json file or any sort of clone of my json file in any related directory.
I really have no idea what is going on and I am starting to go insane. Does anyone have an idea of what the issue might be?
I dont know if it matters but I am running a XAMPP stack on my localhost. All files (index.php, scripts2.js, and settings.json) are in a directory located inside XAMPP's htdocs folder.
EDIT: Thank you all for the speedy and thorough answers, many of you answered the question I was a bout to ask next. I really appreciate it!
This is because the browser is caching the file from your first request. Simply clear the cache and run it again and the new data will be retrieved.
UPDATE:
To prevent the browser from caching this file, change your AJAX settings like so:
jQuery.ajaxSetup({ cache: false });
Before you make the getJSON call
Try clearing web cache and restart local servers if you have not already
When using jQuery.ajax() instead of the shorthand method, you can disable caching like this:
jQuery.ajax(settingsPath, {cache: false})
jQuery will append a timestamp parameter to your request URL which changes with every request and therefore keeps the browser from caching the response.
To force the browser to get a new version each time you can use cache: false in jQuery.ajax()
$.ajax({
dataType: "json",
url: settingsPath,
cache: false,
success: function (data){
$.each(data, function(index){
console.log("!"+data[index].name);
});
}
});
Pass additional parameter to your requested url which value will change with every request.So,your browser will consider it as new request every time and will not cache the data.
var random = Math.round(new Date().getTime())
var settingsPath = 'settings.json&time=' + random;
jQuery.getJSON(settingsPath, function(data) {
});
});
You can use any algoritham that generate random new value everytime for random for every request.
OR
you can have same things with jQuery#Ajax method
jQuery.getJSON is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So, set the optional parameter cache to false (this value by default is always true):
$.ajax({
dataType: "json",
url: url,
data: data,
cache: false, // If set to false, it will force requested pages not to be cached by the browser
success: success
});
Therefore, your getJson becomes:
var settingsPath = settings.json;
jQuery.ajax({
dataType: "json",
url: settingsPath,
data: data,
cache: false,
success: function(data) {
jQuery.each(data, function (index) {
console.log("!" + data[index].name);
/*unrelated other stuff */
});
}
});

Dialog popup and spinner not behaving correctly

I want to popup/display a dialog. It has two tabs and in each of these tabs there is a table (lets say table1 and table2).
Both of these tables contain data those are populated by a rest/ajax service (lets say service1 and service2).
When each of these rest services completes, the table component is populated with the data.
On top of this, the dialog has a spinner widget activated when the dialog first pops up.
The spinner widget is deactivated when BOTH of the rest services have completed.
For table1 I have code that looks a bit like this :
this.updateTable1 = function (dialog)
{
dialog.setSpinner(true)
var call = {}
call.url = 'service1';
call.xmlHttpReq = $.ajax({
url: url,
dataType: 'json',
async: true,
type: 'GET'
}).always(
function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown)
{
dialog.table1.loadData(processedDataOrXHRWrapper);
dialog.setSpinner(false)
});
};
For table2 the code is pretty much the same.
Which means that it also has dialog.setLoading(false). This means that whichever process finishes first, the spinner is deactivated, which is incorrect behaviour.
Somehow the two ajax calls need to know about each other, but I don't like that idea :(. Should I have some kind of third object that stores state of which processes have finished?
I tried using ajax calls in sync mode, but that just blocks the display thread in the browser.
You can use Deferred promises to implement this.
var updateTable1 = function (dialog)
{
return $.ajax({
url: url,
dataType: 'json',
async: true,
type: 'GET'
}).always(
function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown)
{
dialog.table1.loadData(processedDataOrXHRWrapper);)
});
};
// and same for updateTable2
dialog.setSpinner(true);
$.when(updateTable1(dialog), updateTable2(dialog)).always(function() {
dialog.setSpinner(false);
});
Only issue with the above is that, if the ajax call in updateTable1 or updateTable2 fails, the always function is immediately called. If you don't want this - see the $.whenall function in the answer to this question:
jquery deferred - "always" called at the first reject

Ajax, Php- Postback only works on Firefox

Im using ajax postback to post all fields of a form to a php page, that sets some sessions.
It all works fine when im working with firefox, but when i tried chrome and IE, it just does
nothing..
Here is my ajax:
$.ajax({
type: 'POST',
url: '../client_controller/teste',
data: {
form: $('#the-form-' + num).serialize(),
key: num,
},
//async: false,
//crossDomain: true,
success: function (response) {
alert(response);
},
error: function () {
console.log($.makeArray(arguments));
},
complete: function () {
console.log($.makeArray(arguments));
},
});
I saw some posts about this, but all the solutions i saw do nothing in my case.
The comented async and cross, were some of them.. And i dont want an empty data:, since i need to send those values.
Regards
Remove the trailing comma
complete: function() {
console.log($.makeArray(arguments));
}
, <------ THIS ONE
});
Already found the answer!
When using serialize functions be careful when using markup language.
My problem was that I had a form that wasn't closed, and although it worked on Firefox, the other browsers couldn't process the serialize function!

IE incompatability with window.location.href

I'm using a callback from an AJAX post request to navigate to a new page, but it is not working on Internet Explorer. My code is as follows:
$.ajax({
type: "POST",
url: phpUrl,
data: data,
async: false,
success: function() {
if (navigator.appName == 'Microsoft Internet Explorer'){ window.location.href("/step2.php")}
else{ window.location.href = "/step2.php"}
},
dataType:'json'
});
This works fine on FF/Safari/Chrome but when I test it on IE it does not work. Is there a better way of redirecting to a new page? I'm using async:false as my data was not loading on Chrome/Safari if I did not use a callback as the page would just change before the POST request was complete.
It's the parentheses. href is not a function, so trying to invoke it—window.location.href("/step2.php")—is a TypeError.
Assign to href like you do on the next line, or better, use location.assign():
location.assign('/step2.php');
While you can directly assign to location's properties (location.href='...';) to cause the browser to navigate, I recommend against this.
Internally, doing so is just calling location.assign() anyway, and assigning to properties does not always behave the same in all browsers.
Regarding, async:false, never do that. If you make a synchronous XHR request, you're doing it wrong. 8.4% of reported IE9 hangs were due to synchronous XHR blocking the browser.
Given that you have it in a callback, the assignment to location won't happen until the POST completes, so I'm not sure what you mean by "the page would change before the POST completes." (Did you forget to cancel a form's submit?)
window.location.href = "/step2.php" is just fine.
IE only like full url.
var fullURL = 'http://www.your_site.com/step2.php';
$.ajax({
type: "POST",
url: phpUrl,
data: data,
async: false,
success: function() {
window.location.href(fullURL);
},
dataType:'json'
});

Categories

Resources