Django GET request in AJAX - ajax

I need to get some HTML using AJAX.
My view work fine as long as I use jQuery:
view.py
def my_ajax(request):
if request.is_ajax():
my_form = MyForm()
context = {
'form': my_form
}
return render(request, 'myapp/form.html', context)
main.js (jQuery load)
$(document).ready(function() {
$('#foo').click(function() {
$('#bar').load('{% url "myapp:form" %}');
});
});
If I use the JavaScript XMLHttpRequest I have to remove if request.is_ajax(): from the view otherwise I got the error The view myapp.views.my_ajax didn't return an HttpResponse object. It returned None instead.
main.js (XMLHttpRequest)
(function() {
document.getElementById('foo').addEventListener("click", function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("bar").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", '{% url "myapp:form" %}', true);
xhttp.send();
}, false);
})();
What I'm doing wrong in the XMLHttpRequest?
I am surely missing something but I would like to use Vanilla JavaScript this time.
Thanks!

Try to add xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); after var xhttp = new XMLHttpRequest();.

Related

Worpress bad request 400 pure Javascript

I get this following error when I use ajax in pure javascript:
"POST http://localhost:8888/website/wp-admin/admin-ajax.php" 400 (Bad Request) line in code: this.xhr.send(JSON.stringify(data));
my Contact.js file:
var Contact = function(data){
//setups and others methods
this.onFormSent = function(data){
data = {
action: 'my_action',
data: data
};
if(this.ajaxSendURL !== null){
this.xhr.open("post", this.ajaxSendURL);
this.xhr.setRequestHeader("Content-Type", "application/json");
this.xhr.onload = function() {
if(self.xhr.status === 200){
console.log(self.xhr.responseText);
var response = JSON.parse(self.xhr.responseText);
self.onSuccessForm(data);
}
};
this.xhr.send(JSON.stringify(data));
}
};
};
I use a form tag in html after filled my "form" and pressed the submit button it should call 'my_action' in php.
this my function.php:
function add_theme_scripts() {
wp_enqueue_script('Contact', get_template_directory_uri() . '/js/Contact.js', array(), 1.0, true);
wp_localize_script('Contact', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
/* AJAX */
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action(){
echo 'msg from server:' + $_POST['data']['name'];
die();
}
What am I doing wrong?
Updated: replaced by the following code and it works
this.onFormSent = function(data){
data = "action=my_function&name=" + dada.name;
this.xhr.setRequestHeader("Content-Type", "application/json");
...
}
Change this lines in ajax request;
data = {
action: 'my_action',
data: youdatadata
};
var data = $.param(data);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(data);

How to add live data to stacked bar chart

I have a stacked bar chart, which gains data from an api.
It works fine when loaded, and the data is displayed as it should be.
Now I wish to add new data to the chart every ten minutes, calling the same API as when loaded, the chart should refresh asynchronously and he new data and axis label need to be updated as new data is gained.
What I have done so far..
https://plnkr.co/edit/s2Os8UlpSbCWlkNP6wuA?p=preview
var ma = d3.line()
.x(function(d) { return x(parseDate(d.date)); })
.y(function(d) { return y(d.ma); });
If you use jquery, then you can send an AJAX request using the $.ajax function. Make sure you handle the response in the result's done() function, as success is deprecated.
Plain AJAX request example:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
JS:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Taken from here. If you mastered AJAX requests, then the next step is to write a poller, using setInterval. The first parameter should be a function which sends a request and the second should be the time between two execution in milliseconds (10000 in this case). Or you can use an existing poller. This is one I have implemented:
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function Poller(params) {
Initializable.call(this, params);
var that = this;
this.initialize("url", window.location.href);
this.initialize("interval", 5000);
this.initialize("type", "POST");
this.initialize("method", "POST");
this.initialize("data", {});
this.initialize("strict", true);
var defaultFunction = function() {};
this.initialize("done", defaultFunction);
this.initialize("fail", defaultFunction);
this.initialize("always", defaultFunction);
this.isRunning = function() {
return !!params.intervalID;
};
this.run = function() {
if (this.strict && (this.green === false)) {
return;
}
this.green = false;
$.ajax({
url: this.url,
method: this.method,
data: this.data
}).done(function(data, textStatus, jqXHR) {
that.green = true;
that.done(data, textStatus, jqXHR);
}).fail(function(jqXHR, textStatus, errorThrown) {
that.green = true;
that.fail(jqXHR, textStatus, errorThrown);
}).always(function(param1, param2, param3) {
that.green = true;
that.always(param1, param2, param3);
});
};
this.start = function() {
if (!params.intervalID) {
this.run();
params.intervalID = setInterval(this.run.bind(this), this.interval);
}
};
this.stop = function() {
if (!!params.intervalID) {
clearInterval(params.intervalID);
params.intervalID = undefined;
}
};
}

XDomainRequest Errors, but developer tools shows response body

I am using XDomainRequest to send a cross domain request. The onerror handler is firing; however, nothing is logged and when tracing network in developer tools I can see the response in the response body.
Anyone have any ideas? Below is the code I am using. Thanks in advance for any help.
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'https://myurl';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
//alert("load");
alert(xhr.responseText);
};
xhr.onprogress = function(){
alert("Progress");
}
xhr.onerror = function() {
alert("error");
};
xhr.send();
XDomainRequest object does not provide anyway to determine what is the status code of error, and returns empty string in xdr.responseText.

Mootool ajax readystate response is always 1?

I've been trying to make this mootools (ver: 1.2.4) Class to process my ajax requests. But my scripts only returns readystate 1. never gets to 2,3 ,or 4, the method handleHttpResponse only seems to run once. I'ves put alerts to see and I only get 1. any ideas?
var replyXML = new Class ({
/* GDW AJAX REQUEST SCRIPT */
/* By: Jonathan Robidas 2011-05-13 */
initialize : function(url){
this.http = this.getHTTPObject(); // We create the HTTP Object
this.url = url; // Requested server-side script
this.response = ''; // String returned by AJAX, Set after positive response
},
returnResponse : function() {
return this.response;
},
handleHttpResponse : function() {
alert(this.http.readyState);
if (this.http.readyState == 4) {
if(this.http.status==200) {
alert("YA YA 2");
this.response = this.http.responseText;
return true;
}
}
},
requestXML : function() {
this.http.open("GET", this.url, true);
//this.http.onreadystateshange = this.handleHttpResponse();
this.http.onload = this.handleHttpResponse();
},
getHTTPObject : function() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
});
This is how i launch it for now. my content is null but my url is a working XML file. so it shouldnt be blank... ?
<script language="Javascript" type="text/Javascript">
window.addEvent('domready', function() {
loadXML = new replyXML('gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59');
loadXML.requestXML();
content = loadXML.returnResponse();
alert(content);
/*
x=content.documentElement.childNodes;
for (i=0;i<x.length;i++) {
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}
*/
});
</script>
Tested on Google chrome, Firefox 4, Internet explorer 7 & 8, all same result.
Here is an example of XML the script is suppose to output: http://jerenovici.net/gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59 so I know my php generating the xml is fine.
Thanks!!
Why are you reinventing the wheel? If you're using mootools, making an ajax request is extremely easy (docs, referring to newest version, but in this case Request hasn't changed):
new Request({
url : './gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59',
onSuccess : function(responseText, responseXML){
/* here, do stuff with your response */
},
onFailure : function(xhr){
/* the XMLHttpRequest instance. */
}
}).send();
Then, are you sure the url is correct?

AJAX doesn't send POST query

$(document).ready(function() {
function ajaxselectrss(rssurlvar) {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('news');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
//var rssurlvar = $(this).attr("title");
var queryString = "rurl=" + rssurlvar;
var urltofile = "rssget.php";
ajaxRequest.open("POST", urltofile, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", queryString.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(queryString);
}
$(".rshownews").click(function() {
window.setInterval(function() {ajaxselectrss($(this).attr("title"))}, 1000);
});
});
The POST query is "undefined" (Firebug).
You should use $.ajax - it will standardise the whole XmlHTTPRequest thing across browsers.
$.ajax({
type: "POST",
url: "rssget.php",
data: queryString,
success: function(data) {
$('#news').html(data);
}
});
(And, BTW, if you setInterval in your click handler, you will start a new periodic call to your ajaxselectrss function every time the button is clicked.)
Also, your context has changed due to the wrapper function. Try changing your click handler like so:
$(".rshownews").click(function() {
var _this = this;
window.setInterval(function() {ajaxselectrss($(_this).attr("title"))}, 1000);
});
Since you seem to use jquery anyway ($(document).ready) you could use it's wrapper for simplifying ajax-requests.
http://api.jquery.com/jQuery.post

Resources