Problem I am making ajax call to server1 i.e. csce and once I got the response I am sending the response as contents to server2 i.e.yahoo server after getting response from there I want to refresh the page or atleast redirect it to the same page. Both ajax calls are working fine. The contents I am sending are also saved the only problem is that I have to manually refresh the page to see the changes. I want to refresh the page once the contents are saved on yahoo. I tried reload and redirect commands in success function of yahoo. But nothing works. I can see the both ajax calls in the HTTPfox but not the redirect.
The url from which i am making calls is different from the url where contents are saved thats why I need to refresh the page to see the changes. i.e. I am saving in yahoo/save while sending contents and seeing changes at yahoo/edit.
I am not sure where I am going wrong. Here is my code I am using. Can anyone suggest where I am going wrong. If my problem is not clear kindly do ask me to clarify more. Thanks.
This code is the code:
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
var substring=xmlHttp.responseText;
alert(substring);// I am able to see the text which is returned by the server1 i.e csce
var handleSuccess = function(o)
{
if(o.responseText !== undefined)
{
console.log(o.responseText);
**window.location.reload()** // also I tried to redirect it to the same site but that also not works
}
};
var callback ={ success:handleSuccess, failure: function(x) {
console.error(x) }, argument: ['foo','bar']};
var request = YAHOO.util.Connect.asyncRequest('POST','http://yahoo.com******', callback, substring);
}
}
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://cse*****id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
Do you just want to display the content in your page? Why don't you try something along the lines of document.getElementById('divID').innerHTML = xmlHttp.responseText;?
With divID being the id of a div that you want to fill the content with.
try following in the handleRequestStateChange function
window.location.href = window.location.href;
Related
I have a working web page, complete with a JavaScript function that displays text messages based on the "non-successful" results, within the same page. Everything is working except this last step.
I need to send a JSON string to my server in a POST, and regardless of outcome, I need the user's browser to navigate to the page returned in the POST. (Just as if it were an ordinary link ( href ="" type of thing.) I am using the custom tag [OK_RESULT_URL] that my server replaces with the real URL just before the page is downloaded.
You see in my code below, that I set the URL to [OK_RESULT_URL] AND the window.location to [OK_RESULT_URL] as well, which seems wrong. That means I'm making two hits to [OK_RESULT_URL], one is a POST with a body (which is correct) and the other one a GET without a body (which is wrong).
I'm a total newbie to JavaScript, so I'm probably missing something obvious. It's as if instead of using xhr.Send() I want to say xhr.SendAndNaviateTo() ... or something like that.
Thanks for any help you can provide.
onApproval: function (response) {
showResult("Approved", JSON.stringify(response, null, ''\t''));
let xhr = new XMLHttpRequest();
let url = "[OK_RESULT_URL]";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200){
window.location = "[OK_RESULT_URL]"};
var data = JSON.stringify(response);
xhr.send(data);
}
after get request arrive the values are there and the button disappear
this is the button working on the localhost..
Im trying to add a Facebook share button in a page with dynamic contents like userid, coming from a esp826 server, using java script like innerhtml by ajax call get request once of json when the page body is on-load. When i test in my local host everything is ok since the json file load very fast and before the button loads and so everything works ok. but when i use the esp8266 server the response of the get request come somewhat after the button is loaded and so when it received and the fields get populated with the values the button disappear and remain only a word with a link.
basically the button is working on my localhost... so the innerhtml and everything is ok.. it seems i need to find a way to reload the css or something by the javascript to get the button box alive again.
is there a way to reload the button?
the .json file is just this: getajx.json
{"temp1":"1", "energia":"2", "energiatotal":"3", "tem":"2", "cliente":"22", "usuario":"22"}
you can test on your localhost by placing this getajx.json file having that content in the same directory of the html page is going to work... but i need to know how to make it work if the get request get too long.. please any help???
i tried to add a flag after the response is positive and activate the reloadCss funtion with it but didnt worked
<script>
var temp1, energia, energiatotal, tem, cliente, usuario ;
var ok=0;
function GetAjx() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
ok = 1;
var myObj = JSON.parse(this.responseText);
document.getElementById("temp1").innerHTML = myObj.temp1;
document.getElementById("energiatotal").innerHTML = myObj.energiatotal;
document.getElementById("tem").innerHTML = myObj.tem;
}};
if (ok =1) { function reloadCss(){
var links = document.getElementsByTagName("link");
for (var cl in links){
var link = links[cl];
if (link.rel === "stylesheet")
link.href += "";
}}
};
xmlhttp.open("GET", "getajx.json" , true);
xmlhttp.send();
}
</script>
I found a solution...
apparently i had to change the order of the scripts making the jquery ajax source load first and also tried to put the script from facebook at the bottom of the page...
i took away the reload scripts and other facebook scripts i was testing
and most importantly made the get request false to make it sync instead of async this forces the page to wait for the get request finish..strangely i tried it before and didnt worked this solution perhaps because of the order of the scripts.. can anyone comment on that?
xmlhttp.open("GET", "getajx.json" , false);
was helpful using the f12 on google chrome in specific the performance tab
i decided to not mess up with priority of the scripts even if i tried
any comments i would appreciate
again
thanks for the help
I login into my website (running on localhost), and store the user id in a session variable
$_SESSION['user_id'] = $user_id;
The main page loads, and all is fine. I show the user id on the main page, so I'm sure of its value. When I load another page, using
php = 'some_php_file.php';
window.open(php,php);
The second page opens ok. But if I try to open the same page again, clicking on the same button on the main page, the system will logout. If I omit the second php in window.open() (using '' instead), I may have multiple copies of the same window (what I don't want), but no problem of automatic logout.
Any idea what may be happening?
EDIT: If I close the second window and repeat the process, I have no logout problem. I can close and reopen the second window as many times as I wish. The problem only happens if I try to open the second window, but it is already open. I can also open different 'second windows' (different php files). I'm only getting logged off if I try to open TWICE the same window.
EDIT 2: Seems I've found it. Before I call window.open(), I'm testing for the existence of the php file, using this function:
function fileExists(url){
var http = new XMLHttpRequest();
http.open('HEAD',url,true);
http.send();
return http.status != 404;
}
If I change the http.open() line to
http.open('HEAD',url,false);
it works! But the manual tells us to use 'true' in the third parameter... What should I do?
It seems to me that your fileExists function simply returns true all the time because it does not wait for the XHR to complete. Except when you specify async = false.
Time to read How to return the response from an asynchronous call? probably.
I have no clue what is the consequence of this always being true, as you do not share exactly what you do with that result.
Now if you want to "stick with the manual" and keep async = true (you should really indeed), then simply wrap your following code in a callback. E.g.:
function fileExistsAsync(url, callback){
var http = new XMLHttpRequest();
http.open('HEAD',url,true);
http.send();
http.onreadystatechange = function () {
if (http.readyState === 4) {
callback(http.status != 404);
}
}
}
fileExistsAsync(url, function (exists) {
console.log("async " + exists);
});
Demo: http://jsfiddle.net/52xqLfow/
I am trying to create a temporary image url for a local image and send it to Google to do a Search by Image. I don't want the image url to be permanent so I want to delete it right after I use it. I have the code below:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(); // asynchronous call to server to delete the URL
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ xml.responseText; // the image url
}
}
xml.open("GET", "REST_ENDPOINT", true);
xml.send();
}
The function above calls the server, and when it finishes, will delete the url and redirect the page. The function "deleteImageURL()" is another ajax call done asynchronously. Currently, this loads the google page fine as the image URL is not done deleting the url by the time that the redirect happens.
My question is this: Will deleteImageURL() finish deleting the image URL even after the page redirects or will it stop (and thus, never delete the URL)?
EDIT: So I was thinking about what you guys were saying about race conditions and tried the following code instead:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(xml.responseText);
}
}
xml.open("GET", "REST_ENDPOINT"
+ id + "/public_url", true);
xml.send();
}
// Deletes the url for the image.
function deleteImageURL(imageURL) {
var xml = new XMLHttpRequest();
xml.open("GET", "REST_ENDPOINT_FOR_DELETE", true);
xml.send();
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ imageURL;
}
This code works every time that I run it. I think that there still may be a race condition, but it seems to be working fine so far.
Thanks again.
The "deleteImageURL()" will finish deleting the image URL even after the page redirects..
Refer : Should I wait for ajax to complete to redirect a page?
The server won't stop processing the request (initiated by deleteImageUrl), but you will not be able to handle a callback if the current page unloads in the browser before the operation is completed.
If deleteImageURL(); contains an async call you should do the redirect when the call is completed. Your code will work when the call is synchronious. We don't see the source of deleteImageURL(); and can be more concrete, but you should do the same thing as you've done for getImageURL().
I am trying to create a bookmarklet that, upon clicking, would request some information from the user (a url and a couple other fields in this case) and then send that data to a php page on my server and then display the result.
I would like to do an Ajax call for this so that I don't actually redirect to the new page, just get the data but I assume I would run into the "Same Origin Policy" limitation of Ajax.... is there any known way of basically doing the same thing?
Also, what would be the best way to pass the parameters? I already have a mechanism in place to recieve the parameters as a post message from a form...is there any way I could just reuse this?
You can set a bookmarklet by create a bookmark and add that piece of code below in location, but, according to same origin policy limitation, that will only work when the current tab is on the same location, here www.google.com.
If I've understand well your needs, that should be ok for your problem.
var request = new XMLHttpRequest();
request.open("GET", "http://www.google.com", true);
request.onreadystatechange = function() {
var done = 4, ok = 200;
if (request.readyState == done && request.status == ok) {
if (request.responseText) {
alert(request.responseText);
}
}
};
request.send(null);
I don't know if POST would work.
You won't be able to do a post, but a GET will work fine. If you're using something like jQuery, it will simply create a script tag with a src URL which would send the data you are looking to submit.
You will have to return JSON style data.
See: http://docs.jquery.com/Ajax/jQuery.getJSON
Alternatively, your bookmarklet could create an iframe on the page, and that could do you work of submitting the data (you could use post then) if you weren't looking to communicate between the iframe and the page itself, but instead just use user input to submit.