Django character wrong encoding for Ajax request - ajax

I have a form which is generated from a database. In the database I have strings such as 'Española' which will become options in a drop down menu.
A the moment my html looks like:
<option value="Española">Española</option>
I am using these values for a dynamic part of the form from which I need to send AJAX requests.
I can see that, when using IE, the header is like so:
GET /collections/find_island?island_group=Espa�ola HTTP/1.1" 500 63206
when it should be:
GET /collections/find_island/?island_group=Espa%C3%B1ola HTTP/1.1" 200 164
As generated by other browsers.
Is there some way I can get this output in my template:
<option value="Espa%C3%B1ola">Española</option>
Any help much appreciated.
EDIT:
My form:
def form(forms.Form):
...
island_group = forms.ModelChoiceField(
required=False,
label=ugettext_lazy('Island Group'),
initial=None,
queryset=Localityonline.objects.values_list('islandgroup', flat=True).distinct('islandgroup').order_by('islandgroup'),
empty_label=ugettext_lazy("Not Specified"),
widget=forms.Select(attrs={"class":'searchfield', "onChange":'getIslandName()'})
)
the javascript:
function getIslandName(lang) {
var islandGroup = document.getElementById("id_island_group").value;
if (islandGroup == '') {
// if Not Specified re-selected then set data to null and bypass updatePage()
var data = null;
update_select($('select[name=island_name]'), data);
}
else {
var url = "../collections/find_island?island_group=" + islandGroup;
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
}

You can call encodeURI in javascipt to give the encoded value that you are looking for. Perhaps mozilla and chrome do it automatically and IE doesn't???
encodeURI('Española')
// "Espa%C3%B1ola"
var url = "../collections/find_island?island_group=" + encodeURI(islandGroup);
or encode the whole url I don't know which one makes more sense...
Encode URL in JavaScript?
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI

Related

Laravel render for differend controller method

I'm struggling with the render() method in Laravel 5.
When $whatever->render() is runned, it takes the controller method name as the route by default.
Example:
When i run this command in DelasController#updateFilter, the pagination route is set to whatever.com/marketplace/updateFiler?page=2, which does not make a sense to me.
Problem:
I want to keep the route as simple as whatever.com/marketplace?page=2.
Question:
Can anybody gives me a hint on how to solve this?
Thank you for your time and a discussion.
Looking forward for a reply.
I have an application in which various paginated lists are displayed in "windows" on the page and are updated via AJAX calls to the server. Here's how I did it:
Set up a route to render the whole page, something like this:
Route::get('/marketplace', function ($arguments) {
....
});
Set up a route which will return the current page of the list. For example, it might be something like this:
Route::get('/marketplace/updateFiler', function ($arguments) {
....
});
In your Javascript code for the page, you need to change the pagination links so that, instead of loading the new page with the URL for the link, it makes the AJAX request to the second route. The Javascript could look something like this:
$('ul.pagination a').on('click', function (event) {
// stop the default action
event.stopPropagation();
event.preventDefault();
// get the URL from the link
var url = $(event.currentTarget).attr('href');
// get the page number from the URL
var page = getURLParameterByName(url, 'page');
$.get('marketplace/updateFiler', { page: page }, function (data){
// do something with the response from the server
});
});
The getURLParameterByName function is simply a helper that extracts the named parameter from a URL:
var getURLParameterByName = function (url, name, defaultValue) {
// is defaultValue undefined? if so, set it to false
//
if (typeof defaultValue === "undefined") {
defaultValue = false;
}
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results === null ?
defaultValue :
decodeURIComponent(results[1].replace(/\+/g, " "));
};
I adapted this code from an answer I found here on Stack Overflow: https://stackoverflow.com/a/901144/2008384.

304 not modified, Ajax is not working?

<script>
var xmlHttp =new XMLHttpRequest();
var url= "summary.txt";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var myArr = JSON.parse(xmlHttp.responseText);
myFunction(myArr);
}
xmlHttp.open("GET", url , true);
xmlHttp.send();
} function myFunction(arr)
var output="";
var i;
for(i=0;i<arr.length;i++){
output+='<p>'+arr[i].title+arr[i].image+arr[i].price+'</p>';
}
document.getElementById("proTab").innerHTML = output;
}
</script>
I stored all both the HTML and JSON in the htdocs folder, did xampp start and made sure Apache and mysql were running on the control panel. I then typed the link to the html using the "localhost/" to get to the html but the page was blank. Sorry for all the details.
Console says 304 Not modified. What should I do?
My guess is that you are using IE, which caches AJAX GET requests aggressively. I would suggest changing to using POST for the AJAX request.
Another alternative if you must use GET requests. You can add a unique querystring value to each GET request like this:
var url = 'summary.txt' + '?' + Math.random()*Math.random();
I used this for jQuery AJAX:
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
I think you can find how to use this for JS without jQuery. So the idea is to clear cache before sending the request, because server responds that nothing changed and sends 304 NOT MODIFIED instead of 200 OK. Namely, your summary.txt hasn't changed (not modified), so that's what server telling you.

My ajax request isn't working

I have an <ul id="keuze_lijst"> , an input field with id #sykje and an button with class .search .
Now when i press the button i would like to clear the UL and repopulate it with data, for this i currently got this .js file.
$(document).ready(function() {
$(".search").click(function(){
var searchValue = $("#sykje").val();
$("#keuze_lijst").empty();
$.ajax({
url: 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search='+searchValue,
data: "",
dataType: 'json',
success: function(rows) {
for(var i in rows){
var row = rows[i];
var id = row[1];
var titel = row[2];
var artiest = row[9];
$("#keuze_lijst").append("<li class='mag_droppen'>"+
"<div class='song_left'>"+
"<div class='titel'>"+titel+"</div>"+
"<div class='artiest'>"+artiest+"</div>"+
"</div><!-- .song_left -->"+
"</li>");
}
}
});
});
});
When i remove the ajax command and put something like $("#keuze_lijst").html("hello"); it works fine. But the ajax command isn't working. Though the var searchValue does his work. (ajax uses the correct url). And when i enter that url the page echoes an fine json with multiple rows.
But in my page the ajax script isn't adding the <li>.
What am i doing wrong?
edit: added an jsfiddle -> http://jsfiddle.net/TVvKb/1/
.html() totally replaces the HTML. So at the end, your "#keuze_list will contain </li>.
Just execute one html() command after you build your html into a string var or something.
From a quick glance, I can say that the problem might be with your use of the html() function. This actually replaces the entire html content.
You might want to try using append() or prepend().
Possible Problems:
You are running into a Same Origin Problem. Per default you can only make Ajax-Requests to your own domain. If you need to make cross-domain calls use JSONP or CORS.
Use the html() only once, and hand over your complete string, otherwise you will override your previous html all the time.
You are not landing in the success handler due to an error (e.g. invalid JSON).
Not sure, but I think if you insert a string in the .append() and other jQuery methods, it parses to (valid) HTML first. That means that unclosed tags are closed, making your HTML invalid.
$('<div />'); // parses to <div></div>
So, I assume that your DOM ends up like this this:
$('ul').append('<li>').append('foo').append('</li>'); // <ul><li></li>foo</li></ul>
Please, just format your string first. You don't want jQuery to parse every input.
var str = '<li>';
str += 'foo';
str += '</li>';
$('ul').html(str);
For cross-domain AJAX requests (without JSONP):
proxy.php
header('Content-Type: application/json');
if(empty($_GET['search'])) exit;
$url = 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search=' . $_GET['search'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
curl_close($ch);
Javascript
$.getJSON({
url: 'proxy.php&search='+searchValue,
success: callback
});

Information Bar appears in IE8 while downloading

I have an application in which there are options to Export the document in Word/PDF format. We do a form submit to post the HTML and send it to the server for conversion. In the back-end the servlet writes it back to client after setting a contentType. The Information Bar appears during the first download only.
I cannot recommend users to reduce their Browser Security levels. Hence i need a solution to by-pass this alert. I saw that Google Docs has handled this. Does anyone have an idea about what needs to be done ?
I'm using the following JQuery code:
$.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : $.param(data);
//split params into form inputs
var inputs = '';
$.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
$('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
And each time download should be initiated, I'm firing
$.download(options);
Server response is with proper content-type headers (e.g. Word).
Maybe you have forgotten to remove submitted form from the DOM?

What do browsers want for the Content-Type header on json ajax responses?

I am returning some json which needs to be handled by javascript as the response to an XMLHTTPRequest.
If I set the response's content type to "text/plain", all browsers but Chrome will accept it and pass it to my JS with no problem. However, Chrome will wrap the response in
<pre style="word-wrap: break-word; white-space: pre-wrap;">
before passing it to my javascript.
If I set the response's content type to the "proper" "application/json" all browsers but Firefox will accept it and pass it to my JS with no problem. Firefox, however will ask to save or open the response as a file.
What's the correct, cross-browser Content-Type?
You may solve the issue by parsing the response into the JSON object by using jQuery funcion parseJSON - http://api.jquery.com/jQuery.parseJSON/
The parameter you pass into the function is the JSON object string, which you extract from the response data:
function AjaxResponse (data) { // AJAX post callback
var jsonResult = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));
}
Tested (besides Chrome which problem this solves) in FF and IE8 for the following simple JSON result, for other browsers and more complex responses no guarantees...
NOTE: the content type in this case is text/plain or text/html I think - I've used the following ASP.Net MVC function to return the result
ContentResult System.Web.Mvc.Controller.Content(string content);
Where I returned the JSON object like
System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer
= new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonResponse = jsonSerializer.Serialize(
new { IArticleMediaId = 0
, ImageUrl = Url.Content(fullImgPath)
});
return Content(jsonResponse);
In ajaxFileUpload.js in uploadCallback() replace
io.contentWindow.document.body.innerHTML.innerHTML
with
$(io.contentWindow.document.body.innerHTML).html()

Resources