How do I send user to a link upon successful xhr POST? - javascript

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

Related

How to get text data from webpage

I am trying to get data form a website about institution using XMLHttpRequest but rather than data I am getting error page please help
My code:-
var url = '[https://tsecet.nic.in/institute_details.aspx?iCode=JNTH][3]';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.write( this.responseText);
}
}
xhttp.open("GET", url , true);
xhttp.send();
Target Web Page Address:-
https://tsecet.nic.in/institute_details.aspx?iCode=JNTH
If I try to open
https://tsecet.nic.in/Default.aspx>>then click on >>
institute profile >> then click on>>JNTH
Then I am able to get data in browser Else I am redirected to an error page
Please help me...
Note
I am trying to get this data from a different website and a different
domain This website is scripted in aspx
The AJAX request you're trying to run can't do that, as the pages have the X-XSS-Protection: 1 header, blocking such requests. It looks as if they allow the internals URIs to launch only within a "frame" set by the homepage. Unfortunately, I can't tell for sure. In short, you are going to need another approach.

Trying to build query string and scrape Google results

I'm trying to build a Google query string, make a request to that page, scrape the HTML, and parse it in a Chrome extension, which is JavaScript. So I have the following code:
var url = "https://www.google.com/search?#q=" + artist + "+" + title;
searchGoogleSampleInformation(url);
function searchGoogleSampleInformation(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
return parseGoogleInformation(xhr.responseText, url);
}
}
xhr.send();
}
function parseGoogleInformation(search_results, url)
{
var link = $(".srg li.g:eq(0) .r a", search_results).attr('href');
}
The parse method just grabs the url of the first search result (which is not want I'll end up doing, but just to test that the HTTP Request was working). But link is undefined after that line. Then I used alert(url) and verified that my query string was being built correctly; I copied it from the alert window and pasted into another tab, and it pulled up the results as expected. Then I opened a new window with search_results, and it appeared to be Google's regular homepage with no search at all. I thought that problem might be occurring because of the asynchrony of the xhr.open call, but flipping that didn't help either. Am I missing something obvious?
It's because "https://www.google.com/search?#q=" + artist + "+" + title initially has no search results in the content. Google renders the page initially with no results and then dynamically loads the results via JavaScript. Since you are just fetching the HTML of the page and processing it the JavaScript in the HTML never gets executed.
You are making a cross domain Ajax call, which is not allowed by default. You cannot make a cross domain call unless the server supports it and you pass the appropriate headers.
However, as you mentioned you are building a Chrome extension, it is possible by adding a few fields in the manifest file: https://developer.chrome.com/extensions/xhr#requesting-permission

cannot manipulate response from xmlHttpRequest 2

I'm using XHR 2 to upload/save files.
According to the response of the server I want to perform an action. For example if the responce is "Saved" I want to hide a div or if the response is "Not Saved" I want to show another div etc...
I implemented what appears to be a simple code that should be working , but is not
Here is the snippet of the XHR
//initialize
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr.responseType="text";
xhr.onload = function() {
//if all ok....
if (xhr.status === 200)
{
//update html5 progress bar
progress.value = progress.innerHTML = 100;
//get the respnse
var data=xhr.response;
//convert it to sting - kind of overkill, I know, but I'm stack
var data2=data.toString();
//alert it -- works
alert('data2 '+data2);
//now, do something, according to the response -- NOT working, never alert anything
if (data2=="Not Saved"){alert('Ooops, not saved');}
if(data2=="Saved"){alert('It's all good');}
if(data2=="File too big"){alert('hey, you are watching Jake and Amir');}
document.getElementById('imagesaved').innerHTML=data;
}
//refers to if (xhr.status === 200)
else {document.getElementById("imagesaved").innerHTML="Connect to server failed";}
What is wrong here? This should be working right? Any suggestions?
Thanks
EDIT
I put the alerts for testing. What I actually want to do is call some functions.
If I put
if (data2=="Not Saved"){functionOne();}
if(data2=="Saved"){functionTwo();}
if(data2=="File too big"){functionThree();}
the functions never get called
if I put
if (data2!="Not Saved"){functionOne();}
if(data2!="Saved"){functionTwo();}
if(data2!="File too big"){functionThree();}
ALL the functions are called!!!
I still dont get it...Maybe its something with the response? Or the onload function?
Thanks again
What I finally did is make the server response with numbers, not text. So encoding does not matter any more...
This is the code
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200)
{
var data=xhr.response;
if(data==1)
//say to the user is saved
{document.getElementById('imagesaved').innerHTML="Saved";}
//say to the user, there was an error
else{document.getElementById('imagesaved').innerHTML="Error";}
}
//say to the user that connection to the server failed
else {document.getElementById("imagesaved").innerHTML="Cannot connect";}
};
xhr.open('POST', 'upload.php');
xhr.send(formData);
This is a workaround. I dont know if its the right way to solve this problem , technically. I decided to post it anyway, to help others to quickly solve similar problems. If anyboy else has a better way to suggest , please do.
In this line : if(data2=="Saved"){alert('It's all good');}, you have to escape " ' ".
So convert it to : if(data2=="Saved"){alert('It\'s all good');}
Are you sure that the response of your ajax is text/plain ?
Look on the console (ctrl+shift+i on chrome, F12 on firefox), on net or network tab.
Look on console tab if you got some javascript errors too.

problem in refreshing the page after making two ajax calls

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;

Ajax call from Bookmarklet

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.

Categories