Loathing IE and it's refusal to respond to JQuery Post - javascript

Ladies / Gents:
Doing a $.post which works fine in Chrome & FireFox. IE - not so much...the success callback (addTicketAndRender()) never gets hit:
http://jsfiddle.net/AeQxJ/1/
I've read something about needing to do "cache-busting" against IE with my POST, but I'm relatively new to this stuff so don't know if that's the appropriate thing to try and if so, how to do it.
Source:
function addTicketAndRender(incomingTicket) {
console.log("Add and Render");
alert(incomingTicket);
}
$(document).ready(function() {
console.log('ready');
// variables to feed trusted ticket retrieval
var trustedURL = "http://tableau.russellchristopher.org/trusted",
userName = "foo",
serverURL = "http://tableau.russellchristopher.org/";
$.post(trustedURL, {
username: userName,
server: serverURL,
client_ip: "",
target_site: "",
cache: "false"
}, function(response) {
addTicketAndRender(response);
});
});​
Little help, please?
Update1: Switched this out to an ajax post: No difference. Still good on Chrome and Firefox, still dead in IE:
$.ajax( {
url : trustedURL,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false
} ).done( addTicketAndRender );
Update2: Integrated additional cache-busting technique. Same behavior - Chrome/FF works, nothing from IE - Using Fiddler, I can see the POST go out when running the code below from http://jsfiddle.net/AeQxJ/3//. In IE, that never happens. Tested outside of jsfiddle and see the same result. Next step: Rule out stupid IE browser settings on my part by testing on a box where I haven't touched browser settings.
function addTicketAndRender(incomingTicket){
alert(incomingTicket);
}
$(document).ready(function() {
// variables to feed trusted ticket retrieval
var trustedURL = "http://tableau.russellchristopher.org/trusted",
userName = "foo",
serverURL = "http://tableau.russellchristopher.org/";
var number=Math.floor(Math.random()*1);
$.ajax( {
url : trustedURL + "?" + number,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false
} ).done( addTicketAndRender );
});​
Update 4: Ruled out my copy of IE as an issue. Added error trapping code to the POST, and ONLY when running in IE, I see this thrown:
error: function(xhr, textStatus, error){
alert(xhr.statusText);
alert(textStatus);
alert(error);
//output:
// xhr.StatusText: No Transport
// testSttus: Error
// error: No Transport
Searching on "IE No Transport jquery POST" leads me here:
jQuery Call to WebService returns "No Transport" error
Post indicates adding jQuery.support.cors = true; should resolve the issue, but when I do, errors are returned:
//output:
// xhr.StatusText: Error: Access is denied
// testSttus: Error
// error: Error: Access is denied

Change
$.post( ...
cache: "false"
...
To:
$.ajax(...
cache: false,
...
Note, The first cache is a meaningless string, while the later is a Boolean false.

If the cache: false is not working for you, the old school way was to add a get parameter to the url, like a random number, so:
var number=Math.floor(Math.random()*1)
$.ajax( {
url : trustedURL + "?" + number,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false
} ).done( addTicketAndRender );
This should help you debugging as well (change from random number to sequential). If still doesnt work I remove .done and use something like complete i.e.
$.ajax( {
url : trustedURL,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false,
complete : function() {
addTicketAndRender
}
});
One last thing, if your doing this using your jsfiddle page, make sure you remove console.log() from your code, as this will cause IE to break (it doesn't understand console.log).

$.post is only a shorthand version of $.ajax() link: http://api.jquery.com/jQuery.post/
If you need more control I suggest using $.ajax() since you have a lot more option with the "native" method. Link: http://api.jquery.com/jQuery.ajax/
Besides a good coding tips concerning jQuery.ajax() is always set $.ajax({cache: false}) somewhere as a default, since IE is (surprise) the only browser with cache: true as default

IE tends to trip on console.log(''); statements. Try to wrap it into a Log() function:
function Log(text) {
try {
console.log(text);
}
catch (e) {
}
}
If that fixes your problem, you'll want to use this approach to using console.log() throughout your project.

Related

How to solve error parsing in dataTables?

I have a function button that carry user info fullname, after clicking the button, it will send fullname and level to an API to be process and the result should be display in dataTable. Unfortunately, I got this error.
This is console.log for console.log(params). {"task_level":3,"fullname":"Administrator"}
Below is console.log for console.log(params).
Both console log is similar to API's result.
I don't know which is proper.
JS 1st Try (1st Ajax to send the parameter to API and after return success hopefully working but not.
"<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$.ajax({
url : url_api + '/api/user_task',
crossDomain: true,
type : 'POST',
dataType : 'json',
data: params,
success: function(response){
if (response.status == "Success"){
console.log(response)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
},
error: function(e){}
});
}
JS 2nd Try
<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
Documentation says:
When using the ajax option to load data for DataTables, a general error can be triggered if the server responds with anything other than a valid HTTP 2xx response.
So, you have to check server-side response instead of search for problems on the front-end.
Also, in your case make sure
the plugin sends request to the same domain from which the current page is loaded;
browser security system doesn't prevent loading of external scripts - for example on http://localhost you cannot Ajax load a script from http://google.com without special measures;
you are specifying a relative path without a domain name (if you are using a single domain);
JSON data in response is a valid.
If you cannot alter the backend system to fix the error, but don't want your end users to see the alert message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it:
$.fn.dataTable.ext.errMode = 'throw';

Ajax call is throwing an Invalid Character error

I am working on a Java application using Struts 1.2. I am facing a blocking error when I make an AJAX call to a Struts action.
The struts action, getInfos.html, is called successfully but after that when I make the AJAX call I get the following error in the console:
Invalid Character/parsing error
The data variable is a correct JSON format. Why would it trigger this error?
I've gone through all the similar questions online but I don't know why it's triggering an invalid character error.
$.ajax({
type: "POST",
url: "getInfos.html",
dataType: "json",
async: false,
cache: false,
data: {
Code: "code1",
type: "type",
mand: "mand",
signature: "signature"
},
success: function(data) {
console.log('succes');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
In the execute method that is handling the ajax request, i am calling the attributes using the request
final String code = (String) request.getAttribute("code");
final String signature = (String) request.getAttribute("signature");
final String type= (String) request.getAttribute("type");
/*
Making a call to a webservice using the attributes bellow,
using **response** Object
*/
if (reponse != null &&
(CodeReponseHttp.OK.equals(reponse.getCodeReponse()))) {
jsonObj.put(SUCCESS_CALL, true);
} else {
jsonObj.put(SUCCESS_CALL, false);
}
return new JsonResult(jsonObj);
But they are set to null; which means that the ajax data is not passed into the request, when I debug the execute method and I explicitly set values to these attributes everything works fine.
new JsonResult(jsonObj) is a generic class with a constructor that accepts a JSONObject
Like Rory McCrossan Comment it could be the response you got is not a json and your code expect a json response
When i comment dataType param it work fine
$.ajax({
type : "POST",
url : "getInfos.html",
//dataType : "json",
async: false,
cache: false,
data: JSON.stringify({
Code : "code1",
type : "type",
mand : "mand",
signature : "signature"}),
success : function(data){
console.log('succes');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
The problem had been solved, after debugging, the response type was not a JSON since there is a redirection to an error page if an exception is thrown, the exception was thrown because the data attributes were null, and it turned out that they are parametres not attributes, so getting the parameters solved the problem.
request.getParameter("code");
thank you all for your collaboration.

How to prevent Backbone.js routing (or history) to automagically add parameters to GET-request?

I have a very strange issue here, that I think has got something to do with the Backbone.js routing.
In our mobile app, there is a login-screen, that executes a AJAX-Post-Request (with jQuery), that runs against an API. Username, password and a third parameter are in the POST-body. This works like a charm.
The strange behaviour kicks in, after Backbone.js begins to to do some routing. After re-directing the browser, (only!) the username and password are send as a parameter-list to the GET request.
So the request i.e.
http://localhost:3000/#login
for unknown reason becomes
http://localhost:3000/?username=myuser&password=mypassword#login
Please notice, that the new parameters in the GET-request are not 100% part of the POST-body, because the savePassword-parameter is missing. Also notice, that the login-request goes against the API, (/api/user/login), not the route of the login-screen (/#login)
I already tried out a lots of things, also taking all the backbone-sourcecode apart, but still can't find how to prevent this behaviour.
Another notice: I see this only on mobile, so in the UIWebView on iOS and the WebView-object on Android. Maybe this issue is also related to the mobile...
I am very happy for any help, answers or hints, how to disable this behaviour and get the username/password out of this freakin URL.
Edited:
This is the AJAX-Request for loggin in.
login: function(username, password, savePassword, successcallback, errorcallback) {
$.ajax({
method: 'POST',
dataType: 'json',
url: config.api_base_url + 'user/login',
data: {
username: username,
password: password,
savePassword: savePassword
},
success: function(data, response, xhr) {
app.auth_token = xhr.getResponseHeader('Authtoken');
$.cookie('auth_token', app.auth_token);
if (successcallback) {
successcallback();
}
},
error: function(data) {
if (errorcallback) {
errorcallback(data);
}
}
});
}
According to jQuery.ajax() docs:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
And than, you should add in your settings processData equal to false:
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
Code jQuery.ajax():
login: function(username, password, savePassword, successcallback, errorcallback) {
$.ajax({
method: 'POST',
dataType: 'json',
url: config.api_base_url + 'user/login',
data: {
username: username,
password: password,
savePassword: savePassword
},
processData: false,
success: function(data, response, xhr) {
app.auth_token = xhr.getResponseHeader('Authtoken');
$.cookie('auth_token', app.auth_token);
if (successcallback) {
successcallback();
}
},
error: function(data) {
if (errorcallback) {
errorcallback(data);
}
}
});
}

Why does this AJAX POST fails with elasticsearch? [duplicate]

I am trying to send an Ajax POST request using Jquery but I am having 400 bad request error.
Here is my code:
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
},
error: function(e) {
console.log(e);
}
});
It Says: Can not build resource from request.
What am I missing ?
Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object.
So the correct version is here:
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: JSON.stringify({
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}),
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
May be it will help someone else.
In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.
It turned out to be the anti forgery token.
$.ajax({
url: "/Cart/AddProduct/",
data: {
__RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
productId: $(this).data("productcode")
},
The problem was that the .Net controller wasn't set up correctly.
I needed to add the attributes to the controller:
[AllowAnonymous]
[IgnoreAntiforgeryToken]
[DisableCors]
[HttpPost]
public async Task<JsonResult> AddProduct(int productId)
{
The code needs review but for now at least I know what was causing it. 400 error not helpful at all.
Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.
400 Bad Request
Bad Request. Your browser sent a request that this server could not
understand.
Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.
415 Unsupported Media Type
Try this.
var newData = {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
};
var dataJson = JSON.stringify(newData);
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: dataJson,
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.
The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.
You have to get name and value from craft in your template :
<script type="text/javascript">
window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>
and pass them in your request
data: window.csrfTokenName+"="+window.csrfTokenValue
You need to build query from "data" object using the following function
function buildQuery(obj) {
var Result= '';
if(typeof(obj)== 'object') {
jQuery.each(obj, function(key, value) {
Result+= (Result) ? '&' : '';
if(typeof(value)== 'object' && value.length) {
for(var i=0; i<value.length; i++) {
Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
}
} else {
Result+= [key, encodeURIComponent(value)].join('=');
}
});
}
return Result;
}
and then proceed with
var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: buildQuery(data),
error: function(e) {
console.log(e);
}
});
I'm hoping this may be of use to those encountering 400 errors while using AJAX in Wordpress going forward. Even though this question is many years old, the solutions provided have all been programmatic, and I'm sure many have stepped through their code to repeatedly find it's correct, yet continue to find it is not working.
I found dozens of results asking how to resolve "WP AJAX request returning 400 Bad Request" or "WP AJAX request returning 0" and nothing today worked.
Googling "How do I fix 400 bad request on Wordpress?" finally resulted in the answer appearing from https://wp-umbrella.com/troubleshooting/400-bad-request-error-on-wordpress/
Clear your Web Browser Cache and Cookies
You may be surprised, but most 400 errors in WordPress can be fixed by clearing your browser's cache and cookies. Browser caches temporarily store images, scripts, and other parts of websites you visit to speed up your browsing experience.
Clearing both my cache and cookies saw the 400 Bad Request code disappear and results return AJAX results as expected.

How to make a successful JSON call from Javascript

I am baffled by this for very long now. I want to gain this precious knowledge of making JSON call properly. Help me Humans.
So I'm making a call exactly like this:
$.ajax({
type : "POST",
url : "http://quote.mythicalQuotes.com/unicorn/service/historical/json?callback=callme&symbols=APPL",
dataType: "text",
cache : false,
data : My_Array,
error : function(request,error){alert(request+" "+error); },
success : function(data)
{
alert("Response" + data);
}//success
}).fail(function(textStatus, errorThrown) { alert("error Error");
console.log("The following error occured: "+ textStatus, errorThrown); });
But it fails and throws 'error' alert. Good Coding!
Now pasting "http://quote.mythicalQuotes.com/unicorn/service/historical/chart/lite/json?callback=callme&symbols=APPL" on my browser URL gives me nice JSON of format:
callme(
{
"SYMB" : [
{
"DESCRIPTION" : "APPL,
"BARS" : {
"CB" :[
{
"lt" : "09-01-2011::20:00:00",
"op" : "16.31",
"cl" : "15.22",
"hi" : "16.45",
"lo" : "14.72",
"v" : "17768019"
},
{
"lt" : "09-02-2011::20:00:00",
"op" : "15.22",
"cl" : "14.22",
"hi" : "19.45",
"lo" : "10.72",
"v" : "17768000"
}
]
}
]
})
So what atrocity am I doing here which is provoking my anger toward this particular Javascript semantics/syntactics?
Couple of reasons I thought which might cause this.
1. Same origin policy.
2. Wrong JSON format being return.
3. Stupidity of my code.
Please help.
This is a JSONP-type response. Add dataType: jsonp to the JQuery AJAX request. Since you're also specifying the callback function explicitly, add jsonpCallback: callme also. See the JQuery docs for more info (scroll down to the "dataType" section).
$.ajax({
dataType: "jsonp",
jsonpCallback: "callme",
// ...
success: function(data) {
alert(data); // should show the JSON: { "SYMB" : ... }
}
});
You mentioned the cross-domain policy; the JSONP spec is a workaround for this policy blocking cross-domain requests. The idea is that, rather than returning data, the server returns a Javascript snippet containing data. The client then executes the returned function to retrieve the data. The JQuery ajax method has built-in functionality to handle all this "behind the scenes".

Categories

Resources