I'm using Ajax to pass my form data and files to a PHP file for processing.
Javascript:
$("form#applyform").submit(function(){
var data = new FormData();
jQuery.each($('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: 'ValidateApplication.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
ValidateApplication.php definitely exists. I can view it if I type in the address into the web browser, however when I submit the form chrome console returns 404.
The PHP is in the same folder as the HTML page the JavaScript is running on so I am confused as to why I keep getting a 404.
UPDATE
Changing POST to GET gets rid of the 404 error, but returns a 500 Internal Server Error
UPDATE 2
Changing the action of the form to ="ValidateApplication.php" and submitting it as normal (without AJAX) leads to the correct file without any errors.
I've had the same issue and after 2 hours looking for what was causing the 404 Not Found error I found that I was recently playing with the header() from PHP and had forgotten to delete the following line of code:
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
After deleting it, my Ajax functions became normal again.
It seemed to be a problem with the FormData object. Once I changed my method to use .serialize() instead, the page worked just fine.
$("form#applyform").submit(function(){
var data = $("form#applyform").serialize();
jQuery.each($('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: 'ValidateApplication.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
For me, it was that I used an input field with name="name" which made the called page return a 404. Weird stuff, hope this helps someone.
Try adding a / before the filename:
url: '/ValidateApplication.php',
Try changing the request type from POST to GET and see if it works.
Try commenting out parts of the code:
/*cache: false,
contentType: false,
processData: false,*/
Try another browser.
Please validate you have provided name="" attribute properly in the form
Form submit validate all bean attribute from name attribute of the input
Please check your PHP page name!
Do not use page-ajax.php, but instead use page_ajax.php.
Based on my case, I'd be sure to recheck your url address.
Related
I have an issue with jQuery AJAX call on my Laravel application. It fails when using type="file" in the form.
I can't reproduce the issue locally, it happens on prod server only.
$.ajax({
url: url,
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
...
The error I get is:
POST ... net::ERR_CONNECTION_CLOSED
No errors in Laravel logs, if I dump error in error callback there is only a message "error", so nothing helpful there.
What might be the issue?
For some reason the server freaks out if you set file type and try to submit a form without actually submitting the actual file. In that case the field comes up as having name "" and size 0.
Doing this worked like a charm:
var verifyIdentity = formData.get('verify_identity')
if(verifyIdentity && verifyIdentity.size === 0){
formData.delete('verify_identity')
}
I have done following code. Similar code at another place is working fine. But this place sometimes it works fine but some time it keeps loading. I checked my ajax request in network but nothing found. It keeps loading. There is no any JS / PHP Error in console.
I even tried to add cache:fale and async:false/true. But nothing works.
Note: when i trie to upload a image it keeps loading and if i press upload button again it works and image upload sometimes, some times it wont work.
Please HELP. Thanks in Advance :)
$.ajax({
url: 'upload_file',
data: data,
datatype: "json",
type: 'post',
contentType: false,
processData: false,
async: true,
error: function(error) {
console.log(error);
},
success: function(data) {
console.log(data);
}
});
I have a form that I need to process before it's submitted. The form has several text and radio inputs, as well as a file one. I'm using jQuery to pass the form data:
$button.on('click', function(e) {
e.preventDefault();
var formData = new FormData($('.js-my-form')[0]);
$.ajax({
type: 'GET',
url: '/get-data',
data: formData,
contentType: false,
processData: false
}).done(function(response) {
// handle response
});
});
Then, in Laravel controller:
$input = Input::all() // <- EMPTY ARRAY
No idea why Input comes empty. Any help appreciated.
Your problem is that you are using a GET to send a request with enctype = multipart/form-data. When you use a native FormData object this is the format that you get by default. You can read how to send the form's data
using the POST method and setting the enctype attribute to application/x-www-form-urlencoded (default);
using the POST method and setting the enctype attribute to text/plain;
using the POST method and setting the enctype attribute to multipart/form-data;
using the GET method (in this case the enctype attribute will be ignored).
So if you set your requesto to a GET the content of your form present in the body of the request will be ignored. The enctype attribute is what tells the server how to process your request. This is why you should use POST.
Note that when you write
contentType: false,
processData: false
you are telling jQuery that do not mess with the data you are passing and leave your native Formdata object untouched. This will cause the enctype to be set automatically.
First i suggest use a type 'POST' to pass your data at your method and second, try serialize the form data
$.ajax({
type: 'POST',
url: '/get-data', /*Route laravel*/
data: formData.serialize(),
contentType: false,
processData: false
}).done(function(response) {
// handle response
});
So, I could not find any resource to confirm this, but it seems FormData won't work with GET type - at least when using jQuery's $.ajax() function.
Changed GET to POST - and the form input is getting to the Laravel controller with no problems.
Not sure I like it, thought, as I'm actually not POSTing anything, but GETting information I need. Anyways, it works.
I'm trying to make an AJAX request send a file towards my controller, which then should proceed to read out the sent file and return a sorted array back to the front-end, though it doesn't work as I'm stuck on a 'blob' not set error. I've searched about but didn't really find the answer I was looking for, thus why I'm creating this question.
Currently I'm receiving the following TypeError:
'slice' called on an object that does not implement interface Blob.
The data that I'm trying to send is as following:
http://piclair.com/qk8ms (pic because I can't copy the data directly from my browser.)
The javascript:
// Click handler for file read
$(document).on('click','#load-csv-btn',function(e){
e.preventDefault();
var file = $('#file_upload')[0].files;
console.log(file);
readCSV(file);
});
function readCSV(file){
$.ajax({
type: "POST",
url: "ajax/read.php",
data: {file: file},
contentType: false
}).success(function(data){
console.log(data);
}).fail(function(){
console.log('error');
});
}
The PHP handler, though I guess that part is kind of irrelevant for this problem:
<?php
var_dump($_POST);
I've found someone saying that setting processData: false and contentType: false would let the script ignore the blob requirment, but if I set those parameters my server just sends back an empty array, which I guess is no suprise as I'm not processing any data.
So I'm hoping someone knows a solution to this problem and is able to help me out.
EDIT:
Just to make clear which method I've tried that returns an empty array, here is the alternate code:
$(document).on('click','#load-csv-btn',function(e){
e.preventDefault();
var file = $('#file_upload')[0].files[0];
var fd = new FormData();
fd.append("csv",file);
readCSV(fd);
});
function readCSV(file){
$.ajax({
type: "POST",
url: "ajax/read.php",
data: {file: file},
contentType: false,
processData: false
}).success(function(data){
console.log(data);
}).fail(function(){
console.log('error');
});
}
As far as I am concerned AJAX uploads are not easily done without external libraries. At least, that is what I learned the first time I needed this done.
http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
This guide is pretty good, but a little bit outdated if you are using a newer version of jQuery.
You might need to change some deprecated functionality such as (.live() to .on()).
In the end I can warmly recommend it as a good start. I've used it widely for years and with great success.
Good luck!
I have the following code :
$("#loginSubmitButton").on("click",function(){
var loginUserDetails = {
email: $("#email").val(),
password: $("#password").val()
};
//Send the AJAX request to authenticate the user
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: JSON.stringify(loginUserDetails),
contentType: "application/json;charset=UTF-8",
dataType: "json",
}).done(function() {
$("#loginResult").text("Login successful");
})
.fail(function() {
$("#loginResult").text("Login failed");
});
});
As per the jquery documentation (unless I am understanding something incorrectly) I expect the done to be fired if I receive a 200 OK from my web server. However, in chrome console I can see a 200 OK response but jquery seems to fire the fail handler.
Does anyone have any idea what I might be doing wrong here?
You need to remove:
dataType: "json"
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's probably ignoring the underlying issue. It's most likely caused by a parser error (the browser parsing the json response). Firstly examine the XHR parameter in either .always() or .fail().
Assuming it is a parser fail then why? Perhaps the return string isn't JSON. Or it could be errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
If your server returns empty string for a json response (even if with a 200 OK), jQuery treats it as failed. Since v1.9, an empty string is considered invalid json.
Whatever is the cause, a good place to look at is the 'data' parameter passed to the callbacks:
$.ajax( .. ).always(function(data) {
console.log(JSON.stringify(data));
});
Its contents will give you an understanding of what's wrong.
Need to remove , from dataType: "json",
dataType: "json"
The ajax URL must be the same domain. You can't use AJAX to access cross-domain scripts. This is because of the Same Origin Policy.
add "dataType:JSONP" to achieve cross domain communication
use below code
$.ajax({
URL: cross domain
dataType: 'jsonp'
// must use dataType:JSONP to achieve cross domain communication, otherwise done function would not called.
// jquery ajax will return "statustext error" at }).always(function(data){}
}).always(function(data){
alert(JSON.stringify(data));
}
A few things that should clear up your issue and a couple hints in general.
Don't listen for a click on a submit button. You should wait for the submit event on the form.
The data option for $.ajax isn't expecting a JSON string. It wants a serialized string or an array with name and value objects. You can create either of those easily with .serialize() or .serializeArray().
Here is what I was thinking for your script.
$('#form-with-loginSubmitButton').on('submit', function(e){
e.preventDefault():
var $form = $(this),
data = $form.serializeArray();
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: data
}).done(function(result){
console.log(result);
});
});