Convert Jquery-Ajax to native JavaScript - javascript

i have the following code in jquery-ajax that is working fine
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
$.ajax(attributes);
}
Now i want to convert this to native JavaScript Code and i am doing this and 403 error is occur and i am unable to get response.
let me know what changes i have to make to make it working like above code(using jquery-ajax)
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.responseType = 'json';
xmlhttp.overrideMimeType("application/json");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonResponse = JSON.parse(xmlhttp.responseText);
console.log(jsonResponse);
attributes.success(attributes.data);
} else {
console.log(xmlhttp.responseType);
console.log(JSON.parse(xmlhttp.responseXML));
console.log(xmlhttp);
}
}
xmlhttp.open(attributes.type, attributes.url);
xmlhttp.send(attributes.data);
}

Related

JavaScript Post and wait for Response JSON

Right now i have the following code below, this code posts some data to my page and waits for a response of status = SUCCESS or Failure. I am trying to understand if this is async or sync. How can I make this JavaScript query wait for the response and then run what is inside success? It doesn't seem to wait for the response of what it is posting to.
Thanks!
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.post('', form.serialize(), function(json) {
console.log(json)
if(json.status === 'SUCCESS') {
console.log('success');
window.open(json.imgid, '_self');
} else {
console.log('failure');
}
}, 'json');
$('#progress_bar').show();
}
I then tried to work on making it work the way i wanted by editing the code below but now its just returning the HTML contents of the entire page rather than the JSON response. Any idea why its not getting the JSON response?
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.ajax({
url: '',
type: 'POST',
data: data,
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}
Add dataType: 'json', below data: data,
my.submit = function() {
var form = $('#lines');
//console.log(form)
var data = form.serialize();
//console.log(data)
$.ajax({
async: false,
url: '',
type: 'POST',
data: data,
dataType: 'json',
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
window.open(json.imgid, '_self');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}

AJAX call gets a “400 bad request”

I am new to jquery, i am getting 400 bad request (i find in browser console).
$("form#upload").submit(function(){
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var formData = new FormData($(this)[0]);
$.ajax({
url : '/uploadController/upload',
type: 'POST',
data: formData,
async: false,
beforeSend: beforeSendHandler,
success: function (data) {
var msg=data.msg;
var obj=data.obj;
if(data.success == true)
{
$('#successmsg').html(msg);
$('.alert-success').show();
$('.alert-danger').hide();
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
}else {
$('#errmsg').html(msg);
$('.alert-danger').show();
$('.alert-success').hide();
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
POST url 400(Bad Request)
Here console showing in error $.ajax({ line on my js file.
But it working on some systems, i don't what is the problem.
Anyone has some ideas?? Thanks a lot.
Since you are using jQuery, you can get serialized you form with this line:
var formData = $(this).serialize()
Use this formData in the ajax and it should work (assuming the relative URL to post is correct)

Continuous ajax calls makes application crash

I have a html application which contains 4 ajax calls which runs continously every 2 seconds back to back. The objective is to read new and fresh data fron the db continuously and seamlessly.
function messagesreceived(){
var queryString = "XXXXXXXXX";
$.ajax({
url:queryString,
'Content-Type':'application/json',
method:'GET',
dataType:'json',
cache: false,
success:function(data){
displaymessages(data);
rendermessagesreceived();
},
complete: function(xhr,status){
setTimeout(messagesreceived,2000);
},
error: function(xhr,status){
if(xhr.status == 0){
footerText.setText("NETWORK DISCONNECTED");
}else{
footerText.setText("Something went wrong! Please reload the page!");
}
}
});
}
function loadreadings() {
var queryString = "XXXXXXX";
$.ajax({
url: queryString,
'Content-Type': 'application/json',
method: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
mapreadings(data);
plotreadings();
},
complete: function(xhr, status) {
setTimeout(loadreadings, 2000);
},
error: function(xhr, status) {
if (xhr.status == 0) {
footerText.setText("NETWORK DISCONNECTED");
} else {
footerText.setText("Something went wrong! Please reload the page!");
}
}
});
}
function loadreadings2() {
var queryString = "XXXXX";
$.ajax({
url: queryString,
'Content-Type': 'application/json',
method: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
initiate(data);
footerText.setText("");
},
complete: function(xhr, status) {
setTimeout(loadreadings2, 2000);
},
error: function(xhr, status) {
if (xhr.status == 0) {
footerText.setText("NETWORK DISCONNECTED");
} else {
footerText.setText("Something went wrong! Please reload the page!");
}
}
});
}
Its runs fine first 15/20 mins and then crashes. The below link is the screenshot of the error.
can anyone please suggest how to resolve this. Its a very critical issue that I have been facing from past 15 days. Googled for the solution but no luck.
Appreciate your time and help.
Thanks.

jquery ajax call response in javascript is blank

The fail function gives me a correct output, whereas the done function gives me blank. I am stuck with this for hours. Any idea on how to debug this?
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (contentType == null) {
contentType = "application/json";
}
var reqst = $.ajax({
beforeSend : function(req) {
req.setRequestHeader("Content-Type", "application/json");
},
url : url,
type : "post",
contentType : contentType,
data : paramsTable,
});
reqst.done(function(xhr){
alert(xhr.responseText);
});
reqst.fail(function(xhr){
alert(xhr.responseText);
});
I would like to recommend you to use Ajax jQuery API instead of the old Ajax requests. No body uses it today (almost nobody; since you use it)
$.ajax({
beforeSend: function(req) {
req.setRequestHeader("Content-Type", "application/json");
},
url: url,
type: "post",
contentType: contentType,
data: paramsTable,
success: function () {
// here the code to execute if success
},
error: function () {
// here the code to execute if error..
}
});
Why your code isn't working
Because you are never using the xhr to send the Ajax request so it has nothing to show as the response text. Funny isn't it? hehehe.
use this:
success: function(resp) {
alert(resp); // where resp is the name of the responseText here..
}
I have shown you how to use it. Good luck!
For more: http://api.jquery.com/jquery.ajax/
Try to use standard jquery ajax structure:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
})
.fail(function() {
alert( "error" );
});

Jquery not working in only ie8, all other browsers work fine

Here I am trying to load some data using Ajax.
In IE 9 and all other browser works fine.
But in IE8 it always goes to catch. I don't why it always fire an exception.
Here is my code.
var SyncResponseText = "";
var WrapedRequestObject = JSON.stringify(RstClientServerDTO);
try {
SyncResponseText = eval($.ajax({
type: "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: "../../ApplicationServiceHandler/ClientRequestHandler.ashx",
data: WrapedRequestObject,
timeout: 240000,
dataType: "json",
async: IsAssync,
success: function (msg) {
// if (msg == false) {
// window.location.href = window.location.href;
// }
// else {
SuccessCallBack(msg);
// }
}, // function (data) { alert('success') },
error: function (xhr, textstatus, error) { ErrorCallBack(xhr, textstatus, error) } // { alert('error') }
}).responseText);
}
catch (Exception) {
SyncResponseText = Exception.get_Message();
}
return SyncResponseText;
Don't use eval. That part of your code makes no sense.

Categories