jQuery AJAX fail with files in form request - javascript

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')
}

Related

Ajax Request to laravel for uploading a form sometimes work well but some times keep loading

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);
}
});

Laravel: I have some problem posting data with Ajax

Im new to using ajax and I have another post here about my code and they said it was correct.
However Im still facing issues
My code:
body[circle.id] = {id: currentid-1, x: event.offsetX, y: event.offsetY};
// Ajax
for(let i = 0;i < body.length;i++){
$.ajax({
url: 'get.php',
type: 'post',
data : {
data: body[i],
},
dataType: 'json',
});
}
The error:
[Error][1]
I cannot comment.
From the title I guess you are using Laravel.
I see you are hitting the file directly, but looks like you are showing only half the setup. In case Laravel.
What is the route setup?
And if the setup is like Route::get try Route::any.
How are you debugging the issue? Do you have any logs?
Can you check the logs of "web server"?
Either artisan serve or php -S should give at least some hints what your ajax is hitting.
According to the error image you have posted, The error says that the method only accepts the GET request but you are trying to make POST request in your AJAX method, Change your request type to GET like this,
$.ajax({
url: 'get.php',
type: 'get',
data : {
data: body[i],
},
dataType: 'json',
});
I fixed it.The problem was in url and routes

JS: FormData w/ File Input is Crashing Ajax Request

Got a really odd problem that didn't show up until I pushed my code to a live server and tried to use it with my iPhone.
This is submitting to a node.js script that I've set to log all incoming request (along with headers and methods) and the logs show nothing being received when the problem below presents itself.
So anyway:
$('#addrecord').on('submit', function(e) {
e.preventDefault();
var url = '/admin/app/addrecord'
var data = $('#addrecord')[0];
var formData = new FormData(data);
$.ajax({ // create an AJAX call...
data: formData,
processData: false,
contentType: false,
cache: false,
type: "POST", // GET or POST
url: url, // the file to call
success: function(response) { // on success..
if (response.name == 200) {
if (response.message == "add") {addComplete(response.address);}
else {editComplete(response.address);};
}
else {
console.log("Form Rejected");
}
},
error: function(response) {
console.log("Error - " + JSON.stringify(response));
}
});
});
This is paired with the usual <form id="addrecord" method="post" enctype="multipart/form-data" role="form"> ... </form> in my html file.
So the problem is that is this form I have an <input type="file" id="photo" name="photo"> input field. If I try to submit the form without an image selected in this input, the form doesn't send anything and just hangs. Absolutely nothing is received by the server (remember, I'm logging every request).
Now, if I use the file input to select an image off my phone, or if I edit the html to remove the input file field, the Ajax request fires without a hitch and everything is received perfectly by my node.js server.
I'm really stumped on this one. Any ideas?
Apparently, this is a bug in Safari.
Ended up detecting if a file had been selected, and if not, deleting the element from the DOM before submitting the form.

Jquery load function throws "XML Parsing Error: not well-formed" error in firefox

Trying to load an xml file and getting the xml parsing error.
$("#analyticForm_description").load('https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt', function() { MD.ui.editPallets.editform_definition(); } );
Should not throw any error. Note the url provided is valid and accessible from a browser directly. The function is also being called. Somehow even after the error reported on console, page loads successfully.
Do not want to see any errors reported on console.
I think Firefox expects an Content-Type and Chrome ignores it.
$.ajax({
url : "https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt",
contentType: "text/xml",
success : function(response) {
$("#analyticForm_description").html(response);
}
});
or for the load method use ajaxSetup:
Description: Set default values for future Ajax requests. Its use is
not recommended.
$.ajaxSetup({
contentType: "text/xml"
});
$("#analyticForm_description").load('https://192.168.23.10/SystemServices/...', function() {
MD.ui.editPallets.editform_definition();
});
I was also facing a similar error and upon search i stumbled upon this post, after debugging code for a while i found out the reason.
Error shown in console
XML Parsing Error: undefined entity
Location: path-to-file.html#link3
Line Number 26, Column 29:
Here is why i was getting this error
I was dynamically generating url that i want to hit, and due to some typo i was getting undefined as the url which was used in making ajax calls resulting in this issue
$.ajax({
url: url, //this was undefined
type: "get",
data: data,
contentType: "text/xml",
success: function (response) {
//some code
},
});
Posting this as it might help someone facing the same issue.

Jquery ajax returning 404 not found

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.

Categories

Resources