Django template not re-rendering on successful AJAX get request - ajax

I have written a very simple ajax code which makes a get request, and it expects django template values as response. So when I try to execute this ajax code, in chrome under network, I can see that the get request was successful and in the preview section under network, I can see the template values that I had expected but the webpage remains same, doesn't get rendered again.
My view:
def test(request,id=1):
return render(request,'test.html',{'num':id,'next':9})
My template and ajax code:
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<p>{{num}}</p>
<button onclick='test({{next}})'>Test</button>
<script>
function test(next){
$.ajax({
url:'/test/'+next,
type: 'GET',
success: function(){
console.log('done');
}
});
}
</script>
Please check this sample image of my problem when I started on '/test/66' , made a click on the button, got the required response, still no change.

You're mixing server side rendering (DTL) and client side (javascript). Once django as rendered the template, you're javascript has no access to server side variable as {{ text }}.
You will have to do :
Template before SSR
<div id="content">
<p>{{num}}</p>
<button onclick='test({{next}})'>Test</button>
</div>
<script>
function test(next){
$.ajax({
url:'/test/'+next,
type: 'GET',
success: function(data){
document.querySelector('#content p').innerHTML(data);
}
});
}
</script>
Template after SSR (something like this, you get the point)
<div id="content">
<p>66</p>
<button onclick='test(66)'>Test</button>
</div>
<script>
function test(next){
$.ajax({
url:'/test/'+next,
type: 'GET',
success: function(data){
document.querySelector('#content p').innerHTML(data)
}
});
}
</script>

Related

how to make ajax call on same page ajax request send and get in same page

here is ajax code i'm implement this code
i want to call ajax request same page where i want to get the request mean same page send request and get request
function data(status)
{ $.ajax({
type:"post",
url:"main.php",
data: "status="+ status,
success:function(data)
{
} }); });
i'm try this code but have problem in ajax call same html page show header footer also result
how to call on self page where is ajax code how it is possible?
In your success callback, do the necessary DOM update.
"data" will contain the actual response text from thte page main.php.
Your html should look like something like this:
<html>
<head>
<title></title>
<script src=[jquery JS file]"></script>
</head>
<body>
<div id="mydiv"></div>
</body>
<script>
function data(status)
{ $.ajax({
type:"post",
url:"main.php",
data: "status="+ status,
success:function(data)
{
$("#mydiv").html(data);
}
});
}
</script>
</html>
Here is the code:
$.ajax({
url:'main.php',
mtype:'post',//use mtype as 'get' for get reuest,
contentType:'application/json',
async:true, // for asynchronous calls
sucess:function(data)
{
},
error:function(error)
{
}
});

How to pass hidden values using AJAX to another PHP file using GET method?

I’m trying to pass a hidden value that is from database to another PHP file using AJAX with GET method. But it keeps saying undefined variable. I couldn’t use a normal POST method as requirements do not want a button but a normal url link.
<script type="text/javascript">
$(document).ready(function() {
$("#edit").click(function(){
$.ajax({
type:"GET",
url:"editItem.php",
data:"itemid=" + $(this.find(":selected").val()),
cache: false,
success: function(msg){
}
});
});
});
</script>
<input type="hidden" name="itemid" id="edit"/>
Edit

Ajax get request with Django

I try to implement an ajax request in my django app to get the number of spectators of a flash video recorder I implemented in my app. This number is in an xml file.
Here the js I used did in my template:
var url = window.location.pathname.split('/');
var id = url[2]; // The id of my video is www.mysite/video/ID.com
setInterval(function() {
$.ajax({
type: "GET",
url: "http://myxmlfiles",
success: parseXml
});
}, 2000);
function parseXml(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id) {
$(".DubScore").html($(this).attr("count"))
}
});
}
And in my html:
<div class="DubScore"> </div>
The xml file renders:
<streams>
<user id="3" count="1"/>
</streams>
The problem is nothing appears. I really don't know what I did wrong.
Any advice would be great,
EDIT:
When I run my js console, I can see the number of spectators, as I wanted. So the only problem is that it doesn't display this number into my div. The problem is between the js and the html. If you have any idea on how to fix it, it would be great. Thanks

Ajax response inside a div

I am trying to show the value of ajax response inside a div and for that I have the following code in my view file.
<script type="text/javascript" src="MY LINK TO JQUERY"></script>
<script type="text/javascript">
$(function(){ // added
$('a.vote').click(function(){
var a_href = $(this).attr('href');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>contents/hello",
data: "id="+a_href,
success: function(server_response){
if(server_response == 'success'){
$("#result").html(server_response);
}
else{
alert('Not OKay');
}
}
}); //$.ajax ends here
return false
});//.click function ends here
}); // function ends here
</script>
<a href="1" title="vote" class="vote" >Up Vote</a>
<br>
<div class="result"></div>
my Controller (to which the ajax is sending the value):
function hello() {
$id=$this->input->post('id');
echo $id;
}
Now what I am trying achieve is get the server_response value (the value that is being sent from the controller) in side <div class="result"></div> in my view file.
I have tried the following code but its not showing the value inside the div.
Could you please tell me where the problem is?
The problem is that you have mixed arguments of Ajax success handler. First goes data which your script gives back, then goes textStatus. Theoretically it can be "timeout", "error", "notmodified", "success" or "parsererror". However, in success textStatus will always be successful. But if you need to add alert on error you can add error handler. And yes, change selector in $("#result") to class. So corrected code may look like this:
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>contents/hello",
data: "id=" + a_href,
success: function(data, textStatus) {
$(".result").html(data);
},
error: function() {
alert('Not OKay');
}
});​
success: function(server_response) {
$(".result").html(server_response);
}​
<div class="result"></div> // result is the class
The selector should be .result not #result
Try changing <div class="result"></div> to <div id="result"></div>, because that's what you're referencing in your ajax success function
$("#result").html(server_response);

Jquery ajax call not working with relative and absolute urls

This is the code, I don't get any alerts whether, error or success. That ajax call returns a json map, and that map is populated in the select options dynamically.
<body>
<script>
$(document).ready(function() {
var selectValues;
$.ajax({
type: "GET",
url: "http://59.163.254.24:4287/wap/retrieve/hanset/data/",
data: APP_002,
async: false,
success: function(data) {
selectValues = data;
alert("Details saved successfully!!!");
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
});
</script>
<div>
<select class="mobile-vendor">
<option value="motorola">Motorola</option>
<option value="nokia">Nokia</option>
<option value="android">Android</option>
</select>
</div>
<div>
<select class="model"></select>
<a id="download-link"> Download </a>
</div>
</body>
Why it can't it send the request to the server, I'm using logs in the server side. No request there.
The page url : http://59.163.254.24:4287/wap/download/
Ajex request Url : http://59.163.254.24:4287/wap/retrieve/hanset/data/
I used both /wap/retrieve/hanset/data/ and http://myhost.com/wap/retrieve/hanset/data/ as the parameter for url in the ajax method, both are not working.
Code on your server (link you provided) is not the same as the one you have posted in your question. Code there has error: SCRIPT1009: Expected '}' meaning that you are missing } from your javascript.
Line:
// bonus: how to access the download link
comments out the rest of javascript as you have not switched it to a new row. This commented js includes some code and closing braces. You should add newline after this comment.
This is why you have javascript error and your browser never calls server.
And your parameter should be 'APP_002', not just APP_002
When you fix this, you will probably be able to make request, but if not, we can check for any other errors when you do this.
I think the problem is you're passing APP_002 using the data parameter, which is equivalent in this case to the querystring. Looking your comments on the OP, you need to actually pass it in directly in the URL so that the request is routed correctly on the server, like this:
$.ajax({
type: "GET",
url: "http://59.163.254.24:4287/wap/retrieve/hanset/data/APP_002",
async: false,
// rest of your code...
});
Example:
http://59.163.254.24:4287/wap/retrieve/hanset/data/?APP_002 -> page not found
http://59.163.254.24:4287/wap/retrieve/hanset/data/APP_002 -> JSON response
Actually, there is not a problem with the code you provided.
Here is jsfiddle:
http://jsfiddle.net/fHtcc/1/
However, there must be an issue with APP_002 (if it is not something defined) or Jquery is not included to page.

Resources