AJAX call won't work on production, but works local - ajax

I've got a very strange situation.
I'm using an AJAX call to pass some parameters to my code-behind and everything works fine on local, but on my production environment I'm not being able to recover the parameter values in code-behind.
I've added here a few breakpoints just to you show where the problem is. The first one captures some parameter values just to check if they are empty/null (it's not actually part of the code) and the second will return an error if "inscricao" is null (which should not be).
When running the app in my local environment, I'm able to get the parameter values without any problems, as shown here.
But the same app, accessing the same database, with the same values will enter the second breakpoint and return a message as such, on production.
I have other AJAX post methods in the same page that work just fine, and as I said, it works fine on local. Is there any way to find out why the same code doesn't run on production? The other AJAX methods I have on the same page also work on production, this is the only exception.
I'll add the AJAX code below:
$.ajax({
type: 'post',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('[name="__RequestVerificationToken"]').val());
},
url: '?handler=SolicitarSafe2Pay',
datatype: "application/json",
data: {
valor: valortotal,
IDInscricao: Number(inscricaoID),
HtmlResumo: resumoemail,
IDCupom: idUsoUnico,
Nome: $Nome.val(),
NomeSocial: $NomeSocial.val(),
CPF: $CPF.val(),
Telefone: $Telefone.val(),
CEP: $CEP.val(),
Pais: $Pais.val(),
Estado: $Estado.val(),
Cidade: $Cidade.val(),
Endereco: $Endereco.val(),
Numero: $Numero.val(),
Bairro: $Bairro.val(),
Complemento: $Complemento.val(),
FormaPagamento: Number($FormaPagamento.val()),
NomeCartao: $NomeCartao.val(),
NumeroCartao: $NumeroCartao.val(),
CVV: $CVV.val(),
Vencimento: $Vencimento.val(),
Parcelas: Number($Parcelas.val())
},
success: function (data) {
...
},
error: function (xhr, status, error) {
console.log(xhr); // to see the error message
}
});
I've tried adding the RequestVerificationToken as a header, directly on the data object and even decorate the page with [IgnoreAntiForgeryToken]. All these options work on my local machine, but the same error still occurs on production.

Related

2nd AJAX call to same URL fails - but works randomly and rarely

I am trying to get a response from a web service, specifically to add two WFS layers from geoserver to a leaflet web map. The first layer gets added no problem every time, but most of the time, the second layer fails, complaining that the callback function is not defined:
ReferenceError: getJson is not defined
But what is very strange to me is that the second layer will be added, only sometimes. Refreshing the page and trying again will almost always fail.
This is the code making the ajax call:
$(document).ready(function() {
...
$("#add-network-button").on("click", function() {setLocation("Moscow")})
function setLocation(locationName) {
var networkParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'netex:' + locationData[locationName].networkWFSName,
maxFeatures: 99999,
outputFormat: 'text/javascript',
format_options: 'callback: getJson'
};
addWebService(map, WFSURL, networkParameters)
var buildingParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'netex:' + locationData[locationName].buildingWFSName,
maxFeatures: 99999,
outputFormat: 'text/javascript',
format_options: 'callback: getJson'
};
addWebService(map, WFSURL, buildingParameters)
}
And here is the addWebService function:
var addWebService = function(map, WFSURL, WFSParameters) {
var leafletWFSParameters = L.Util.extend(WFSParameters);
console.log(WFSURL + L.Util.getParamString(leafletWFSParameters));
$.ajax({
url: WFSURL + L.Util.getParamString(leafletWFSParameters),
dataType: 'jsonp',
jsonpCallback: 'getJson',
success: handleJson,
cache: false
});
// TODO: add style
function handleJson(data) {
L.geoJson(data, {}).addTo(map);
}
}
You're using jsonp, which means the data you're getting back is not JSON, but javascript code that makes a call to a globally-defined function (which name is defined by jsonpCallback).
jQuery automagically creates a function with that name, performs the network request, and when that function runs, it destroys its own reference from the global scope.
You're performing two calls to addWebService() in quick succession, which trigger two jQuery $.ajax({jsonpCallback: 'getJson'}) calls. The second call is overwriting the globally-defined getJson callback function. When the first jsonp payload is received by your browser, the globally-defined getJson callback is destroyed. When the second jsonp payload is received, it tries to call a globally-defined getJson function, and failing. A classic race condition.
Let me quote jQuery's documentation for the jsonpCallback parameter on $.ajax(), empasis mine:
jsonpCallback
Type: String or Function()
Specify the callback function name for a JSONP request.
This value will be used instead of the random name
automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests.
I suggest you either use other transport format than JSONP, or use different callback names for each request.

jQuery-Mobile: ajax request stops working after changePage failure

I am presently developing a web application with jQuery mobile. However, I found that when a "changePage" fails, I can no longer send ajax requests. After the failure, all ajax requests return an error. Here's the code executed when the submit button on the form is clicked (it's a basic user login screen):
// Event when user click the Submit login button
$('#submitLogin').on("click", function () {
// submit the user credentials to the server
$.ajax({
type: "POST",
url: "./LogUser",
data: {
EmployeeID: $('#EmployeeID').val(),
EmployeePIN: $('#EmployeePIN').val()
},
dataType: "text",
async: true,
cache: false,
error: function (rqst, text, thrownError) {
$('#dlg-login-error-message').text(thrownError);
$('#dlg-login-error-popup').popup("open");
},
success: function (data) {
if (data == "Success") {
$.mobile.changePage("./LoadScreen/Menu");
}
else {
$('#dlg-login-error-message').text(data);
$('#dlg-login-error-popup').popup("open");
}
}
});
return false;
});
If the post itself fails, I can resubmit without problem. If the .mobile.changePage fails, a "page not found" is displayed, but I am not able to resubmit, ajax no longer making request to the server and jumping directly to the error callback with a "not found" error.
I am guessing the problem comes from the fact that jQuery mobile uses AJAX request to load pages, and that somehow, ajax calls are getting mixed up somewhere.
I did more tests, even intercepted the pageloadfailed event, but nothing works. After the page change failure, AJAX calls no longer sends anything to the server and jump automatically to the error callback function.
I tried with async=false, same problem. I tried debugging jQuery-mobile, but I am still not able to find the "changePage" function itself ( the .code is quite confusing ).
I just spent the last two days trying to figure out a way to resolve this and I am seriously thinking of using something else than jQuery-mobile for our development.
I have found a workaround for my problem, but I do not know the full impact of this solution yet.
To prevent the problem, I had to set the "pushStateEnabled" configuration option to "false".
So if you find yourself with the same problem, try putting the following in a script right before the loading of the "jQuery-mobile" script.
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
Example:
<!-- Load the script for jQuery -->
<script src="~/Scripts/jquery-2.1.4.js"></script>
<!-- Set default for jQuery-Mobile, before it is actually loaded -->
<script>
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
</script>
<!-- Load the script for jQuery-Mobile -->
<script src="~/Scripts/jquery.mobile-1.4.5.js"></script>

jQuery Ajax - Cant parse json?

I got a very strange problem, I thought this worked before but it doesn't any more. I dont even remember changing anything. I tried with an older jQuery library.
I got an error that says: http://i.imgur.com/H51wG4G.png on row 68: (anonymous function). which refer to row 68:
var jsondata = $.parseJSON(data);
This is my ajax function
I can't get my alert to work either because of this error. this script by the way is for logging in, so if I refresh my website I will be logged in, so that work. I also return my json object good as you can see in the image. {"success":false,"msg":"Fel anv\u00e4ndarnamn eller l\u00f6senord.","redirect":""}
When I got this, I will check in login.success if I got success == true and get the login panel from logged-in.php.
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.success(function(data)
{
var jsondata = $.parseJSON(data);
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});
Thank you.
If the response you have showed in the attached screenshot is something to go by, you have a problem in your PHP script that's generating the JSON response. Make sure that thePHP script that's generating this response (or any other script included in that file) is not using a constant named SITE_TITLE. If any of those PHP files need to use that constant, make sure that that SITE_TILE is defined somewhere and included in those files.
What might have happened is that one of the PHP files involved in the JSON response generation might have changed somehow and started using the SITE_TITLE costant without defining it first, or without including the file that contains that constant.
Or, maybe none of the files involved in the JSON generation have changed, but rather, your error_reporting settings might have changed and now that PHP interpreter is outputting the notice level texts when it sees some undefined constant.
Solving the problem
If the SITE_TITLE constant is undefined, define it.
If the SITE_TITLE constant is defined in some other file, include that file in the PHP script that's generating the response.
Otherwise, and I am not recommending this, set up your error_reporting settings to ignore the Notice.
Your response is not a valid JSON. You see: "unexpected token <".
It means that your response contains an unexpected "<" and it cannot be converted into JSON format.
Put a console.log(data) before converting it into JSON.
You shoud use login.done() , not login.success() :)
Success is used inside the ajax() funciton only! The success object function is deprecated, you can set success only as Ajax() param!
And there is no need to Parse the data because its in Json format already!
jQuery Ajax
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.done(function(data)
{
var jsondata = data;
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});

caching issue with jQuery/AJAX

I am getting data through $.ajax multiple times. However the data is not getting refreshed in every call. Rather I am getting the same data in every call to $.ajax. The code was working properly at my home.
However in below code if I substitute console.log("success "); with console.log("success "+data); and observe in chrome console, then the code works fine. I suspect its a caching issue, but can figure it out.
function getDataJSON()
{
originalData="";
new Date().toString();
$.ajax({
url: 'data.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
success: function(data)
{
console.log("success ");
...
...
Thanks
you can set cache Cache. by default it will set to cache=true.
from DOCS
If set to false, it will force requested pages not to be cached by the
browser. Note: Setting cache to false will only work correctly with
HEAD and GET requests. It works by appending "_={timestamp}" to the
GET parameters. The parameter is not needed for other types of
requests, except in IE8 when a POST is made to a URL that has already
been requested by a GET.
$.ajax({
url:'url',
cache:false,
.....
})
Like #Ravi said cache priperty is you're frined.
You should realy spend more time on studying you're weapon of choice!
Link => first hit on google if you search jquery ajax
There is another method of preventing caching. Just append some random number to url you are accessing.
For example:
"www.url.com?" + new Date().getTime()
or
"www.url.com?" + Math.random()
from Stack answer

request.xhr undefined in Ext JS

my web site is made using Ext JS 4.1 framework and ASP .Net MVC v3. When new frame is rendered there are 19 separate AJAX requests for retrieving data in JSON-format. All requests are familiar and made by Ext.Ajax.request(). Example:
Ext.Ajax.request({
url: getOrderLink,
method: "GET",
params: { recId: orderRecId },
headers: {
'Accept': 'application/json'
},
success: function (response) {
var order = Ext.decode(response.responseText);
...
}
});
In some cases there are errors in ext-all.js in
onStateChange : function(request) {
if (request.xhr.readyState == 4) {
this.clearTimeout(request);
this.onComplete(request);
this.cleanup(request);
}
},
where request has no property xhr so that request.xhr.readyState throws exception "Cannot read property 'readState' of undefined".
This errors appear not for all requests and don't effect site work(responses are retrieved successfully). Some times this errors don't appear at all. Timeout for all requests is set to 30s by default and they take about 1.5-2 seconds each.
I am using Google Chrome 21.
Could you please give me some idea why it's happening.
The problem seems to occur if and only if you have a breakpoint or a "debugger;" line in anything related to AJAX. For me it happened in Chrome, haven't tried other browsers yet.
In my case it happened when I had set a breakpoint in a load event handler for a store like code example below.
But the error occurrs if you set a breakpoint inside the Ext onStateChange function in the framework itself as well.
If disabling your breakpoints and debugger; calls removes the error you can safely ignore it!
There is a similar thread on ExtJS forums. Sencha might add a fix.
Ext.define('MyApp.controller.MyController', {
extend: 'Ext.app.Controller',
stores: ['Projects'],
init: function () {
this.getProjectsStore().addListener(
"load",
this.onProjectsStoreLoaded,
this
);
},
onProjectsStoreLoaded: function () {
console.log('MyController: onProjectsStoreLoaded');
debugger; // <- this causes the errors to appear in the console
SomeOtherThingsIWantedToDebug();
}
}

Resources