jQuery does not work in IE11, but works in Chrome - javascript

I have problem with jQuery. When I upload image in Chrome it performs the AJAX successfully and I am able to update the page with the response data. But in IE 11 and Firefox it does not. The code:
$(".newfoto").on('submit', (function(e) {
$("#mailresult").html('<img src="themes/standart/iconss/spin1.gif" alt="loading..." /><p>Please, wait...</p>');
e.preventDefault();
$.ajax({
url: "dataok.php?act=foto",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#mailresult").html(data);
setTimeout(function() {
$("#mailresult").empty();
}, 2000);
var imgTag = '<img src="image.php?imgid=' + escape($('.myphoto').attr('id')) + '" />';
$('.myphoto').html(imgTag);
},
error: function() {}
});
}));

The correct way to prevent the form from submitting and reloading the page is to use a return false; at the end of the submit function. This will also replace e.preventDefault(); in your code.
Also, FormData is not supported on all browsers. See https://stackoverflow.com/a/2320097/584192. You may need to detect and workaround this.
$(".newfoto").on('submit', function(e) {
$("#mailresult").html('<img src="themes/standart/iconss/spin1.gif" alt="loading..." /><p>Please, wait...</p>');
$.ajax({
url: "dataok.php?act=foto",
type: "POST",
data: (typeof FormData === 'function') ? new FormData(this) : $(this).serialize(),
contentType: false,
cache: false,
processData: false,
success: function(data) {
// success
},
error: function(jqXHR, status, error) {
console.log(error);
}
});
return false;
});

Related

Php $_FILES is empty when upload with ajax

I have form with input for attachment:
<form enctype="multipart/form-data" action="" method="post" id="sendInvoiceForm">
.....
<div class="templateDiv">
<span class="invoice_email_label">Email attachments:</span>
<input name="email_attachment[]" type="file" multiple="">
</div>
<div class="templateDiv">
<button id="send_invoice_btn" class="bigButton redButton">Send</button>
</div>
</form>
And js:
data = new FormData($("#sendInvoiceForm")[0]);
data.append('flagSend', 1);
data.append('send_invoice_subject', sendInvoiceSubject);
....
$.ajax({
type: 'POST',
data: data,
processData: false,
contentType: false,
url: sJSUrlSavePdfInvoiceToServer,
dataType: 'json',
success: function (data) {
if (data.msg === 'Error. This invoice number exists.') {
alert(data.msg);
} else {
...
}
},
error: function () {
alert('error');
}
});
I tested and seems it doesnt work. All data pass well, but not file.
When I print_r $_FILES it is empty. What is my error? Thanks.
it's work for me --
var form_data = new FormData($('#submitForm')[0]);
$.ajax({
url: "<?php echo base_url() . 'backends/update_documents' ?>",
type: "POST",
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (res) {
// console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
//console.log(xhr);
}
});
you can try with cache: false
and mention for button, type="button"
this is what i do and works
append the formdata,
var formData = new FormData(your_form);
// for multiple files , because i need to check
new_files is class, i use because i am creating form dynamically
$.each($(".new_files"), function (i, obj) {
// console.log(obj.files);
$.each(obj.files, function (j, file) {
var max_size = 5120000;
var file_type= file.type;
var match = ["image/jpeg", "image/png", "image/jpg", "application/pdf"];
// after validation etc
// append formdata
formData.append('file[' + j + ']', file);
});
});
// if you want something else,
formData.append("id", $('#kreditornr').val());
// ajax
$.ajax({
type: "POST",
url: "url",
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) {
// success
}
});
First remove dataType: 'json' Then if it still shows error then replace
data = new FormData($("#sendInvoiceForm")[0]);
with
data = new FormData($("#sendInvoiceForm").prop('files')[0]);
try to send the data via :
data: $('#sendInvoiceForm').serialize();

jQuery AJAX: Uncaught SyntaxError: Unexpected token

I am trying to update my div content with new content when the user uses the search textbox:
$('#business_request_filter_search_textbox').on('input propertychange paste', function () {
$.ajax({
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name";
type: "GET",
cache: false,
data: { search: $('input#business_request_filter_search_textbox').val() },
beforeSend: function(xhr) {
$('#request_area').html('<center>Please wait while we gather results...</center>');
},
success: function(data) {
$('#request_area').html(data);
},
});
});
Now I have a dropdown selecting what they want to filter the search by, the username or the business name. This is the line that is throwing the error.
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name";
Am I doing something wrong?
You should have a comma ',' at the end of the url line:
$('#business_request_filter_search_textbox').on('input propertychange paste', function () {
$.ajax({
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name",
type: "GET",
cache: false,
data: { search: $('input#business_request_filter_search_textbox').val() },
beforeSend: function(xhr) {
$('#request_area').html('<center>Please wait while we gather results...</center>');
},
success: function(data) {
$('#request_area').html(data);
},
});
});
You don't have dataType defined for the ajax call.
Add dataType which is the expected format of your ajax request which can be text, json etc
Try This Code
$('#business_request_filter_search_textbox').on('input propertychange paste', function () {
$.ajax({
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name",
type: "GET",
cache: false,
data: { search: $('input#business_request_filter_search_textbox').val() },
beforeSend: function(xhr) {
$('#request_area').html('<center>Please wait while we gather results...</center>');
},
success: function(data) {
$('#request_area').html(data);
},
});
});
Hope This help You :) Enjoy :)

jQuery ajax collision issue

I have been coding an ajax request and i have a problem with it.
var addonUploadForm = $('#addonUploadForm');
var addonUploadFormMessages = $('#addonUploadForm-messages');
$(addonUploadForm).submit(function(e) {
e.preventDefault();
//var formData = $(addonUploadForm).serialize();
//var formData = new FormData($(this)[0]);
var formData = new FormData($('#addonUploadForm')[0]);
$.ajax({
type: 'POST',
url: $(addonUploadForm).attr('action'),
data: formData,
xhr: function() { },
cache: false,
contentType: false,
processData: false // marked line of error
success: function(response) {
$(addonUploadFormMessages).removeClass('error');
$(addonUploadFormMessages).addClass('success');
$(addonUploadFormMessages).html(response);
$('#addonTitle').val('');
$('#addonDescription').val('');
$('#addonFile').val('');
grecaptcha.reset();
},
error: function(data) {
$(addonUploadFormMessages).removeClass('success');
$(addonUploadFormMessages).addClass('error');
grecaptcha.reset();
if (data.responseText !== '') {
$(addonUploadFormMessages).html(data.responseText);
} else {
$(addonUploadFormMessages).html('<div class="alert alert-danger fade in out">×<strong>Error!</strong> An error occured and your message could not be sent.</div>');
}
}
});
});
That is my code and on the marked line there is a missing , and this code works fine apart from doesnt display the request on the page and it instead just takes me to the ajax url but if i put the , in it does nothing when i submit the form no errors, no nothing.
Probably this line causes the error:
xhr: function() { },
without an xhr object you cannot send an ajax request.
So leave out this line.
Also you need to put the "," in at your marked line.
Your url opens because if you leave out the "," the function will throw an error and your e.preventDefault() won't work.
Also I would leave out these lines:
contentType: false,
processData: false
And you should probably escape the html content in this line:
$(addonUploadFormMessages).html(data.responseText);
Hope this helps.
I fixed it i had 2 versions of jquery runnning with noconflict and they where 1.11 and 1.4, and 1.4 was last loaded before this. So i had to change my no conflict to var jq1 = jQuery.noConflict(true); and then my ajax code to
var addonUploadForm = $('#addonUploadForm');
var addonUploadFormMessages = $('#addonUploadForm-messages');
$(addonUploadForm).submit(function(e) {
e.preventDefault();
var formData = new FormData($('#addonUploadForm')[0]);
jq1.ajax($(addonUploadForm).attr('action'), {
type: 'POST',
url: $(addonUploadForm).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
$(addonUploadFormMessages).removeClass('error');
$(addonUploadFormMessages).addClass('success');
$(addonUploadFormMessages).html(response);
$('#addonTitle').val('');
$('#addonDescription').val('');
$('#addonFile').val('');
grecaptcha.reset();
},
error: function(data) {
$(addonUploadFormMessages).removeClass('success');
$(addonUploadFormMessages).addClass('error');
grecaptcha.reset();
if (data.responseText !== '') {
$(addonUploadFormMessages).html(data.responseText);
} else {
$(addonUploadFormMessages).html('<div class="alert alert-danger fade in out">×<strong>Error!</strong> An error occured and your message could not be sent.</div>');
}
}
});
});

Ajax call to database not works

in my application I have to make an ajax call to php file.it works proper in all devices. but when I tried it on ipad mini it not calls the php, so that the functionality not works, I've seen so many question about this problem and edited my code like this.
jQuery.ajax({
type: "POST",
async: true,
cache: false,
url: "directory/phpfile.php",
data: data,
success: function(response) {
}
});
my old code is
jQuery.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
data: data,
success: function(response) {
}
});
and the problem still cant resolve . so please any one tell me how to resolve this.
Please use this code
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
<script type='text/javascript'>
$(document).ready(function startAjax() {
$.ajax({
type: "POST",
url: "test.php",
data: "name=name&location=location",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});

avoid showing values in url with jquery ajax

I am making ajax call to login with spring security but it shows username and password in the url no matter what.
ex: /?j_username=s&j_password=s
I am trying to find my mistake for a long time but I couldnt be able to see it. It is probably a small mistake.
here is my ajax call;
function performLogin() {
var j_username = $("#j_username").val();
var j_password = $("#j_password").val();
$.ajax({
cache: false,
type: 'POST',
url: "/login",
crossDomain: true,
async: false,
data: { 'j_username': j_username, 'j_password': j_password},
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("x-ajax-call", "no-cache");
}
});
}
Thanks
EDIT:
It is resolved by adding `return false;`
But I am not sure if my approach is good. Here is the update;
'function performLogin() {
var j_username = $("#j_username").val();
var j_password = $("#j_password").val();
$.ajax({
cache: false,
type: 'POST',
url: "/Mojoping2/login",
crossDomain: true,
async: false,
data: { 'j_username': j_username, 'j_password': j_password},
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("x-ajax-call", "no-cache");
},
success: window.location.reload()
});
return false;
}
It has nothing to do with the Ajax call. You are not cancelling the form submission!
function performLogin() {
var j_username = $("#j_username").val();
var j_password = $("#j_password").val();
$.ajax({
cache: false,
type: 'POST',
url: "/login",
crossDomain: true,
async: false,
data: { 'j_username': j_username, 'j_password': j_password},
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("x-ajax-call", "no-cache");
}
});
return false;
}
and however you are adding the event
onsubmit="return performLogin();
If you are using jQuery to attach the event, you can use
function performLogin(evt) {
evt.preventDefault();
...
I created a jsfiddle to test your code and have been unable to replicate your bug. The POST request appears to submit normally (going via the chrome dev tools), and no extra GET values are appearing for me.
Demo: http://jsfiddle.net/5EXWT/1/
Out of interest, what version of jQuery are you using?
{this is just here so i can submit the jsfiddle}

Categories