Ajax Success Wont Trigger - html

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

Related

Codes are displayed instead of html elements

I have called ajax request in some interval of time. Now, if I pressed the back button after success ajax then, the browser displayed all of my HTML code instead of displaying HTML elements.
<script>
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
}
});
}, 1000);
</script>
if($request->ajax()){
foreach ($devices as $device){
$latestUpdate = Carbon::parse($device->updated_at);
$diff = Carbon::now()->diffInMinutes($latestUpdate);
if($diff > 2){
Device::where('id',$device->id)->update(['status'=>'3']);
}
}
return response()->json(['msg' => "successfully checked"]);
}
I had expected to render the HTML elements, but it displayed.
{
"msg": "successfully checked"
}
Same things happened when I send HTML in json.
if($request->ajax()){
$returnHtml = view('alerts.index', compact('threshold'))
->with('alerts', $alerts)->render();
return response()->json(['html' => $returnHtml, 'data' => $alerts]);
}
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('alerts.index')}}',
dataType: 'json',
success: function (data) {
var formatedhtml = $('<div>').html(data.html).find('table');
$('table').html(formatedhtml);
}
});
}, 5000);
In this case it display
Instead of returning as json return data as array:
Try something like this
return ['html' => $returnHtml, 'data' => $alerts];
There's nothing wrong with how you are receiving the data when you use return response()->json(['html' => $returnHtml, 'data' => $alerts]);
If you want to actually put the html that you received from your server into an element in your page, you will need to use Element.innerHTML (https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) so that the html will not be escaped by the browser.
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
// this is the table where you want to place the received table contents
var my_table=$('#my-table')
// we turn the data we received from the server into a jQuery object, then find the table we want data from
var received_table=$(data.html).find('table')
// switch out the table contents
my_table.html(received_table.html())
}
});
}, 1000);
EDIT: Since you are using jQuery, I changed the answer to fit.

flask-cors is not parsing the data from ajax client

I am using flask for creating some endpoints for a blockchain project . I need to accept json data from ajax client . Since it is cros platform , i am using flask cors . But i cant seem to find a solution. It is not working
I have already tried doing
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, origin = '*')
Basically my client code is as follows .
$.ajax({
url: 'http://localhost:8080/ratings/new',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: json1,
crossDomain: true,
xhrFields: {
withCredentials: true
},
processData: false,
beforeSend: function (xhr) {
//xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data, textStatus, jQxhr)
{
$('body').append(data);
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
And at my server i have an endpoint of
#app.route('/ratings/new', methods = ['POST','OPTIONS'])
def rating():
values = request.get_json()
if values == None:
return "No data received", 400
#ratings = values['rating']
index = blockchain.new_ratings(values)
response = {
'Message': f'New transaction will be added to the block {index}',
}
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin','*')
return response, 201
At the server side i am not receiving the required data and at the client side i am getting the following error .
Access to XMLHttpRequest at 'http://localhost:8080/ratings/new' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Please help me solve this problem . Thanks in advance.
Silly mistake , make the withCredentials: false
$.ajax({
url: 'http://localhost:8080/ratings/new',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: json1,
crossDomain: true,
xhrFields: {
withCredentials: false
},
processData: false,
beforeSend: function (xhr) {
//xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data, textStatus, jQxhr)
{
$('body').append(data);
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});

FB.api('/me') AJAX Post in Django

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?

Headers using ajax request

How to set headers using Ajax request? in below code
$.ajax({
type: type, //GET or POST or PUT or DELETE verb
url: requestURL, // Location of the service
// contentType: "application/x-www-form-urlencoded", // content type sent to server
dataType: "xml", //Expected data format from server
processData: false, //True or False
success: successCallback, //On Successfull service call
error: serviceFailed// When Service call fails
});
Request headers can be managed using beforeSend(jqXHR, settings) function and the setRequestHeader method, e.g.
$.ajax({
...
beforeSend : function(xhr) {
xhr.setRequestHeader('content-Type', 'application/x-www-form-urlencoded');
}
});

JSON data not parsing in node.js displays undefined in console

JSON data not parsing in node.js displays undefined in console..
Here is HTML code:
var jsonObjects = [{id:1, name:"amit"}];
jQuery.ajax({
url: 'http://localhost:8081',
type: "POST",
data: {"id":"1", "name":"amit"},
dataType: "json",
success: function(result) {
alert("done")
}
});
Here is Nodejs code:
http.createServer(function (request, response)
{
response.writeHead(200, {"Content-Type":"text/plain"});
var urlObj = JSON.stringify(response.data, true);
console.log(urlObj)
response.end();
}).listen(8081);
Try using GET method Instead of Post. Try this
var jsonObjects = [{id:1, name:"amit"}];
$.ajax({
type: 'GET',
url: 'http://localhost:8081',
data: {
jsonData: JSON.stringify(jsonObjects)
},
dataType: 'json',
complete: function(validationResponse) {
}
});
The data will be held in the request, not the response as it has come from the client request.
If you are using express to create your http server you will also need to tell it to use the bodyParser middle wear.