ajax request sometime fails due to ERR_CONNECTION_RESET but not always - javascript

I am submitting a form using ajax. Form is consist of some textboxes, textareas etc (string data) and a file as well. I am sending the form as javascript FormData().
The problem is that the Ajax request sometimes failed but not always.
e.g. I tried to upload bigger files in zip, it was uploaded successfully five times but on the sixth attempt it got failed due to an error i got in the console "ERR_CONNECTION_RESET"
How to overcome this that it never happens. Thanks
Ajax Request using FormData():
var formData = new FormData();
formData.append("consider all my data here from form",data);
$.ajax({
url : 'abc.com/controller/function&token='+token,
type: 'post',
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
$("#loader").show();
},
complete: function () {
$("#loader").hide();
},
success: function(json){
$("#loader").hide();
console.log(json);
},
error: function(error){
console.log(error);
alert("Something went wrong while updating chapter info. Please, refresh and try again.");
}
});

Related

Checking if form has been submitted via ajax - PHP

As the title says, I wanna check if this ajax method has been submitted or not and show the result in a condition.
Here is the Ajax POST code;
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: handleResult
});
And here is the condition I put but it is not working.
function handleResult(data){
if(data == 'error'){
window.location.href ='404.php';
}
else{
$( "#clearcart" ).click();
window.location.href = "ordercomplited.php";
}
}
try this
$.ajax({
url: "addorderInfo.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert(data)
},
error: function (error) {
alert(error.responseText) // if your request doesn't work
}
});
There isn't sufficient code to know why is not working.
IMHO the ajax call is not handling the error. Try to edit your code as follow:
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: function(data) {
handleResult(data);
}
error: function(data) {
handleError(data);
}
});

Prevent Bootstrap Modal from showing using ajax error

I was wondering if there is a way to prevent the Modal from showing up when an ajax call returns an error. I've seen a few posts here already that use
e.stopPropagation();
but I couldn't manage to make that work. My ajax call looks as follow
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
//show error message
$('#alertdone').removeClass('hidden');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
//hides the error message
$('#alertdone').addClass('hidden');
}
});
Thanks
I am assuming that you need to hide (don't show) the modal if the AJAX calls fails (since there's a difference between ajax call failing and returning error from server side).
For that you need to remove your data-attribute from HTML and do something like this:
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
$('#alertdone').removeClass('hidden');
$("modal_selector").modal('hide');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
$('#alertdone').addClass('hidden');
$("modal_selector").modal('show');
}
});
If you want to hide/ show modal depending on condition use modal()
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
//show error message
$('#alertdone').removeClass('hidden');
$("Your_modal_id").modal('hide');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
//hides the error message
$('#alertdone').addClass('hidden');
$("Your_modal_id").modal('show');
}
});

JSON request jumping directly to error statement despite having response data sent from server

Background :
this is a simple ajax request to fetch data from database, my query and server side code works just fine.
Problem :
When i put the GET URL in my browser it shows the correct JSON response, but firebug (Firefox extension) doesn't show any response, and the error message is logged.
alert('success'); doesn't show
$('#loadOrderDetails').click(function () {
var id = document.getElementById("order_id").value;
var dataString = 'order_id=' + id ;
alert(dataString);
$.ajax({
type: "GET",
url: "index.php?route=new/orders/GetOrder",
data: dataString,
cache: false,
dataType: 'json',
success: function (data) {
alert ('success');
// my code to show data in table..
},
error: function (req, status, err) {
console.log('something went wrong', status, err);
}
})
});
any suggestions?
thank you all, it seems that my problem was because of www , i solved it in server settings .

How to push a JSON to a webservice using Ajax

I have a form on my HTML page with some fields to be filled and an option to upload a file. My Javascript function converts the inputs to the fom into a json file. I am trying to push this generated json along with the file uploaded by the user to a webservice but I am getting an error which says
405 OPTIONS
Here's the Ajax function I wrote. The formData.serializeObject() function gives me the Json output to the form.
$(function() {
$('form').submit(function() {
($('#file')[0].files[0].name);
var formData = new FormData($("form")[0]);
formData.append("filename", $('#file')[0].files[0].name);
var obj = new FormData();
form = form
$.ajax({
url: "Webserviceurl:port/function_to_send_json",
type: "POST",
data: JSON.stringify(formData.serializeObject()),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data) {
$.ajax({
url: "Webserviceurl:port/function_to_send_file",
type: "POST",
data: obj,
contentType: false,
success: function(data) {
},
error: function(data) {
console.log("Error Happened");
}
});
return false;
},
error: function(data) {
console.log("Error Happened");
}
});
})
});
What could I be doing wrong here?
The error message is being reported because you are making a preflighted request. This means the browser is sending an OPTIONS request asking for permission to make a POST request.
The server is responding to the OPTIONS request with a 405 error meaning "You can't make an OPTIONS request to this URL!"
That said …
data: JSON.stringify(…),
If you are sending JSON then you should say you are sending JSON, which ha a content type of application/json, not:
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
There is no serializeObject method on formData objects, so formData.serializeObject() should be throwing an exception.
This question covers how to upload files with Ajax.

AJAX is not sending request

I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});

Categories