How can I request a url using AJAX - javascript

I am quite new in this area.
I need to find out how to make a request to my solr server using Ajax
How can I give a url(my solr server's url) in request
Any body know how to deal with this?
How can i make a request to the below mentioned url
http://mysite:8080/solr/select/?q=%2A%3A%2A&version=2.2&start=0&rows=100&indent=on
See here: Corrected the Code Snippet as below
function getProductIds() {
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) console.dir(xmlhttp);
else alert('no response');
var ajaxURL = "http://localhost:8080/solr/select/?q=*:*&version=2.2&start=0&rows=100&indent=on";
xmlhttp.open("GET", ajaxURL, true);
xmlhttp.send();
}
This is my code, it always showing "no response"
Thanks.

You will have to prepare the URL before sending in the request first get the URl using javascript and then encode it to ajax format like below
var URL = location.href;
var ajaxURL = encodeURIComponent(URL);
xmlhttp.open("GET",ajaxURL,true);
after reading your question clearly it seemed it is a static URL hence you can do below
var URL = "http://localhost:8080/blah blah blah";
xmlhttp.open("GET",URL,true);
Are you sure it is Get request. because get requests are most of the time cached. also log the response object into Firebug console and inspect the object to know more. Since you get no response that means the server did not send you anything for the request you made.

I'm just now working on XMLHttpRequests to solr as well and I was stuck with what seems like an identical problem. I too am quite new at this. However, the problem for me was that of same origin policy. Firefox seems to give very little feedback when this problem occurs. Chrome at least give you a error message (most of the time?).
In Chrome you can get around this, but only for development purposes, by starting it with the '--disable-web-security' command line option.
I'm yet to find a good workaround for this problem for Solr. In general you avoid the restriction by only using requests with relative paths, but that doesn't seem possible when doing a request to another port.
Ways to circumvent the policy (I haven't had time to study this too much yet)

$.ajax({
url: "url path",
context: document.body
}).done(function(data) {
alert(data);
});
This one also will work.

Related

Is there any way to convert svg url to <svg> tag in javascript? [duplicate]

I'm currently building a site that should be able to function as a ftp sort of browser. Basically what I have is a ftp server with some images on it.
What I can't figure out is: if I browse to this ftp site I can view the source of the ftp site (as seen in some browser), what I need is to save that source in a way to a string (using javascript).
The reason is, that I will make som kind of 'image' browser. I plan on accomplishing that by reading the source into a string, then copy all the image sources and use innerHTML to create a new layout.
In short: I want to read information from a url and display it in a different way.
Well, can't seem to get it working. The problem might be that I cannot use serverside scripting. Would it be possible however to put a file on the ftp server that I can load that can dynamically load the data in the same folder? (when I say FTP I actually mean a NAS server with FTP access).
Your answer is Ajax. It can POST and GET data from an URL, just like browsing a website, and it will return the HTML as a string.
If you plan on using jQuery (real handy), it is easy to use Ajax. Like this example (does not work without the library):
$.ajax({
url : "/mysite/file.html",
success : function(result){
alert(result);
}
});
If you want to use default Javascript, take a look at http://www.w3schools.com/ajax/default.asp
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
IN Javascript to get data without using alert() :
$.ajax({
url : "/mysite/file.html",
async:false, //this is the trick
success : function(result){
//does any action
}
});
Modern Promise-based Fetch API solution (no more XMLHttpRequest or jQuery.ajax()):
fetch('data.txt')
.then(response => response.text())
.then(data => console.log(data));
Example using async/await:
async function myFetch() {
let response = await fetch('data.txt');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
let text = await response.text(); // await ensures variable has fulfilled Promise
console.log(text);
}
There's not much to add to what Niels and rich.okelly have said. AJAX is your way to go.
Keep in mind though, that cross-domain restrictions will prohibit you to access data that is not in the same domain. You'll find a possible workaround here.

Security of GET vs. POST when using Ajax

I used ajax to send the data. I was successful in implementing it using two different approaches:
1) Using method 'POST' and sending data in send() method by setting requestheader.
var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send("userName=xyz&password=abc");
2) Using method "POST" and appending parameter values in the URL as:
var xmlHttp = getXMLHttpRequest();
var url="login.do?userName=xyz&password=abc";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send();
Since this is an ajax call, URL will not be visible in the browser window, so I wanted to know which approach is better and why?
Thanks in advance
Here is W3 recommendation for you.
That pretty much says what exactly you need to do.
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead.
Though it is saying post, internal meaning of it is to keep the URL clean.
Apart from the given two ways, if I were you, I prefer clean codes (imagine 10 query param).
var data = new FormData();
data.append('userName', 'xyz');
data.append('password', 'abc');
var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send(data);
Putting data into the URL's query parameters doesn't make it a GET request. A POST request is a POST request; the difference is between sending data in the URL or sending it as POST body. There's no fundamental difference between both in this case, the data is equally (non) visible for anyone who cares to look.
The only arguable difference in security is that the URL will likely be logged by the server and/or proxies, while body data usually isn't. But then again, you're already sending the data to the server you presumably trust, so even that doesn't make much of a difference. And the server(s) could be logging the body as well if they wanted to.
Semantically I'd send the data in the POST body, but that's not because of security.

Parse Error from JS AJAX requests only on live server - Python GAE

I have a number of AJAX requests (made with regular JS) that seem to be causing trouble when they make requests of my Python GAE back end. Here's an example:
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.send(JSON.stringify(requestOjb));
},
I am getting a code 400 with a Parse Error, but only on my deployed server. Everything works fine on the dev server. The error says the problem is with my back-end function "new_game", but does not specify a line where the error occurred. The endpoint function works correctly when I access it directly from the API explorer, so I figure the problem must be a result of the data sent from my JS file. Here's that function anyway:
#endpoints.method(request_message=NEW_GAME_REQUEST,
response_message=GameForm,
path='game',
name='new_game',
http_method='POST')
def new_game(self, request):
"""Creates new game"""
user = User.query(User.name == request.user_name).get()
# ... removed unnecessary code for this question
return game.to_form('Good luck playing Battleship!')
The request message it's expecting takes the form of {'user_name': 'some_name'} and it appears, through console.log, that JS is sending it in the right format.
The log where the parse error comes up is interesting, because it shows a 200 code POST request, although it mentions the 400 error when I dive into that log.
I've double and triple checked that my code works on the dev server, and that I've got the exact same code deployed. I don't know where to look next to continue debugging this thing. Any help is appreciated.
Figured it out. I tried running the AJAX request with jQuery, and got a slightly different error message, which lead me to find that I had to set the request header, because it was causing the server to read the incoming data differently than it should have. The following AJAX request now works perfectly.
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify(requestOjb));
},

javascript xml cross-domain mess - how to go around?

I'm a real noob in js. I've seen a lot of questions about this, but none of them seems got it clear to me. They all falls into json, that is not available.
I'm trying to access a very poorly documented API(it is in portuguese...). It does not support Json nor Jsonp. It is only xml, via SOAP, HTTP GET e HTTP POST. And of course I'm getting:
XMLHttpRequest cannot load
http://www.camara.gov.br/SitCamaraWS/Deputados.asmx/ObterDeputados.
Origin http://kubrusly.com is not allowed by
Access-Control-Allow-Origin.
my code is:
$.ajax({
type: "GET",
url: "http://www.camara.gov.br/SitCamaraWS/Deputados.asmx/ObterDeputados",
dataType: "xml",
success: parseXml
});
When working locally this goes fine, but once uploaded to my server, it won't retrieve nothing...
Curious enough if i try dataType: "jsonp" :P i get an error complaining about unexpected char '<'. And the xml doc is visible in Safari's console. So the data, in xml format, is arriving in browser, it is there, but i can't access it...
So if json is not an option, how can i go to retrieve this data? It is so frustrating.
I pasted the testing code here:
http://jsfiddle.net/HwP2S/1/
#Kevin B
Thanks for your answer. I did a little research on CORS. I got a little confused with that. Is this supposed to happend on the client side? Any way I got an .htaccess from html5 boilerplate, uncommented the
[EDIT] - solved.
Ok, so I get it going, thanks for the help of you guys. I'll let my solution registered here...
I found that CORS stuff is done in the server side, not my case.
I did not try YQL, you know one more variable, syntax... I let this for last, but did not need it.
I managed to set a proxy and go through it, i spend a lot of time before setting the user agent, and that did it. Before that I aways got 403 error...
this page from yahoo, helped my a lot, some good code examples, both js and PHP.
here the code that is working for me:
js:
// Based on script from yahoo's example # http://developer.yahoo.com/javascript/samples/ajax/sample_proxy_ajax.html
// tweaked by vk
// end point without domain...
var endPtpath = '/SitCamaraWS/Deputados.asmx/ObterDeputados?';
// PHP proxy
var proxiedUrl = 'http://kubrusly.com/yxd/php_proxy_simple.php?yws_path=' + encodeURIComponent(endPtpath);
// mind browsers...
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
//overrideMimeType if supported
if ( typeof xmlhttp.overrideMimeType != 'undefined') { xmlhttp.overrideMimeType('text/xml'); }
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Perhaps your browser does not support xmlhttprequests?');
}
// Create an HTTP GET request
xmlhttp.open('GET', proxiedUrl, true);
// Set the callback function
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Output the results
console.log(xmlhttp.responseText);
} else {
// waiting for the call to complete
console.log("waiting...");
}
};
// Make the actual request
xmlhttp.send(null);
PHP
<?php
// PHP Proxy --- only 'GET'
// Based on script from yahoo's example # http://developer.yahoo.com/javascript/samples/proxy/php_proxy_simple.txt
// tweaked by vk
// hostname - just base domain
define ('HOSTNAME', 'http://www.camara.gov.br');
// Get the REST call path from the AJAX application - js;
$path = $_GET['yws_path'];
// assign yo url
$url = HOSTNAME.$path;
//Open the Curl session
$session = curl_init($url);
// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_HTTPGET, true);
//set user agent, that did it!!! copied from browsers...
curl_setopt($session, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36');
// The web service returns XML. Set the Content-Type appropriately
header("Content-Type: text/xml");
//// verbose mode for debuging good tool!
// $fp_err = fopen('verbose_file.txt', 'ab+');
// fwrite($fp_err, date('Y-m-d H:i:s')."\n\n"); //add timestamp to theverbose log
// curl_setopt($session, CURLOPT_VERBOSE, 1);
// curl_setopt($session, CURLOPT_FAILONERROR, true);
// curl_setopt($session, CURLOPT_STDERR, $fp_err);
// Make the call
$xml = curl_exec($session);
// done, shutDown.
curl_close($session);
?>

Coding with XMLHttpRequest for Safari Extension

In my extension, I create Access Level as "All" as well as I add whitelists as http://*/* too for every domain.
And I have following code in my JS file (which run as end script):
var feedbackmsg = "message goes here";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://mysitename.com/feedback.php', true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("html=" + feedbackmsg);
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.getAllResponseHeaders());
if (xmlhttp.status == 200) {
alert("send");
} else {
alert("error");
}
}
}
Whenever I run it, I am getting no header respond in alert box as well as error alert message. How can I resolve the problem?
Whether or not it's an extension, XMLHttpRequest (if injected into a page) isn't allowed to access anything outside the page's current domain, I think. The console just says that the request was cancelled. At least, that was the case for me when I tested it just now. (I didn't have any urls in the whitelist or blacklist when I tested, but the Access option was set to "all".)
You can try going to the same domain as the one you want to "call" with the XHR object in your code, and see if it succeeds then. If it does, you'll know it's because the domain of the page and the XHR request must match.
However, it appears you can do cross-site ajax request from the extension's global page (oddly enough). At least it seemed to work for me just now. That's actually a little scary (I'd prefer it to be more difficult to call up a random server from an extension) but it worked.
Don't know if that helps you out, though.

Categories