I'm getting reports that a website I developed is not functioning as it should in IE 9 and IE 10. The problem occurs when attempting to submit a form:
$("form[name='signIn']").submit(function(e) {
var formData = new FormData($(this)[0]);
e.preventDefault();
$( "#return_status_sign_in" ).empty();
$.ajax({
url: "<?= SITE_URL ?>account/login",
type: "POST",
data: formData,
async: false,
success: function (msg) {
$('#return_status_sign_in').append(msg);
},
cache: false,
contentType: false,
processData: false
});
});
The above submits the form via AJAX in all other browsers and works perfectly. However, in IE 9 and 10, the page refreshes and the POST data appears as get variables in the URL. How come is this happening? Could it be that e.preventDefault(); is not triggering? If so, what's the alternative to that?
As I stated in my comment, IE 9 uses the 'xdomainrequest' object to make cross domain requests and 'xmlhttprequest' for other requests. Below is a sample of code that I use to work around this issue. 'xdomainrequests' only send 'plain/text.' They cannot send JSON:
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var xdr = new XDomainRequest(),
data = JSON.stringify(jsonData);
xdr.open('POST', 'http://www.yourendpoint.com');
xdr.onload = function() {
// When data is recieved
};
// All of this below have to be present
xdr.onprogress = function() {};
xdr.ontimeout = function() {};
xdr.onerror = function() {};
// Send the request. If you do a post, this is how you send data
xdr.send(data);
} else {
$.ajax({
url: 'http://www.yourendpoint.com',
type: 'POST',
dataType: 'json',
data: {
// your data to send
},
cache: true
})
.done(function(data) {
// When done
})
.fail(function(data) {
// When fail
});
}
Related
i have this js that requests the user to be logged out whenever they close the tab/window and cancels that request when the user does an window.onload shortly after a few second to distinguish between refresh and exiting the tab/window. it works perfectly when on Chrome but when it comes to mozilla the window.onunload event gets triggered but does not trigger the ajax call. below are my codes
window.onunload = function(){
setCookie('tabs', parseInt(getCookie('tabs')) - 1, 99999)
if(parseInt(getCookie('tabs')) < 1)
{
if (window.localStorage) {
window.localStorage['myUnloadEventFlag']=new Date().getTime();
}
requestSessionTimeout();
}
};
window.onload = function(){
setCookie('tabs', parseInt(getCookie('tabs')) + 1, 99999)
if(parseInt(getCookie('tabs')) < 2 ){
if (window.localStorage) {
var t0 = Number(window.localStorage['myUnloadEventFlag']);
if (isNaN(t0)){
t0=0;
}
var t1=new Date().getTime();
var duration=t1-t0;
if (duration<10*1000) {
cancelSessionTimeoutRequest(); // asynchronous AJAX call
}
}
}
};
and here are the cancelSessionTimeoutRequest and requestSessionTimeout definitions
function requestSessionTimeout(){
var header = ''
var token = ''
$.ajax({
url:antiCsrfHost +"/addSessionToDeleteQueue",
type:"POST",
aysnc:false,
contentType: 'application/json; charset=utf-8',
success:function(d){
}
})
}
function cancelSessionTimeoutRequest(){
$.ajax({
type: 'GET',
url: antiCsrfHost + '/csrf' ,
xhrFields: true,
contentType: 'application/json; charset=utf-8',
aysnc:true,
success: function (data) {
$.ajax({
url:antiCsrfHost +"/removeSessionToDeleteQueue",
type:"POST",
data : null,
dataType : 'json',
aysnc:true,
contentType: 'application/json; charset=utf-8',
beforeSend : function(xhr){
xhr.setRequestHeader(data.headerName, data.token);
},
success:function(d){
}
})
}
})
}
Hey your code working on Google Chrome but not working on Mozilla....
Solution 1:
Means there may be a cache problem first you clear cache then relaoad your webpage
Or
Solution 2:
event.preventDefault();
Write this code inside windowonload function
This problem confused me. Why my code cannot run on the server (in local runs well). What is wrong with the uploaded code?
I did the first ajax setup for all ( my script )
$.ajaxSetup({
headers: { 'X-CSRF-Token' : tokenCsrf,
// 'Content-Type':'application/x-www-form-urlencoded; multipart/form-data; charset=UTF-8',
},
error: function(jqXHR, exception) {
var response = JSON.parse(jqXHR.responseText);
var message = '';
if(response.body){
message = (response.body.msg ? response.body.msg : response.body);
}else{
$.each(response, function (key, value) {
message += value[0] + '<br/>';
});
}
// scripts
},
beforeSend:function(){
// scripts
},
complete:function(){
// scripts
},
done:function(){
// scripts
}
});
and script ajax for uploading (cut)
var fd = new FormData($(this)[0]);
$.ajax({
url: url,
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
// scripts
}
});
so why in my bankend i use
dd($request->all()) // emtpy
if in my local work perfectly
UPDATE:
in my backend
public function myController(Request $request){
dd($request->all()); // <<--- empty ( nothing parameter from front)
}
in my case, why when submit form empty parameter, If in server, but work in local.
Solved
I got wrong config in PHP.ini
I have an older JAX-RS application that I'm running on IBM Liberty profile 16.0.0.4 with the jaxrs-2.0 feature. I'm getting some weird behavior that I can't explain, and need some help.
JAX-RS service code:
#Path("/loadData")
#POST
#Produces("text/plain")
public String loadData(#Context HttpServletRequest request) {
String id = request.getParameter("id");
String email = request.getParameter("email");
// add'l request processing code
}
JQuery code:
$(document).ready(function() {
var reqData = {id:"123456", email:"user#email.com"};
$.ajax({
type: "POST",
cache: false,
url: "http://localhost:9080/jaxrs/loadData",
data: reqData,
contentType: "application/json",
dataType: "json",
timeout: "30",
beforeSend: function() { ... },
success: function(data) { .... },
complete: function(data) { .... }
});
});
JQuery (in IE) Results:
request.getParameter("id") or ("email") = null;
request.toString() = org.apache.cxf.jaxrs.impl.HttpServletRequestFilter#f272c8dc
IOUtils.toString(request.getInputStream) = "id=123456&email=user1%40email.com"
SoapUI Results:
request.getParameter("id") = 123456 and ("email") = user#email.com;
request.toString() = org.apache.cxf.jaxrs.impl.HttpServletRequestFilter#de62638a
IOUtils.toString(request.getInputStream) = ""
I compared the RAW HTTP request in SoapUI and in IE's console, they both appears to be the same, as far as I can tell. So that's really got me confused, both JQuery and SoapUI are performing POST, but seems in IE's case the query stream is not being parsed into parameters, rather just maintained as a string. I've tried to mess around with the contentType and request declaration with no effects. I was originally using JQuery 1.7.1, but I tried on 3.1.1 with no effects. Has anyone seen this before. Any help or insights would be really great, thanks!
Try using "JSON.strigify" for params
$(document).ready(function() {
var reqData = {id:"123456", email:"user#email.com"};
$.ajax({
type: "POST",
cache: false,
url: "http://localhost:9080/jaxrs/loadData",
data: JSON.stringify(reqData),
contentType: "application/json",
dataType: "json",
timeout: "30",
beforeSend: function() { ... },
success: function(data) { .... },
complete: function(data) { .... }
});
});
After click on submit beforeSend: works but it does not call success: also there is no console error . The data also submit to database correctly ! Then why it not call the success: . Please Help
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
Console Message
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
In a Ajax call 'dataType' attributes means what data format can be expect from client(browser). As per error message server is returning 'string' instead 'json'.
But on the other hand, given ajax call is expecting json data to be returned by backend server. Either provide a
valid JSON in response or change datatype to html.
In your AJAX call settings you set dataType to json, but in return you provide a string.
dataType (default: Intelligent Guess (xml, json, script, or html)) The
type of data that you're expecting back from the server. If none is
specified, jQuery will try to infer it based on the MIME type of the
response
So, you have two solutions:
Provide a valid JSON in response
Do not ask for JSON by changing your dataType value (to html), or by removing it.
I had similar problem. As you are redirecting page in success you need to use
e.preventDefault(); // to prevent page refresh
after the ajax call or
return false; // to prevent page refresh
Something like this :
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});
I read that IE10+ is able to do cross-domain normally like all the other browsers, but it does not seem to work in my case.
When I start the request, IE simply reloads the page.
ajaxreq = $.ajax({
postData = {"movie":movie, "season":season};
url: "/cgi-bin/find_data.py",
type: "post",
datatype:"json",
cache: false,
async : true,
data: postData,
success: function(response){
var json = $.parseJSON(response);
}
})
.fail(function(err) {
alert("error" + err);
});
The same happens with XDR, though I would need that only if I cared about IE<10.
There are two solutions:
Change the input type of the button from submit to button
Add return false; in the onclick event