how to fix xmlhttprequest function problem when inserting data - javascript

my code works only if i add this code:
document.write(str);
which open a new page and write in it insert data in database
but if i try to the code without it like this :
function addcourse2(str,cn)
{
xmlhttp=new XMLHttpRequest();
//document.write(str);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status == 200) {
alert('response:'+xmlhttp.responseText);
} else {
alert('failure!');
}
};
xmlhttp.open("GET","tpages/addcourse2.php?q="+str+"&p="+cn,true);
xmlhttp.send();
}
here i get alert message failure and nothing gets inserted into database
i need and explanation to this a way to fix it

looking at your comments i understand that the page is refreshing after you click the button before the state is reaching 4 then this is the button code to prevent it from refreshing
add return false;
<button "onclick='addcourse2("value1","value2");return false;'>add course</button>

Let's try to describe.
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open.
https://developer.mozilla.org/en-US/docs/Web/API/Document/write
So, this AJAX script with document.write work as from new page and each case calls to URL ""tpages/addcourse2.php?q="+str+"&p="+cn"
If commented document.write Then browser may be cached URL and browser read from cache and doesn't call same URL. So, you can use unique URL string and test so.
Also, may be was an other case.

Related

Ajax reloads page instead of submitting the request

I have an Ajax script that causes the entire page to reload without ever submitting the URL for the request in the script. The server logs show the page URL as being re-submitted. Adding an alert demonstrates that the function is being run, but the embedded URL seems to be ignored. When used by itself, the request URL in the script returns the correct data.
Why isn't the embedded URL applied?
Another Ajax script on the same page works fine using a var named xhttp instead of xfiles so there's no conflict in that.
function rlist() {
var xfiles = new XMLHttpRequest();
xfiles.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("filelist").innerHTML =
this.responseText;
}
};
xfiles.open("GET", "/cgi-bin/cnc.cgi?precert~patients~rlist~813527153~0975184859230735~~6306919737~622156596S", true);
xfiles.send();
}
The objective is to refresh a small table of uploaded files. The responseText contains the table html with links. That can't be the issue here though since the URL is never submitted in the first place.
Swetank Poddar actually had the right idea... As it turns out, it was user error. I had left out the colon in javascript:void(0) and continuously overlooked it. So the Ajax was running correctly but the typo in the link was causing the page to subsequently reload. It was all so fast that it wasn't obvious and the database on the server showed the last processed hit as the link to load the page in the first place, which was the link to reload it as well.

Call to xmlhttprequest from page onload event is not working OK when Back from another page

After going from my page to anther page by pressing a link, and than back to current page, than in call to xmlhttprequest from onload event, The js code of xhr.open and xhr.send is working, but the sever side code called by xhr is not running, and in xhr.onreadystatechange function the xhr.responseText is returning his old value.
In this scenario off comming back from another page, call to xmlhttprequest from document.onreadystatechange event is also not working OK.
The same code works OK when I call it from onload in the first page loading (before going to another page and returning), or when I call it from a button click.
Why the call to xmlhttprequest from onload event is not working OK when Back from another page?
I'm using Chrome.
Here is my code:
<script type="text/javascript">
function CallAJAX() {
xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = AJAX_onreadystatechange;
xhr.open("GET", '/MyPage.aspx', true);
xhr.send(null);
}
function AJAX_onreadystatechange() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('xhr.responseText=' + xhr.responseText);
}
}
window.onload = function () {
//alert is working also after going to link and than back to current page
alert('alert')
//Call to xmlhttprequest from page onload event - is Not working OK - after going to link and than back to current page
CallAJAX();
}
</script>
<!--here is the "link" mentioned in the above comment-->
link
<!--Call to xmlhttprequest from button onclick event - is working OK-->
<input id="Button1" type="button" value="button" onclick="CallAJAX();" />
Update
I found the problem:
In some browsers, and in some circumstances, xhr brought the xhr.responseText
value from browser cache, instead to call server.
Here is the solution:
This problem solved by adding unique query string param to url param of xhr.open. This guaranty that the ajax will avoid using the cache, and always hit the server, because with the unique param, the url is turned to unique in every call to xhr.open.
The unique value is produced by "new Date().getTime()" which returns the number of milliseconds between midnight of January 1, 1970 and now.
This is the solution code:
xhr.open("GET", '/MyPage.aspx?uniqueParamVal=' + new Date().getTime(), true);

Execute <script> from separate .php file

Been working on (what seemed like) a simple issues for a few days now and could use some help.
I call a php file on a button-click, do a bunch of server-side operations, and wish to change a few things in the HTML at the end of the php (change images, changing text, enabling buttons, etc.)
So, what I'm trying to do (for the test case here) is change an image twice. It works fine in the first set of code (script in the html file), but it doesn't work in the second set of code (script in the php file). I.e., I see oldImage when the page loads, secondImage when I click the button, but I never see newImage.
<button onclick="test()">Try The Test</button>
<img id="myImage" src="oldImage.jpg">
<script>
function test()
{
var img = document.getElementById('myImage');
img.src = 'secondImage.jpg';
xmlhttp=new XMLHttpRequest();
xmlhttp.open("testPhp.php",true);
xmlhttp.send();
}
</script>
Here's myPhp.php (all on one line in my code; two lines here, for readability):
$script = "<script> var img = document.getElementById('myImage');
img.src = 'newImage.jpg'; </script?";
echo $script;
Any ideas on why the script in myPhp.php doesn't work?
EDIT:
I changed the HTML portion to this, then changed myPhp.php to echo "Hello World", which shows up just fine within myDiv. However, I can't seem to echo the script. Is there any way to do this?
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","portTester.php",true);
xmlhttp.send();
If your ajax call returns markup, for it to have any effect, it has to be added to the DOM.
But I wouldn't recommend doing it this way. Instead, have your PHP file return the information (not a script), and then have the code receiving the information (in the onreadystatechange handler of the XHR object) read that information and take the relevant action.
For example, your PHP could simply return:
newImage.jpg
Then your ajax call would be:
function test()
{
var img = document.getElementById('myImage');
img.src = 'secondImage.jpg';
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = handleReadyStateChange;
xmlhttp.open("testPhp.php",true);
xmlhttp.send();
function handleReadyStateChange() {
if (xmlhttp.readyState === 4 && xmlhttp.status >= 200 && xmlhttp.status < 400) {
// Request is complete and successful
img.src = xmlhttp.responseText;
}
}
}
If you need to send back richer information (as is frequently the case), look at using JSON.
You're not doing anything with the response to your AJAX call. In other words: You are calling the PHP script, the reply is printed, but is thrown away, because your Javascript isn't doing anything with it. You must add some code to interact with the reply. Here's a hint: Don't try to output Javascript from PHP, output something that you USE in your Javascript.
Add this to your Javascript after the xmlhttp.send() call:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myImage").src = xmlhttp.responseText;
}
}
And in your PHP script, put just this:
echo 'newImage.jpg';
One possible issue is that you are missing the semi-colon after your test() in the onclick. Also, your </script> tag is malformed; it reads </script? while it should read </script>. Also, where into the DOM is this echoing? It should go into the head of your document. Right now, it looked unspecified.

XMLHttpRequest asynchronous not working, always returns status 0

Here's a sample XMLHttpRequest I cobbled together from w3schools
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var T="nothing";
xmlhttp=new XMLHttpRequest();
xmlhttp.overrideMimeType('text/plain'); // don't sc
xmlhttp.onreadystatechange=function()
{
alert ("rdystate: " + xmlhttp.readyState);
alert ("status: " + xmlhttp.status);
alert ("Text: " + xmlhttp.statusText);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
T = xmlhttp.responseText;
}
}
xmlhttp.open("GET","SBL_PROBES.htm",true);
xmlhttp.send(null);
//T = xmlhttp.responseText;
alert(T);
}
</script>
</head>
<body>
<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">CHange Content</button>
</body>
</html>
XMLHttpRequest always returns a zero status.
Nothing shows up in Firefox's error console.
If I change the request to synchronous one by changing the line
xmlhttp.open("GET","SBL_PROBES.htm",true);
to
xmlhttp.open("GET","SBL_PROBES.htm",false);
and un-comment the line
//T = xmlhttp.responseText;
The text of the requested file is returned.
The HTM and the file reside in the same directory. If you try this you will need a file SBL_PROBES.htm there also, it's contents are irrelevant.
I'm using Firefox 3.6.22.
Could this be a cross domain problem? If so, why does it work as a synchronous request?
You can use a function inside the if statement. This function is executed when readystate changes to 4.
var handleResponse = function (status, response) {
alert(response)
}
var handleStateChange = function () {
switch (xmlhttp.readyState) {
case 0 : // UNINITIALIZED
case 1 : // LOADING
case 2 : // LOADED
case 3 : // INTERACTIVE
break;
case 4 : // COMPLETED
handleResponse(xmlhttp.status, xmlhttp.responseText);
break;
default: alert("error");
}
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=handleStateChange;
xmlhttp.open("GET","SBL_PROBES.htm",true);
xmlhttp.send(null);
Your old code did a asynchronous call and continued just with the alert Statement. T was empty at this time.
Ok, I'll explain a little bit how this whole thing works:
First we define two callback functions, which we call later in the request, named handleResponse and handleStateChange.
Afterwards we create a Object, which represents the XMLHttpRequest
var xmlhttp=new XMLHttpRequest();
This results in an Object as follows (simplyfied):
XMLHttpRequest { status=0, readyState=0, multipart=false, onreadystatechange=handleEvent()}
With the open(...) function call you set parameters for the request:
xmlhttp.open("GET","SBL_PROBES.htm",true);
This means, do a asynchronous GET Request to fetch the Page SBL_PROBES.htm
Then the send(...) function is called which fires the request itself.
We registered a callback function for the onreadystatechange, as you can imagine, this is actually an eventHandler. Each time the state changes this function is called. (It is the same as if you register a callback function to an onKeyUp Event in a form, this callback is triggered each time your key goes up :) )
The only case which is of interest for your problem is state 4. Therefor the handleRequest callback function is called only in state 4. At this time you Request has actually a result, and further a status. (Status means your webserver returned a status code 200=ok, 404=not found etc.)
That is not all the magic which is behind the ajax stuff, but should give you a simplified overview, what is actually happening behind the scenes.
It is important that you test this on a webserver, do not use file:// for testing.
If you need more in detail info, just let me know.
Status Zero happens for two reasons.
You are running off the file protocol.
Something is posting back the page when the Ajax request is active.
I believe you are seeing #2 here. SO you need to cancel the button click.
<button type="button" onclick="loadXMLDoc(); return false;">CHange Content</button>
In your code above that alert(T) will always say nothing when the request is asynchronous.
Its because async returns before the request returns. Synchronous requests return after the request returns.
Try manipulating your logic in here.
xmlhttp.onreadystatechange=function()
{
alert ("rdystate: " + xmlhttp.readyState);
alert ("status: " + xmlhttp.status);
alert ("Text: " + xmlhttp.statusText);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
T = xmlhttp.responseText;
alert(T);
}
}
I've battled the problem of not getting a result when using asynchronous XMLHttpRequest open statement. Since this question is the first I found when using google, here is how I solved it:
If you use a button that is inside a form, make sure it is set to type="submit" and onclick="return myFunction()". And in myFunction(), make sure you return false, not true! By returning true from the function, you reload the page and the XML object disappears. If you return false, the XML request gets the time it needs to complete and the onreadystatechange function will be run.
Source: Flask Mailing List
I have now received the good response to this common problem. The response follow:
This is a very common problem when developing for the web. There's two ways around it.
The first is to use JSONP, which our API supports when you add a query parameter ("?callback=foo"). This should get you up and running right away and is great for development, but it isn't secure for production use since users get access to your API key.
The second (which is what we use on Forecast, and is the best method for production) is to set up a proxy server on your own domain which can make requests to Forecast on the user's behalf. This sidesteps the browser's same-origin policy, prevents users from accessing your API key (which can be stored server-side), and also allows you to make use of request caching, if desired. (Our favorite web server, NGINX, supports this out of the box and is really easy to configure. If you need some sample configurations, let us know!)

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);

Categories

Resources