Jquery / JSON handle XHR Response - javascript

I am posting some JSON info using the code below. Currently, if it is successful (200 response) the alert pops up, but if it is unsuccessful nothing happens.
What I would like to do is basically say if successful do X, else do Y.
I have try using an if / else statement within the function, but it doesn't seem to work.
Apologies if this is a silly question, I am new to working with JSON, XHR etc. Any assistance would be greatly appreciated.
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);
EDIT: Working Code:
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback,
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError);
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);

add this line to your return jQuery.ajax({}) function:
error: function(xhr, ajaxOptions, thrownError){
window.alert(thrownError);
}
hope this helps~

Related

Firebase Dynamic Link Creation With JavaScript

var object={
"longDynamicLink": "https://[APP_NAME].page.link/?link=[LINK_HERE]",
"suffix":{
"option":"SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
dataType: "json",
data: object,
success: function(response, textStatus, jqXHR) {
alert(response.shortLink);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
The above code works if the "suffix" is deleted from the request. That makes an "UNGUESSABLE" url, but I want a short URL. As stated in the documentation at https://firebase.google.com/docs/dynamic-links/rest?authuser=0 I added the suffix option parameter, but it results with a 400 response. Any ideas why?
I haven't ever tried this but, ...
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=api_key
var params = {
"longDynamicLink": "https://example.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
"suffix": {
"option": "SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
data: jQuery.param(params) ,
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});

Post AJAX API Javascript SAPUI5 failed

I want to use POST method with AJAX in SAPUI5 javascript but I found an error.
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({
nomorDosir: "01001961288",
kodeCabang: "A02"
}),
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: " + data + " " + JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});
error:
I already did change code with dataType=text, or data: {nomorDosir: "01001961288", kodeCabang: "A02"} (without stringify), but I not yet find the solution. How to fix this problem?
Thanks.
Bobby
Not sure what your use case is but if you are trying to post to an oData service, it might be much easier to use SAPs createEntry method where the URL is the path to the model you want to post to and your JSON are the properties:
var oModel = new sap.ui.model.odata.v2.ODataModel("https://services.odata.org/V2/OData/OData.svc/");
//oModel should use your service uri
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
oModel.createEntry(url, {
properties: {
nomorDosir: "01001961288",
kodeCabang: "A02"
}
}, {
method: "POST",
success: function(response) {
alert(JSON.stringify(response));
//do something
},
error: function(error) {
alert(JSON.stringify(error));
}
});
oModel.submitChanges();
What you have is wrong json format, you have:
data: JSON.stringify({nomorDosir: "01001961288", kodeCabang: "A02"}),
Which actually should be:
data: {"nomorDosir": "01001961288", "kodeCabang": "A02"},
Which then you don't need to do a json.stringify on, because it already IS a json format. Hope this will help you out.
Which you could also try is setting a variable outside like this:
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
var json = {"nomorDosir": "01001961288", "kodeCabang": "A02"};
$.ajax({
type: "POST",
url: url,
data: json,
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: "+data+" "+JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});

Getting error trying to submit data using JQuery ajax

When I try to run the following JQuery ajax, I get an error saying that a parameter is missing and it will not send the data. I can't find any syntax errors. What am I doing wrong?
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: fd,
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
Why not use jQuery native form encoder?
$.ajax({
...
data: $('#illustrationTypeForm').serializeArray(),
...
});
Try This
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: $('#illustrationTypeForm').serializeArray(),
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
To make ajax request using jQuery a type 'POST' you can do this by following code :
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

Ajax call no error but does not work

Here my Ajax Call and it does not produce any error but it does not call the php file (I can see it in the network tab of my chrome, and when I call it in the javascript console, it's does return false as expected :
function submitData() {
$('#sortable2').sortable({
axis: 'y',
update: function(event, ui) {
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: './post_occupation_data.php'
});
}
});
return false;
}
Thank you
Try this code and and check the if you are getting alert messages are not.. if 404 alert message please check your URL
function submitData() {
$('#sortable2').sortable({
axis: 'y',
update: function(event, ui) {
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: './post_occupation_data.php',
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
},
success: function(result){
alert(result);
}
});
}
});
return false;
}
try to stringify the parameter like below
data: JSON.stringify(data)
Also add below parameters in your ajax call
contentType: "application/json; charset=utf-8",
dataType: "json",

jQuery: Calling a function from AJAX request

I'm trying to call a function when I get success from my ajax call, but it's not working. This is what I've tryed so far.
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d) {
console.log(dt);
console.log(msg.d);
buildTableBody(dt, msg.d);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
function buildTableBody(dt, obj) {
dt.fnClearTable();
data = [];
$(obj).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
}
Thanks in advance!
Edit #1
I used console.log in order to show you what I got from dt and msg.d (Image)
Edit #2
If I paste the commands from buildTableBody function in the success: handler instead of calling buildTableBody function in the success: handler it actually works:
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
dt.fnClearTable();
data = [];
$(msg.d).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
But it makes no sense to me, since this actually should work in both ways.
Pretty sure you have a typo on your function call
buildTableBody(td, msg.d);
should be
buildTableBody(dt, msg.d);
Also what is the return type from Index.aspx/getMRPReasonCodeReport? If it is string, you've got to unescape the string before you can treat it as JSON.
Try removing contentType : "application/json utf-8" from your AJAX call. That is the type of the data sent to the server. It is likely that you want the default content type.
Unless your server-side resource was configured to accept json it likely accepts application/x-www-form-urlencoded
http://api.jquery.com/jQuery.ajax/

Categories

Resources