Ajax get request with Django - ajax

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

Related

Django template not re-rendering on successful AJAX get request

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>

how do basic jquery ajax in typo3 flow?

I am trying to do some very basic ajax. I just want an onchange event on a select that will call an ajax function that will get the options for another select and fill it in. However I am not sure how to do this in a simple way in Typo3 Flow. My php code for the action just looks like this:
public function getProductsByCategoryAction( $category='' ) {
$postArguments = $this->request->getArguments();
echo __LINE__;
TYPO3\Flow\var_dump($postArguments); die;
}
and my ajax call looks like this:
jQuery('#get_category').change(function(event) {
event.preventDefault();
alert('get products');
var category = jQuery('#get_category').val();
alert(category);
jQuery.ajax({
url: "/admin/orders/getproductsbycategory.html",
data: {
'category': category
},
async: true,
dataType: 'html',
success: function(data) {
alert('hi mom');
...
}
});
});
when I try this url in the browser mysite-dot-com/admin/orders/getproductsbycategory.html?category=17ca6f3e-a9af-da7d-75cd-20f8d6a05ed0
on the page the var_dump just gives me array(empty). Why doesn't the request->getArguments() call work and give the category argument?
The getproductsbycategory.html is created in Neos and has the right plugin for the action call. So I know the right action gets run but it does not get any args. At this point the argument is just a string and not an _identity even though I should eventually do it that way, I'm trying to keep things simple for now for the sake of expediency.
Thanks
Update: as a temp workaround shameless hack I just did this to get the variable:
$categoryID = $_GET['category'];
which works but I'd like to know the proper way especially if it does not involve writing my own view helpers.
First define variable in your html file
<script>
var ajaxUrl = '<f:uri.action action="actionName" controller="(controllername)Ajax"/>';
</script>
Your Ajax code will look like :->
$.ajax({
data: '&lookup='+{somevalue},
type: 'POST',
url: ajaxUrl,
success: function(data) {
$('.lookup-id').append(data);
},
});
Your conroller action will look like :->
public function getLookupIdAction(){
// Get company detail for set logo of company
$companyDetail = $this->getUserCompany();
// Template Name
$templateName = 'GetLookupID.html';
$viewVariables = $this->lookupIdentifierRepository->findByCompany($companyDetail);
$templatepath = 'resource://WIND.Alertregistration/Private/Templates/LookupIdentifier/' . $templateName;
$this->standaloneView->setLayoutRootPath('resource://WIND.Alertregistration/Private/Layouts');
$this->standaloneView->setPartialRootPath('resource://WIND.Alertregistration/Private/Partials');
$this->standaloneView->setFormat('html');
$this->standaloneView->setTemplatePathAndFilename($templatepath);
$this->standaloneView->assignMultiple(array("lookUpValue" => $viewVariables));
$this->standaloneView->setControllerContext($this->getControllerContext());
return $this->standaloneView->render();
}
Your view file look like :->
<f:layout name="Lookup" />
<f:section name="Content">
<label for="lookupId" style="box-sizing: border-box;">Identifier</label>
<div class="select-box" style="box-sizing: border-box;">
// Your Code
</div>
</f:section>

How to call #Html.Action through Ajax in MVC (.NET)

I have a View which renders an action. For example:
<h1>Test View</h1>
#Html.Action("Intro", "Account", new { id = "5" })
However, this Action takes 10-20 seconds to load.
How can i wrap it in an ajax with a loader?
Thanks!
Just create a DIV to serve as a placeholder, then load the content on document load event into the DIV. You can also add a GIF image to show progress and hide it when the content is loaded, Here's an example of how to do it:
<h1>Test View</h1>
<div id="accountInfo"></div>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: '#Html.Url("Intro", "Account")',
dataType: "html",
data: { id : 5 },
success: function (content) {
$("#accountInfo").html(content);
},
error: function (e) { }
});
});
</script>
Please note I didn't test that and just wrote it from the top of my head so there might be some minor syntax errors but this gives you the main idea.
Hope it helps!

Load images to server from mobile site

I am developing a mobile site using asp.net and jquery. no plugin. just simple jquery.I am using the
<input type="file"/>
of HTML5.
So few questions to get the big picture:
1.Can i load files without jquery plugin, but only simple jquery? Just picking the file, send it using ajax and catch it on server side?
2. I have noticed the Request.Files attribute of the Request object. Will it get filled only with post of the whole page or can i get my files there using Ajax?
3.In case the answer in 2 is "No!", how do i exclude the files data on the server side?
Thanks
This is the solution i have found:
JS:
<script type="text/javascript">
$(document).ready(function () {
$('#inputFile').on('change', function () {
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
var formData = new FormData();
formData.append(file.name, file)
$.ajax({
url: 'AjaxPage.aspx',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (response) {
alert(response);
},
error: function (e) {
alert(e);
}
});
});
});
</script>
CS: (On ajax page to catch the files and manipulate them as you will)
var files = Request.Files;
HTML:
<body>
<div>
<input type="file" id="inputFile" />
</div>
</body>

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