TemplateSyntaxError in django when passing variable to ajax - javascript

I receive template error "Could not parse the remainder: '{{movie_id}}' from '{{movie_id}}'" when passing the varriable to ajax. This variable works in template, but ajax cannot get it thru. Variable contains id which is required to pass to my views function.
ajax call:
$.ajax({
url: "{% url 'make-order' {{movie_id}} %}",
type: 'POST',
data: new_array,
processData: false,
contentType: "application/json",
dataType: "json",
headers: {"X-CSRFToken":'{{ csrf_token }}'},
success: function (result) {
console.log(result.d)
window.location.href = "{% url 'confirmation' %}"
},
error: function (result) {
console.log(result);
}
});
urls:
path("make-order/<int:pk>", views.make_order, name="make-order"),
views:
def make_order(request, movie_id):
if request.method == "POST" and request.is_ajax():
data = json.loads(request.body)
print(movie_id)
return HttpResponse(200)
else:
return redirect(request, 'home')

Related

Updating Ajax function asynchronously

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')

js to flask and back to js in a single page app

For my single page web app, I need to:
Send a json from .js to flask (DONE)
Run the input through a python function - getString() and get a str output (DONE)
Send the str output back to the .js file (PROBLEM)
Here is the flask app:
#app.route('/',methods =['GET','POST'])
def index():
req = json.dumps(request.get_json())
if request.method == 'POST':
result = getString(req) #Function outputs a string
return jsonify(result)
else:
print('Not Received')
return render_template('index.html')
if __name__ == '__main__':
app.run()
The problem is that the jsonify(result) is not being sent probably due to the request.method == 'POST' switching to else when jsonify is called. Is there any way to fix my code to send the str output to the .js?
Here is the .js:
//To send info to flask
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json"
});
})
//To receive from Flask
$.ajax({
url: "/",
type: 'GET',
success: function(data) {
console.log(data);
}
});
I think you've misunderstood what GET and POST are, GET is a request that only fetches something from the back end without a message body but a POST can send a body and recieve something.
try this instead:
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json",
success: function(data) {
console.log(data);
}
});
})

Transfer form together with other data using one AJAX post. Django

Very simple task. It is necessary to transfer data from the form together with other data using AJAX POST. The problem is how to extract this data later from the form, because they represent a whole line.
$(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var form=$('#myform').serialize();
var data={};
data['form']=form;
data['csrfmiddlewaretoken']='{{ csrf_token }}';
data['other_data']='other_data';
$.ajax({
type: 'POST',
url: '/myajaxformview',
dataType: 'json',
data: data,
success: function (data, textStatus) {
$('#output2').html(JSON.stringify(data));
},
error: function(xhr, status, e) {
alert(status, e);
}
});
});
});
def myajaxformview(request):
if request.method == 'POST':
if request.is_ajax():
data = request.POST
print(data)
#<QueryDict: {'form': ['csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2'], 'csrfmiddlewaretoken': ['VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9'], 'other_data': ['other_data']}>
form=data.get('form')
#csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2
print(form)
return HttpResponse(json.dumps(data))
return render(request, 'foo.html')
Consider using of FormData:
$(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var data = new FormData(event.target);
data.append('form', event.target);
data.append('csrfmiddlewaretoken', '{{ csrf_token }}');
data.append('other_data', 'other_data');
$.ajax({
type: 'POST',
url: '/myajaxformview',
dataType: 'json',
data: data,
processData: false,
contentType: false,
success: function (data, textStatus) {
$('#output2').html(JSON.stringify(data));
},
error: function(xhr, status, e) {
alert(status, e);
}
});
});
});

unable to retrieve data sent via ajax in controller Laravel 5.1

I am sending data via ajax to my controller as
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
contentType: "application/json; charset=utf-8"/*,
success:function(id){
alert(sessionStorage.getItem('user_id'));
}*/
});
and in the controller I am using
public function getUserMessages(){
$id = Input::get('id');
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
echo "id is ",$id;
return $messages;
}
I am getting nothing in $id. I have also tried $_POST['id'] which says undefined index id. How I can retrive the id value?
$request->has('id') returns false too.
You should use the Request class instead of Input:
public function getUserMessages(\Illuminate\Http\Request $request){
$id = $request->id;
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
return $messages;
}
Your ajax call doesn't work and will throw a 500 Server Error because you need to pass laravel's csrf token with it whenever you POST something. Create a meta tag at the top of your blade view like:
<meta name="_token_" content="{{ csrf_token() }}">
and get the value when you are doing the ajax call:
$.ajax({
url: '/test',
type: 'POST',
data: {
id: sessionStorage.getItem('user_id'),
_token:document.getElementsByName('_token_')[0].getAttribute('content')
},
success:function(id){
alert(id);
}
});
Most likely the success function in your ajax call will only alert [object Object], to get a better overview over whats returned, use
console.log(id);
instead.
You may also create an error function for the ajax call so that possible errors will be shown. Just do add
error: function(err){
console.log(err);
}
after the success function.
The problem is that you are setting the application content as json, You don't need to set the content.
jQuery ajax
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
success:function(data){
console.log(data); // always good to output content for debugginn
}
});
Hope this help. Your ajax should work now.
Have you a route for AJAX requests? (I don't see it.)
Please try following code:
In your AJAX code:
$.ajax({
type: "POST",
url: "{{ route('ajax_route') }}",
data: { _token: "{{ csrf_token() }}", data: "sample data" },
success: function(data){
$(".result").html(data);
},
dataType: "json"
});
In your controller code:
public function ajaxAction(Request $request){
if ($request->isXmlHttpRequest() && $request->isMethod('post')) {
$data = $request->input('data', null);
echo json_encode($data);
}
}
In your route code:
Route::post('/ajax_route', ['as' => 'ajax-action', 'uses' => 'YourController#ajaxAction']);

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.

Categories

Resources