Getting undefined in callback function in cross domain ajax post - javascript

I'm trying to make ajax post request to my flask app and get the answer in the callback function. Unfortunately I got undefined value instead of a json.
Will appreciate any help!
My server-side code:
application = Flask(__name__)
CORS(application)
...
#application.route('/get_forecast', methods=['POST', 'GET'])
def get_forecast():
if request.method == 'POST':
print('in post')
predictions = {}
predictions['data'] = calc_forecast(request.get_json()["data"])
print(predictions)
return jsonify(predictions)
my client-side code:
$.ajax({
type: "POST",
url: "http://localhost:5000/get_forecast",
data: JSON.stringify(markers),
dataType: 'json',
crossDomain: true,
contentType: "application/json",
done: function(resp, status){
console.log('done')
console.log(resp)
console.log(status)
console.log('=====')
}(),
fail: function(xhr, ajaxOptions, thrownError){
console.log('fail');
console.log(thrownError)
}()
});
Here's what I got in the flask terminal:
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [02/Dec/2018 12:59:53] "OPTIONS /get_forecast HTTP/1.1" 200 -
in post
{'data': [10.15451836569513, 56.578480707072714, 12.435548873275337]}
127.0.0.1 - - [02/Dec/2018 12:59:53] "POST /get_forecast HTTP/1.1" 200 -
Here's what I got in the chrome console:
demo.html:228 done
demo.html:229 undefined
demo.html:230 undefined
demo.html:231 =====
demo.html:234 fail
demo.html:235 undefined

If you look at the examples over at http://api.jquery.com/jQuery.ajax/ they look quite a bit different from your call to $.ajax. I adjusted your code to better resemble the examples. Maybe this helps?
$.ajax({
type: "POST",
url: "http://localhost:5000/get_forecast",
data: JSON.stringify(markers),
dataType: 'json',
crossDomain: true,
contentType: "application/json"
})
.done(function (data, textStatus, jqXHR) {
console.log('done');
console.log(data);
console.log(textStatus);
console.log('=====');
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log('fail');
console.log(textStatus);
});
I think, you were looking for success and error settings.
Update: Yes, I'm pretty sure, your settings done and fail are wrong. You want to use success and error.
Also, have a look at https://stackoverflow.com/a/10931891/1621041
This means, your code could also look like this, if you want to put everything into the settings of the $.ajax call:
$.ajax({
type: "POST",
url: "http://localhost:5000/get_forecast",
data: JSON.stringify(markers),
dataType: 'json',
crossDomain: true,
contentType: "application/json",
success: function (data, textStatus, jqXHR) {
console.log('done');
console.log(data);
console.log(textStatus);
console.log('=====');
},
error: function (jqXHR, textStatus, errorThrown ) {
console.log('fail');
console.log(errorThrown);
}
});

Related

Get Java exception class name in javascript

I am using following code to call java web API
m$.ajaxq({
url: contextPath + "/updateElapsedTime",
type: "POST",
data: params,
contentType: "application/json; charset=utf-8",
dataType: 'text',
async: optionalRunAsync,
success: function (response) {
console.log("Success")
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Exception name is ...");
}
});
Now there is a case when it throws custom exception.
I want to know which custom exception is thrown(classname) from java api and print it in javascript.
Check if response is not 200.
then use...
xhr.responseText
this will gives your custom error message

How to get each data before ajaxSend in JSON not after complete/success

I want all the ajax params before sending an ajax request in JSON format and I need to encrypt each value in JSON and again pass to the ajax request.
I get data in URI format as see in below code, not in JSON. How can I get that?
Around 200 Ajax in this format:
$.ajax({
type: "POST",
url: site_url + "user/user/login_action",
data: login_parms,
success: function (data) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
Before Ajax Call:
$(document).ajaxSend(function(event, jqxhr, settings) {
console.log("settings :",settings.data);
});
Console log:
settings : vEmail=disha.c1%40grr.la&vPassword=123456789
Also if in AJAX use formData then how we can get each value of form data?
If you want to send a AJAX JSON CALL you must to use:
$.ajax({
type: "POST",
url: site_url + "user/user/login_action",
dataType: "json",
async: false,
contentType: "application/json",
data: JSON.stringify(login_parms),
success: function (data) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
if you want to modify the param:
$.ajax({
beforeSend: function(xhr){
this.data
}
});

showing 400 (Bad Request) in ajax

I am using cordova and while doing json i am getting an error "Failed to load resource: the server responded with a status of 400 (Bad Request)".
But the same code when I run it on postman is getting the right answer.Please help me to solve this problem.
The code is:
$.ajax({
url: url,
type: "POST",
async: false,
ContentType: "application/json; charset=utf-8",
data: jData,
dataType: "json",
success: function(response) {
console.log(response)
},
error: function(jqXHR, textStatus, errorThrown) {
},
});
And a screenshot of the right answer on the postman is also given for your reference
you need to stringify the JSON data was sending
$.ajax({
type: 'POST',
url: url,
async: false,
data: JSON.stringify(jData),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) {
console.log(response)
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
Try removing the open and closing brackets around your jData
var jData = {};
Not
var jData = [{}];

How to get rid from ?callback=myCallback&_=1340513330866?

I'm trying to capture data from an HTML page that is on the another website. I need to capture that data and save it into my site. That's why I used cross domain ajax like this
var myCallback = function(data) {
console.log(data);
};
var formData = $('.data-capture-form').serialize();
$.ajax({
url: 'http://prospectbank.co.uk/leads/capt',
type: 'GET',
data: formData,
dataType: 'jsonp',
crossDomain: true,
jsonp: 'callback',
jsonpCallback: 'myCallback'
}).done(function(res) {
console.log(res);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
});
Then I get this error
Any help? Thanks
The response from http://prospectbank.co.uk/leads/capt?_=1340513330866? is wrong formatted JSON.
{"status":true}
It should be
{status:true}

AJAX Get status was Ok but jsonp callback returns undefined data

I am sending an ajax request to retrieve data from salesforce using jsonp but jsonp callback data returns undefined
My ajax request is,
$j.ajax({
type: "POST",
async: this.asyncAjax,
url: "https://na14.salesforce.com/services/data/v26.0/
sobjects/customobject?callback=mycallback",
contentType: 'application/json',
cache: false,
processData: false,
data: payload,
jsonp: false,
jsonpCallback: function(data, textStatus, jqXHR){
alert('Data is '+data);
alert('Text status is '+textStatus);
alert('jqXHR is '+jqXHR);
},
error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status === 401) {
that.refreshAccessToken(function(oauthResponse) {
that.setSessionToken(oauthResponse.access_token, null,
oauthResponse.instance_url);
that.ajax(path, callback, error, method, payload, true);
},
error);
} else {
error(jqXHR, textStatus, errorThrown);
}
},
dataType: "jsonp",
beforeSend: function(xhr) {
if (that.proxyUrl !== null) {
xhr.setRequestHeader('SalesforceProxy-Endpoint', url);
}
xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId);
xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion);
if (that.userAgentString !== null) {
xhr.setRequestHeader('User-Agent',that.userAgentString);
}
}
});
But, i got my response is,
Data is undefined.
Text status is undefined.
jqXhr is undefined.
How do i solve this? Is that ajax request in the right format?
Thanks
You are manually setting the name of the callback parameter sent to the URL, but there is no function called mycallback.
You are setting jsonpCallback to a function. jQuery will take the return value of that function and send it as the callback parameter (if you let it send that parameter).
The correct way to do JSONP is:
$j.ajax({
type: "POST",
async: this.asyncAjax,
url: "https://na14.salesforce.com/services/data/v26.0/sobjects/customobject",
contentType: 'application/json',
cache: false,
processData: false,
data: payload,
dataType: 'jsonp',
success: function(data, textStatus, jqXHR){
alert('Data is '+data);
alert('Text status is '+textStatus);
alert('jqXHR is '+jqXHR);
},

Categories

Resources