My requirement is to grab the response from FBapi('/me',) and do a ajax post to a view to update the info to database. With the code below although I get a 200 on Ajax Post I am unable to retrieve the response using request.POST['name'],
request.POST['birthday'] etc .
If I simply give a:-
def GetFBData(request):
print(request)
I get: "WSGIRequest: POST '/login/facebook/" and an AJAX error message of Unexpected token at JSON position 1.
Below is my script :-
FB.api('/me', {
fields: 'birthday,cover,devices,email,first_name,gender,id,last_name,link,location,name,name_format,timezone,verified,website,locale'},
function(response) {
response = JSON.stringify(response);
$.ajax({
url: '/login/facebook/',
type: 'POST',
data:{fb:response , window:window.ui},
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
How to correctly retrieve this response data on the view?
Related
On submitting a form I wanted to provide the user with feedback that the ajax was executed successfully. My ajax is as follows:
$(function() {
$('#submit').click(function (e) {
var url = "{{ url_for('handle_data') }}"; // send the form data here.
var form_data = new FormData($('#mainform')[0]);
$.ajax({
type: "POST",
url: url,
data: form_data, // serializes the form's elements.
success: function () {
alert('success!!');
}
});
e.preventDefault(); // block the traditional submission of the form.
});
// Inject our CSRF token into our AJAX request.
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", "{{ form.csrf_token._value() }}")
}
}
});
});
And on the backend my flask is:
#app.route('/handle_date', methods=['GET', 'POST'])
def handle_data():
"""
:return:
"""
print("hi there")
return ""
I can never get that success alert message to fire.
The server is not receiving JSON, it’s a FormData. And for jQuery to send a FormData, it needs
$.ajax({
type: "POST",
url: url,
data: formData,
// these three additional parameters
processData: false,
contentType: false,
dataType: "json"
})
The second edit i did was at the backend, when returning a response from flask I had to wrap it under jsonify for the ajax success to trigger
I'm Use Laravel 5.2 And Ajax For Crud
Insert to Database is Correct But When Laravel Response The Browser Show Below Error In Console
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Laravel Code:
return response()->json('ok');
Jquery Code:
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
....
error: function(data){// Error...
var errors = $.parseJSON(data.responseText); console.log(errors);
$.each(errors, function(index, value) { $.gritter.add({
title: 'Error',
text: value
});
});
}
RedyState=4
Staus = 200
Can you paste your all controller code related to this error? Make sure you're not echoing anything before returning json response.
For example,
Route::get('/', function () {
echo "hi";
return response()->json('ok');
});
It would cause parse error.
With the Json response, what if you try something like.
return response()->json(['status'=>'ok']);
You javascript code should be
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success:function (xhr){
var data = xhr.data;
},
error: function (error){
}
});
And why are you using var errors = $.parseJSON(data.responseText); ? Your response will be always json, no?
This link gets some random JSON data. To the best of my knowledge, it is valid.
However, when I try to get it using this code:
$.ajax({
type: "GET",
url: "https://getquote.herokuapp.com/get",
dataType: "jsonp",
success: function(data){
console.log("getting data...")
console.log(data);
},
error: function(err){
console.log("ran into an error...");
}
});
... I get an error that says, "Unexpected token :"
I need to get the value for #odata.context property from the following Json response in ajax:
{
"#odata.context":"https://site.sharepoint.com/_api/",
"#odata.type":"#oneDrive.permission",
"#odata.id":"https",
"link":{"scope":"anonymous"}
}
I would like to do something like that in code:
$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Bearer ' + bearerToken);
},
url: serverUrl,
data: JSON.stringify(params),
dataType: 'json',
contentType: " application/json",
success: function (data) {
var myvalue= data.#odata.context; // ****???
var jsonObject = JSON.parse(data); //this line throws an error Unexpected token o in JSON at position 1
}
});
I think you can get data by this:
data["#odata.context"]
And about the JSON.parse throw exception, it caused by the data is not a JSON string.
Example
When I refresh the document, sometimes is working fine (I get the json object in console), but many times I get 500 (Internal Server Error) and from jQuery I see the error is: xhr.send( options.hasContent && options.data || null ); Please help me. Here is the code:
$(document).ready(function(){
$.ajax({
url: '/ajax/cis',
method: "GET",
success: function(data){
console.log(data);
}
});
});
'/ajax/cis' is a laravel controller wich only returns a json object:
return response()->json(['cis_names'=>'cis_names']);
I also tried with post method:
$.ajax({
url: '/ajax/cis',
method: "POST",
data:{_token: token},
//var token = Session::token()
success: function(data){
console.log(data);
}
});
Try this with using Blade and see if that works:
$.ajax({
url: '/ajax/cis',
method: "POST",
data:{_token: '{{csrf_token()}}'},
success: function(data){
console.log(data);
}
});