Send AJAX request to Django view with vanilla JS - javascript

I'm trying to send a GET AJAX request to a Django view using vanilla JS. is_ajax() passes but I could not retrieve the request object properly.
Here is my JS code. With/out JSON.stringify(data) doesn't work.
document.querySelector('#testForm').onsubmit = () => {
let data = {category : 'music'};
const request = new XMLHttpRequest();
request.open('GET', 'test/', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onload = () => {
const data = JSON.parse(request.responseText);
console.log(data);
}
request.send(data);
return false;
});
And here is my Django view:
def test(request):
if request.is_ajax():
print('Yes!')
data = {'category': request.GET.get('category', None)}
return JsonResponse(data)
else:
raise Http404
It prints Yes! to the terminal but I get back a {category: null} in the console.
This JQuery code works and I get the expected {category: "music"} response:
$.ajax({
url: 'cart/',
type: 'GET',
data: data,
dataType: 'json',
success: function (data) {
console.log(data);
}
});
I'm wondering what I'm missing in the vanilla JS code or in my Django view.

GET requests can't have a body, so the data parameter to request.send is ignored. You should make it part of the URL itself:
request.open('GET', 'test/?category=music', true);

Related

Why Ajax is triggering 500 internal error in django?

Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py).
My Hmtl form does have a csrf_token, so I added the header in ajax function, but still got 500 internal erorr. The data is saved into database but the response is not sent to ajax function.
View.py
## Ajax
#login_required
def SubmitModal(request):
if request.method == 'POST':
text = request.POST['Text']
date = request.POST['DatePicker']
time = request.POST['TimePicker']
T = SText()
T.User = request.user
T.Text = text
T.STime = date + ' ' + time
T.save()
return HttpResponse(json.dumps({'success': True}), content_type="application/json")
else:
return JsonResponse({'success': False})
file that contains ajax
$(document).ready(function () {
// Show the modal window when a button is clicked
$('#open-modal').click(function () {
$('#modal').modal('show');
});
// Close the modal window when a button is clicked
$('.close-modal').click(function () {
$('#modal').modal('hide');
});
// Handle the form submission
$('#modal-form').submit(function (event) {
event.preventDefault(); // Prevent the form from being submitted
var formData = $(this).serialize(); // Get the form data
// Submit the form data to the server using an AJAX request
$.ajax({
type: 'POST',
url: '/submit/',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: formData,
dataType: "json",
success: function (response) {
if (response.success) {
$('#success-message').show();
} else {
$('#error-message').show();
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
$(".textarea-input")[0].value = '';
$(".date-input")[0].value = '';
$(".time-input")[0].value = '';
});
});
If you're reproducing this in a non-production environment, you can set DEBUG=True in the settings file. Then when you make the call from your browser, the response will include details about what the issue is. You can also set the ADMINS variable to send exception tracebacks to the specified emails when they're encountered. More details here.
You can view the data being sent and received in the developer tools of the browser you are using.

how to call a service using ajax javascript?

I'm learning programing, could you explain me how to call a service using ajax javascript?
Service information:
Service type: REST
Basic authentication
Estructure: Application/JSON
Url: https://osb.urosario.edu.co/uxxi-URO/WsFotografias/proxy/AdministradorFotografiasJsonPS/fotos/consultar
User: Admi
Password: admi
Parameter JSON example: {"identificacion":["98122811999"]}
I've tested this service in postman
Service answer:
{
"respuesta": [
{
"estado": "Correcto.",
"identificacion": "98122811999",
"imagen": "return string Base 64 format"
}
]
}
Using JQuery :
$.ajax({
type: 'POST',
url: 'https://osb.urosario.edu.co/uxxi-URO/WsFotografias/proxy/AdministradorFotografiasJsonPS/fotos/consultar',
dataType: 'json',
data:{"identificacion":["98122811999"]}
contentType: "application/json"
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth("admi", "admi"));
},
success: function (data,status) {
//do what you want with the data after success
//in this example the response will be promoted in the browser console
console.log(data);
});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
You can call your above RestEndpoint using below:
xmlhttp.open("POST", "/EndpointURI", true);
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
//Use parse() method to convert JSON string to JSON object
var responseJsonObj = JSON.parse(this.responseText);
//use response
}
};
var jsonData = {"name" : "yourData"};
xmlhttp.send( JSON.stringify( jsonData ) );
For Authentication use this:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://EndPointURI", true);
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('userName:password'));
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send();
For authentication part, use JQuery then it will easy for the implementation and as well for understanding. as now aday no body use basic xmlhttp for calling api in javascript, last time i used was a 2003 developed application.

NodeJS: how to perform Ajax Post with FormData

I am testing a local HTML Form sending data to an aspx application as backend. Since I have some problem with CORS (even on localhost) I am trying to emulate the Ajax request performed by jQuery with NodeJS. I don't know if this is the right way to do. In the HTML form, after the jQuery validation, this is what I do:
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
console.log(response);
}
});
//console.log($(form).serialize())
}
and it works, until CORS ends the request. I mean that I can retrieve the data from the backend application.
Instead, if I do:
function loadDoc() {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhttp = new XMLHttpRequest();
/*var FormData = require('form-data');
var myform = new FormData();
myform.append('firstname', 'foo');*/
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("POST", "http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE", true);
//which is the same string I get from .serialize() in jQuery
xhttp.send("firstname=foo&email=some#domain.it");
}
loadDoc();
I cannot get anything from the server application. If I want to get the parameter firstname from the POST data, I get null. So, where am I wrong?
UPDATE
This is the only workaround I have found useful in NodeJS:
var http = require('http');
var querystring = require('querystring');
var post_data = querystring.stringify({'firstname':'Lory'});
var post_options = {
host: 'localhost',
port: '1308',
path: '/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_data)
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
I had also tried with:
var request = require('ajax-request');
request.post({
url: 'http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
data: {'firstname':'Lory'},
headers: {}
}, function(err, res, body) {
console.log(res);
}
);
but it did not work too. I feel such an ignorant and I would like to know the differences between those 3 libraries.
I have some doubts concerning the fact I must use querystring.stringify() in the working solution, because POST data are not in the URL and should not be uder the limits of query string, if I remember well.
I would like to suggest request module. while doing ajax call post, we can post the data by form or JSON format. It's based on receiver end point how they are receiving.
I hope you are trying to post form data.
var request = require('request');
request.post({
url:'http://service.com/upload',
form: {'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
If you are trying to do normal JSON post.
var request = require('request')
request({
method: 'POST',
uri: 'http://www.google.com',
body:{'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
request module provide lots of options. Play with that then you will get the better idea.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm" name="myForm">
<div>
<label for="comment">Comment:</label>
<textarea id="comment" name="comment"></textarea>
</div>
<div>
<label for="rating">Comment:</label>
<textarea id="rating" name="comment"></textarea>
</div>
<input type="submit" value="Submit!">
</form>
<script>
$(document).ready(function () {
$('form').submit(function (event) {
event.preventDefault();
//collect the form data using Id Selector what ever data you need to send to server
let comment=$('#comment').val();
let rating= $('#rating').val()
$.ajax({
url: 'replace your url',
data: JSON.stringify({"comment": comment, "rating": rating }),
processData: false,
type: 'POST',
contentType: 'application/json',
success: function (data) {
alert(data);
}
});
});
})
</script>
</html>

how do I send a GET request with Jquery?

Currently I am using Flask and Jquery and getting a 500 Internal Server Error response in my console. When I post with Ajax to the url on flask, shouldn't it be able to be received? I don't understand why I am getting this error.
Jquery
$('.movie').click(function(){
console.log(this);
$(this).toggleClass('green blue').promise().done(function(){
if ($(this).html() == "Add Movie"){
$(this).html("Added");
}
});
id = $(this).val();
//get information from API
$.ajax({
url: "/profile",
dataType: 'json',
async: true,
data: {id: id},
success: function(data) {
}
});
Python/Flask
#app.route("/profile", methods = ["GET"])
def profile(id):
print("mydata is: ", request.args['id'])
if request.args.get:
print("this API is reached")
id = request.args.get['id']
url_movie = 'https://api.themoviedb.org/3/movie/{}?api_key=78cb6b67a99ce26e6d6619c617d9c907&language=en-US'.format(id)
r = requests.get(url_movie)
code = r.json();
return jsonify(code)
500 is a server error. There is something wrong with the request execution at server side only.

jQuery vs. JavaScript ajax 'POST' functions

This jQuery code is working:
$.ajax({
type: "POST",
url: "file.php",
data: { json: json },
complete: function (data) {
var result = data.responseText;
console.log(result); // logs 'echo' from PHP file
}
});
This JavaScript code is still not working:
var xhr = new XMLHttpRequest();
xhr.open("POST", "file.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result); // supposed to log 'echo' from PHP file
}
}
xhr.send(JSON.stringify(json));
Aren't these two approaches equivalent, or am I missing something?
Suppose 'file.php' looks something like this:
if(isset($_POST['json'])){
$obj = json_decode($_POST['json']);
//some php operation
// echo $obj keys and values
}
data : { json: json }
gets serialized to '{ "json": {data} }'
JSON.stringify(json)
gets serialized to '{data}' and there is no "json" key
add your javascript object to a parent wrapper object with a "json" key
JSON.stringify({ json: json });

Categories

Resources