javascript / ajax querying - javascript

I currently have a web page that uses javascript, however; when I use my Ajax to move towards the DB my responseText is always empty.
js to make the flag and send query
objAjaxUpdates.main_flag = "getNames";
objAjaxUpdates.SendQuery(query);
next in the flow
(The url is an aspx file)
this.SendQuery = function(data) {
this.Initialize();
if (this.req != null) {
//alert(data);
//alert(this.url + " " + this.main_flag);
this.req.open("POST", this.url);
this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
this.req.onreadystatechange = this.processData;
this.req.send(data);
}
}
Next
this.processData = function() {
if (objAjaxUpdates.req.readyState == 4) {
if (objAjaxUpdates.req.status == 200) {
if (objAjaxUpdates.req.responseText == "") {
alert('No Return');
}
else {
...
Any help would be appreciated.

I don't know the library you are using. But the procedure looks correct to me. (There are libraries like jQuery which avoids you to work on the low-level AJAX API, checking response code and so on.)
I advise you to work with something like Firebug for Mozilla, or the Chrome Developer Tools to "debug" your AJAX machinery.
There still is that good old technique:
First test the requests to the server manually.
Then, do a dumb AJAX request.
At the end, test both components.

Related

AJAX POST request to Python method - Post hits right file location, but shows 404

I've been looking at how to integrate AJAX calls into a Python Django application and I'm somewhat new to both. I have been following the advice here:
https://www.quora.com/Can-I-execute-a-Python-function-from-JavaScript
Which led to this and this respectively for AJAX and Django advice.Both made pretty good sense to me. The desired end result is that a template in this fourth folder down (dashboard) call a function in a file called logic.py under the api folder above it:
In a JavaScript file hooked up to my django template, I have the following code I stole from the AJAX resource I listed above and made some light edits to:
window.onerror = function() {
debugger;
}
// browser - safety
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if(window.ActiveXObject) { // ie
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e) {}
}
}
function step2() {
console.log('something');
}
function testLogin() {
request.open('POST', '../../../api/logic');
// I've also been trying ^^^ logic.py, if it matters
request.send(null);
console.log('testLogin ran');
step2();
}
request.onreadystatechange = function () {
if(request.readystate === 4) {
if(request.status === 200) {
console.log(request.responseText);
}
}
}
It still is hooked up to a URL POST action in the django views, so when I hit the submit button in question I see the following two requests get generated:
That is the correct filepath for that location:
So I'm wondering if I'm missing something either about the AJAX setup, or the way it needs to interact with Django, or some combination of the two. Other resources I've been consulting in looking into this:
Call Python function from Javascript code
https://codehandbook.org/python-flask-jquery-ajax-post/
https://www.makeuseof.com/tag/python-javascript-communicate-json/
https://bytes.com/topic/javascript/answers/737354-how-call-python-function-javascript
And I originally started way earlier in the day so there were a few more, but needless to say I didn't see my issue immediately from looking at any of them. Any help is much appreciated.
So this wound up being a quirk of the Django url setup, I can't believe I didn't figure it out but I hadn't been in that part of the code base for some time.
In our urls.py script, the place I was pinging (which was in the location of the URL described) had a redirect on it and for that reason, the traffic wasn't going to the place I thought.

difference from using ajax from jquery and javascript

i cant find an answer to this
i have been learning ajax lately but i learned how to do it all in javascript
now i go swiming around ajax question here and almost all are using jquery
so i end up confused. should i use normal javascript or do it through jquery?
so what are the differences?
this is my normal approach
var xmlHttp = createXmlHttpRequestObject(); //you first create the object to this function global
function createXmlHttpRequestObject() //here you instruct the function
{
var xmlHttp; //here you tell it to use the local variable not the global version of it because this returns to the global with the propper values
if (window.XMLHttpRequest) //if the "window" or browser is aware of this Object 90% of browsers
{
xmlHttp = new XMLHttpRequest(); // if true then the variable is now equal to the heart of ajax
}
else //for internet explorer
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp; //we return it back to daddy the global variable this objects does everything
//this object is everything in ajax for the most part
}
function process() //function that gets called on load of the body
{
if(xmlHttp) //if its not void or if you can run ajax
{
try //try catch statement are sort of required for the heart of things like ajax and server communication
{
xmlHttp.open("GET", "bacon.txt", true); //here 1st type of call 2nd from where 3rd
//is it true assyscronly or at the same time
//it does not start the connection to the server, its only sets up settings for the connection
xmlHttp.onreadystatechange = handleServerResponse; //anytime something changes[propertie]
//i want to call that function handleserverresponse
//begin communication
xmlHttp.send(null); //this is what communicates to the server makesure on ready statechane before this
//if the server responds you want to make sure everything is taking care of like what function onready state change is it going to call
//or what to do like open a text file in this case
} catch(e)
{
alert( e.toString() ); //alert the error message as a string on a popup
}
}
}
//handling the server response
function handleServerResponse()
{
theD = document.getElementById('theD'); //get the div in a var
if(xmlHttp.readyState==1) //if the connection to the server is established
{ //google crhome may not show this one, some browsers ignore some states
theD.innerHTML += "Status 1: server connection established<br>";
}
else if(xmlHttp.readyState==2) //request received, hey client i am the server and i received your request
{
theD.innerHTML += "Status 2: request reveived <br>";
}
else if(xmlHttp.readyState==3) //while is doing its thing
{
theD.innerHTML += "Status 3: processing request <br>";
}
else if(xmlHttp.readyState==4) //your request is finished and ready
{ //it means your response is ready but doesnt guaranteed no trouble
if(xmlHttp.status==200) //if the status is 200 then is succesufll
{
//IF everthing finally good THE GOOD PART
try //put all your calls on a try statement REMEMBER
{
//get the txt file as a string
text = xmlHttp.responseText; //response text n a normal string
theD.innerHTML += "Status 4: request is finished and response is finished";
theD.innerHTML += text;
}catch (e)
{
alert( e.toString() );
}
} else //for the other statuses like 404 else somehting went wrong
{
alert( xmlHttp.statusText ); //this will give you a status report on the wrong
}
}
}
jQuery simply wraps all of the XmlHttpRequest calls into a simple to use library. In the guts of jQuery you will see code that creates the XmlHttpRequest objects.
You can see the code that does this here:
https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js
The nice thing about using a framework like jQuery is that they handle a lot of the browser idiosyncrasies for you. They also handle a lot of the edge cases you might not think about when writing your code.
Using jQuery is just for ease of use. If you prefer doing it the javascript way then carry on doing that.
jQuery ajax calls do exactly the same as what you are doing but jQuery is a javascript framework which simplifies what you write.
jQuery is a javascript framework which contains library of simplified functions compared to the Native Javascript. One of the functions is the XMLHttpRequest.
This way we just need to implement functions that is needed to implement without needed to write the traditional codes to setup the AJAX system to work
You may learn more about jQuery ajax here:
http://api.jquery.com/jQuery.ajax/

AJAX function that uses the POST method creates the following error. Error: returned status code 414 Request-URI Too Large

I'm using an AJAX function to transfer data to a PHP file. The data that I'm passing to the AJAX function is 17000 characters long. This is generally too long to transfer using the GET method, however one would think that the POST method would allow for such large variables to be be passed on.
Here's the AJAX function I'm using:
function ajaxFunction(id, datatypeString, pathToFileString, variable){
var myRequestObject = null;
document.getElementById(id).innerHTML = "<span>Started...</span>";
if (window.XMLHttpRequest)
{
myRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
myRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
myRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
myRequestObject.onreadystatechange = function()
{
document.getElementById(id).innerHTML = "<span>Wait server...</span>";
if(myRequestObject.readyState == 4)
{
if(myRequestObject.status == 200)
{
// process a document here
document.getElementById(id).innerHTML = "<span>Processing file...</span>"
if(datatypeString == "txt"){
//Injects code from a text file
document.getElementById(id).innerHTML = myRequestObject.responseText;
}
else if(datatypeString == "xml"){
//Injects code from an XML file
document.getElementById(id).innerHTML = myRequestObject.responseXML.documentElement.document.getElementsByTagName('title')[0].childNodes[0].nodeValue; // Inject the content into the div with the relevant id
}
else{
document.getElementById(id).innerHTML = "<span>Datatype exception occured</span>";
}
}
else
{
document.getElementById(id).innerHTML = "<span>Error: returned status code " + myRequestObject.status + " " + myRequestObject.statusText + "</span>";
}
}
};
myRequestObject.open("POST", pathToFileString+variable, true);
myRequestObject.send(null);
}
And this is the function call to that AJAX function:
ajaxFunction("myDiv", "txt", "processdata.php", "?data="+reallyLargeJavascriptVariable);
Also this is the error that I'm getting when the AJAX function is called:
Error: returned status code 414 Request-URI Too Large
I've looked around on Stackoverflow and other websites for a solution to this problem. However most answers come down to: "Use the POST method instead of the GET method to transfer the data."
However as you can see in the AJAX function, I'm already using the POST method.
So I'm not sure what's going on here and what to change in my code to solve this issue. I simply want to be able to pass very large variables to my function, but with this function that doesn't seem possible.
Given the error, the limitations of the URI seem to be causing the problem. However, I'm using the POST method and not the GET method, so why is the variable still passed via the URI? Since I am not using the GET method, but rather the POST method like many people suggested in other threads about this problem, I'm not sure why the URI is involved here and is seemingly causing a problem.
Apparently the URI is putting a limit on the size of the variable that I can transfer, however I'm using the POST method, so why is this error occurring and how can I adjust my AJAX function to make it work with the large variables that I want to transfer using AJAX?
When you're doing a POST you need to pass the POST data on the .send (you're currently passing null). You need to set a few header details, as well.
myRequestObject.open("POST", pathToFileString, true);
myRequestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequestObject.setRequestHeader("Content-length", variable.length);
myRequestObject.send(variable);
If you're currently passing a question mark in the start of variable or end of the path go ahead and remove it.

Replace current page with ajax content

I have a page with a dialog window which sends ajax post data to server and receives a response. During development, there can be two responses - one regular (this is not the question) or one with an error. Server returns code 500 and a page with lot of debug informations. This is a regular page returned from a framework and contains some javascript code. I want to be able to display this error page in case it happens.
The problem is, I can not simply attach the returned result to body element or open a new link in a new page and load this error again. I simply get a html page instead of data and I have to display the page (in current window or in another one).
I am using jQuery.
Configure jQuery ajax setup as follows:
$.ajaxSetup({
error: handleXhrError
});
where handleXhrError function look like this:
function handleXhrError(xhr) {
document.open();
document.write(xhr.responseText);
document.close();
}
See also:
Handling of server-side HTTP 4nn/5nn errors in jQuery
You may also try to use data URL's, the latest versions of the major browsers supporting it:
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function loadHtml(html)
{
localtion.href='data:text/html;base64,'+utf8_to_b64(html);
}
This way, you can load any html page you want in runtime.
In your ajax callback:
success: function (data) {
$("html").html($(data).find("html").html());
}
That will replace the entire page's HTML content with the one received from your AJAX request. Works in Chrome... not sure about IE.
Despite that, I'm not sure why you'd want to include the <head> section... but you can easily modify the above to display just what's in the body of the AJAX response, and append it to a div or even a lightbox. Much nicer.
Here is an example of how to change either if the response is a url or a html content (using django\php)
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
var replace_t = '{{ params.replace_t }}';
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(replace_t == 'location')
window.location.replace(xmlhttp.responseText);
else if(replace_t == 'content')
{
document.open();
document.write(xmlhttp.responseText);
document.close();
}
}
}
xmlhttp.open("GET",SOME_ASYNC_HANDLER_URL,true);
xmlhttp.send();
I found this solution. I don't know if it si correct, but for Opera and Firefox it is working.
var error_win = window.open(
'',
'Server error',
'status=0,scrollbars=1, location=0'
);
error_win.document.write(XMLHttpRequest.responseText);
Have you tried just simply creating an element and inserting the returned error page into the element? I do this with error pages and jQuery.
var errorContainer = $( '<div/>' );
errorContainer.html( errorTextResponse );
errorContainer.appendTo( $( 'body' ) );
I may be misunderstanding, but do you know what elements from the result you specifically want to display? You could trying something like this:
success: function(data){
//store the response
var $response=$(data);
//use .find() to locate the div or whatever else you need
var errorMessage = $response.find('#warning').text();
alert(errorMessage);
}
Is that what you were looking for?
I don't think there's any way to do that. Iframes are meant for loading other pages and there's no other sandbox in which to dump a standalone page -- that's what frames were designed for.
It might be difficult with the framework you're using, but it's probably worthwhile to have it generate different errors for your Ajax requests. My Ajax pages will only ever send
{"exit": 1, "message": "As in the shell, a non-zero exit is an error and this is why..."}
Just figured this out
as easy as
document.body.innerHTML = YourAjaxrequest.responseText;
_______________________________________________^ up here is what over writes your current HTML page with the response.
request.onreadystatechange = function() {
if (request.readyState == 1) {
document.getElementById('sus').innerHTML = "SENDING.......";
}
if (request.readyState == 3){
document.getElementById('sus').innerHTML = "SENDING >>>>>>>>>>>>>";
}
if (request.readyState == 4 && request.status == 200) {
//document.getElementById('sus').innerHTML = request.responseText;
document.body.innerHTML = request.responseText;
}
}
request.send(formD);
},false);

Cross-browser implementation of "HTTP Streaming" (push) AJAX pattern

Client request web page from server. Clent then requests for extra calculations to be done; server performs series of calculations and sends partial results as soon as they are available (text format, each line contains separate full item). Client updates web page (with JavaScript and DOM) using information provided by server.
This seems to fit HTTP Streaming (current version) pattern from Ajaxpatterns site.
The question is how to do it in cross-browser (browser agnostic) way, preferably without using JavaScript frameworks, or using some lightweight framework like jQuery.
The problem begins with generating XMLHttpRequest in cross-browser fashion, but I think the main item is that not all browsers implement correctly onreadystatechangefrom XMLHttpRequest; not all browsers call onreadystatechange event on each server flush (BTW. how to force server flush from within CGI script (in Perl)?). Example code on Ajaxpatterns deals with this by using timer; should I drop timer solution if I detect partial response from onreadystatechange?
Added 11-08-2009
Current solution:
I use the following function to create XMLHttpRequest object:
function createRequestObject() {
var ro;
if (window.XMLHttpRequest) {
ro = new XMLHttpRequest();
} else {
ro = new ActiveXObject("Microsoft.XMLHTTP");
}
if (!ro)
debug("Couldn't start XMLHttpRequest object");
return ro;
}
If I were to use some (preferably light-weight) JavaScript framework like jQuery, I'd like to have fallback if user chooses not to install jQuery.
I use the following code to start AJAX; setInterval is used because some browsers call onreadystatechange only after server closes connection (which can take as long as tens of seconds), and not as soon as server flushes data (around every second or more often).
function startProcess(dataUrl) {
http = createRequestObject();
http.open('get', dataUrl);
http.onreadystatechange = handleResponse;
http.send(null);
pollTimer = setInterval(handleResponse, 1000);
}
The handleResponse function is most complicated one, but the sketch of it looks like the following. Can it be done better? How it would be done using some lightweight JavaScript framework (like jQuery)?
function handleResponse() {
if (http.readyState != 4 && http.readyState != 3)
return;
if (http.readyState == 3 && http.status != 200)
return;
if (http.readyState == 4 && http.status != 200) {
clearInterval(pollTimer);
inProgress = false;
}
// In konqueror http.responseText is sometimes null here...
if (http.responseText === null)
return;
while (prevDataLength != http.responseText.length) {
if (http.readyState == 4 && prevDataLength == http.responseText.length)
break;
prevDataLength = http.responseText.length;
var response = http.responseText.substring(nextLine);
var lines = response.split('\n');
nextLine = nextLine + response.lastIndexOf('\n') + 1;
if (response[response.length-1] != '\n')
lines.pop();
for (var i = 0; i < lines.length; i++) {
// ...
}
}
if (http.readyState == 4 && prevDataLength == http.responseText.length)
clearInterval(pollTimer);
inProgress = false;
}
The solution you linked to is not AJAX at all, actually. They call it HTTP Streaming but it's essentially just long polling.
In the example they link to, you can see for yourself quite easily with firebug. Turn on the Net panel - there are no XHR entries, but it takes just a hair over 10 seconds to load the original page. That's because they're using PHP behind the scenes to delay the output of the HTML. This is the essence of long polling - the HTTP connection stays open, and the periodic HTML sent back is javascript commands.
You can opt to do the polling completely on the client side, though, with setTimeout() or setInterval()
A jQuery example
<script type="text/javascript">
$(document).ready(function()
{
var ajaxInterval = setInterval( function()
{
$.getJSON(
'some/servie/url.ext'
, { sample: "data" }
, function( response )
{
$('#output').append( response.whatever );
}
);
}, 10000 );
});
</script>
I would take a look at orbited
They use several comet transport implementation that they choose based on configuration and browser sniffing.
See http://orbited.org/svn/orbited/trunk/daemon/orbited/static/Orbited.js
and look for "Orbited.CometTransports"
Some of the different transports must be matched by the backend implementation, so have a look at the server side for orbited also.

Categories

Resources