Updating Ajax function asynchronously - javascript

I am trying to update data asynchronously. Currently, if I refresh the page, only then I see new data in the console log.
My ajax script:
$.ajax({
url: '{% url 'messages' %}',
datatype: 'json',
type: 'GET',
success: function(body) {
console.log(body)
}
});
My view:
inbox = Messages.objects.filter(receiver=user).order_by('-timestamp')
serialized_inbox = serializers.serialize('json', inbox)
return HttpResponse(serialized_inbox, content_type='application/json')

Related

How to send current URL in JavaScript to a second PHP page?

I want to sent current URL from Page1 to a php page called upload_picture.php.
I look at another question and this is an option:
On Page1
$.ajax({
type: 'POST',
url: '/uas_tools/visualization_generator/V2/Resources/PHP/upload_picture.php',
data: 'url=' + window.location.toString()
});
If using this option, on upload_picture.php, how to get the URL sent from Page1?
Your code to call the ajax will be as this.
$.ajax({
type: 'POST',
url: '/uas_tools/visualization_generator/V2/Resources/PHP/upload_picture.php',
data: { url: location.href },
success: function(response) {
// your success callback
},
error: function () {
// your error callback
}
});
And on the php page you can retrieve the data as
<?php
$page_url = $_POST['url'];

Printing server response in an AJAX callback (using jquery)

I have control over my server endpoint
#app.route('/predict', methods=['GET', 'POST', 'OPTIONS'])
#crossdomain(origin='*')
def predict():
return 'predict12'
I want to return predict12 in the callback of my AJAX call.
$.ajax({
type: "POST",
url: 'https://linear-yen-140912.appspot.com/predict',
data: 'data',
success: function test(){console.log()},
});
What should I put in the success function so it prints predict12?
$.ajax({
type: "POST",
url: 'https://linear-yen-140912.appspot.com/predict',
data: 'data',
success: function test(result){console.log(result)},
});
the success has the result of the AJAX call, and thats what you should be using

Display page only if ajax call succeeds?

I have a subdomain protected by a service similar to cloudflare. It checks if a visitor is human or not. To save bandwidth usage I want only one file to be loaded from this subdomain as indicator if the visitor is a bot or not. If it is not loaded, the service has blocked it as bot, and nothing should be shown.
I already thought of an ajax request before the page loads to check this.
var success = 0;
function myCall() {
var request = $.ajax({
url: "sub.example.com/hello.php",
type: "GET",
dataType: "html"
});
request.done(function() {
// Load page, because the request was successfull
$.ajax({
url: 'content.php', //This is the current file
type: "POST",
dataType:'json', // add json datatype to get json
data: ({load: true}),
success: function(data){
console.log(data);
}
})
});
Is there a better way to do this?
You may try this:
var success = 0;
function myCall() {
var request = $.ajax({
url: "sub.example.com/hello.php",
type: "GET",
dataType: "html",
success: function(){
$.ajax({
url: 'content.php', //This is the current file
type: "POST",
data: dat,
success: function(data){
console.log(data);
},
error: function(data){
console.log('Error!');
}
});
},
error: function(data){
console.log('Error!');
}
});
}

POST request using ajax in Django

I met some problems when I try to send the POST request using ajax in Django. I already research some topics here, but still can't find the way to solved them.
Here is my javascript code that follow this solution:
$.ajax({
url: '{% url home %}',
data: {selected_folders: formData,
csrfmiddlewaretoken: '{{ csrf_token }}'},
dataType: "json",
type: "POST",
});
I also try the solution from Django
$("form").submit(function() {
var csrftoken = $.cookie('csrftoken');
$.ajax({
url: '{% url home %}',
data: {selected_folders: formData,
csrfmiddlewaretoken: csrftoken},
dataType: "json",
type: "POST",
});
});
Here is my view.py
def home(request):
if request.method == 'POST':
Call_Other_Class()
return render_to_response('home.html')
My goal is to send the POST request from home.html to itself, and when home.html get the POST request, it will call other classes to do something else. I am not sure where to put the CSRF token in the template and if my code in view.py is correct or not.
Thanks for your reading and solve my problems.
Edit:
I edited my javascript code to:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajax({
url: '{% url home %}',
data: {selected_folders: formData},
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
dataType: "json",
type: "POST",
});
});
</script>
HTML:
<form>
<ul>
<li id='key1'></li>
<li id='key2'></li>
</ul>
</form>
still doesn't work.
For Js:
$("form").submit(function() {
$.ajax({
url: '{% url home %}',
data: {selected_folders: formData,
csrfmiddlewaretoken: $("[name = csrfmiddlewaretoken]"),
dataType: "json",
type: "POST",
});
});
For view.py:
def home(request):
if request.method == 'POST' and request.is_ajax():
Call_Other_Class()
return render_to_response('home.html')
The best solution is using the online documentation.
From what I recall:
first call a GET in Ajax and in the answer, force ensure_csrf_cookie decorator
then keep the CSRF cookie, you have all the detail explanation here.

Will an asynchronus-Ajax request be completed if I instantly reload or close my page after it's being sent to the server?

For example if I do this request with jQuery's Ajax:
$(document).ready(function() {
$('#some_button').click(function() {
$.ajax({
url: '/some/request',
type: 'POST',
data: [{my: 'dummy', data: 'lata'}],
dataType: 'json',
async: true,
});
window.location.href = '/my/parent/location';
});
});
So I'm interested:
Will my action be completed on the server nevermind if I'm refreshing the page just right after the initial request is sent?
Ajax is synchronous.. So it will be immediately redirected irrespective of the Request..
You can call that in the success callback of your Ajax Request instead..
$(document).ready(function() {
$('#some_button').click(function() {
$.ajax({
url: '/some/request',
type: 'POST',
data: {my: 'dummy', data: 'lata'},
dataType: 'json',
success : function() {
window.location.href = '/my/parent/location';
}
});
});
});

Categories

Resources