I am trying to load an XML file that asks for a username and password.
The code I'm using is as follows that I am trying to send the username and password in the URL:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
The full code of my page looks like this:
<html>
<body>
<textarea id="test1" name="test1" cols="90" rows="30">
XML file will be displayed here
</textarea><br>
<script type="text/javascript">
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("test1").value=xmlhttp.responseText;
} else
{
alert('Panel not communicating.Reason: '+xmlhttp.status);
}
}
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
xmlhttp.send();
</script>
</body>
</html>
Anyone know what I am doing wrong?
First, add this function to create the authorization header contents:
function make_base_auth(user, password)
{
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
Then, call the function and store the return value in a separate variable:
var auth = make_basic_auth('admin', 'admin');
Lastly, pass the value of auth to the XMLHttpRequest object:
xmlhttp.setRequestHeader('Authorization', auth);
xmlhttp.send();
Attribution: http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html
I ended up getting it working by doing the following:
Change:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
To:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false,"username","password");
See this question for a similar scenario. How to use Basic Auth with jQuery and AJAX? Note one answer states that IE does not support credentials in a URL (as you are attempting to do).
Related
I am trying to get a live chat working using PHP and mysql and AJAX. It is almost completely functioning, except I cant seem to figure out how to submit the chat message without reloading a page. I have a page, sendchat.php, that takes input from the previous page and enters the data into a database. I am trying to use a text input field and when the user clicks the enter key, it would execute the PHP page with the details needed to send to sendchat.php without actually loading or refreshing the page. This is what I have so far:
<form id="send-message-area">
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeydown="onChatEnter(this);"></textarea>
</form>
</div>
</td></tr></table>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
function onChatEnter(str) {
if(event.key === 'Enter') {
$.ajax({
type: "GET",
url: "sendchat.php?msg=" + str ,
success : function() {
// here is the code that will run on client side after running clear.php on server
}
});
}
</script>
All it does is try to load the url, but its not trying to find sendchat.php or send the data. Instead it just tries to load a blank page. Where am I going wrong here? Everything seems spelled correctly and case sensitive. I check if the user pressed enter when they press a key. If they did, I am loading an AJAX function to execute a PHP page. Yet, it is not doing that. Just for FYI, I do not want a button there to be clicked.
EDIT:
I tried the suggestions below and still nothing. I decided to try a different approach now. Still doesn't work.
<script>
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","sendchat.php?msg="+str,true);
xmlhttp.send();
}
}
</script>
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeypress="updatechat(this.value);"></input>
Try this:
$("#send-message-area").submit(function(e) {
e.preventDefault();
e.stopPropagation();
});
I am not sure how.. But I fixed it.. I think it had to do with giving the input a name along with the ID. See below:
<script language="javascript" type="text/javascript">
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
var planetloc = document.getElementById("loc").value;
chaturl = "sendchat.php?msg="+str+"&loc="+planetloc;
sendie.value="";
xmlhttp.open("GET",chaturl,true);
xmlhttp.send();
}
}
//-->
</script>
This was the code I used for the html:
<p>Your message: </p>
<input type='text' id='sendie' name='sendie' maxlength = '100' onkeypress='updatechat(this.value);'></input>
<input type='hidden' id='loc' name='loc' value='$chatroom'></input>";
I also added chaturl to combine the ajax page I needed along with the parameters passed to it. It seemed by creating a variable for that it solved other issues too.
So I'm trying to build a pretty simple website, to learn basic webdesign. It's just a random quote generator - you click on a button and it prints some famous quote. Anyway, I try to use ajax to get the quote, so I use this function:
function loadXMLDoc()
{
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("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
but no matter what I type into RandomQuote.php, even if it's something like :
<?php
echo 'Hello, world';
?>
nothing shows up in the quote "div', it just becomes blank. I really have no idea what's the problem here. Thanks for the help!
Well, I'm not sure about much, but are you calling your function? You put your ajax inside loadXMLDoc() , so you probably have to call it. Another way is to put your ajax into an addEventListener so when a user clicks on something, it'll execute. If that's not the problem, try making sure your element in your html page with the id of "quote" is spelled correctly. Sometimes the latter scenario is always the problem for me.
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
console.log( "Load was performed." );
});
Don't forget to include jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
This is my ajax function, try to use it:
/**
* #function ajax Send ajax-request with post
* #param {string} xmlpage Target url
* #param {string} data Post parameters (like param1=val1¶m2=val2...)
* #param {Function} callback
* #return {null}
*/
function ajax(xmlpage, data, callback)
{
var xmlh = null;
if(window.XMLHttpRequest)
xmlh = new XMLHttpRequest();
else
try
{
xmlh = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex)
{
xmlh = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlh)
{
xmlh.open("post", xmlpage, true);
xmlh.onreadystatechange = function(x)
{
if(xmlh.readyState==4 && typeof callback !== 'undefined')
callback(xmlh.responseText);
}
xmlh.setRequestHeader("Accept-Language","ru, en");
xmlh.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlh.send(data);
}
}
Following test files using your code from the question. It is working perfectly. Either you are missing something or its a browser issue. I tested on Mozilla. To be sure of browser independent code use jQuery for Ajax call
test.html
<html>
<script>
function loadXMLDoc()
{
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("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
RandomQuote.php
<?php
echo 'hi';
Update: jQuery version
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function loadXMLDoc()
{
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
});
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
Here is my code it will send get request and renders some content of the response in html.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mytitle</title>
</head>
<body>
<script type="text/javascript">
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.send();
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
</script>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
<div id="placeholder"></div>
</body>
</html>
this code is working perfectly when i run in eclipse browser. but its failing in Browser.
I have checked browser configuration for script enabling and its enabled. and also no issue with browser configuration.
Im new to javascript http requests.
Please suggest
I read somewhere that the Eclipse browser doesn't adhere to the same origin policy [Wikipedia]. That's why it is possible to make an Ajax request to an external URL, something that is not possible by default in a "normal" browser.
And indeed if I try to run your code [jsFiddle], I get the following error:
XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
There are multiple ways to work around the same-origin policy [SO]. In your case it seems that the service supports JSONP [SO].
With JSONP, your not making an Ajax call to the server, but instead you are using the URL with a dynamically created script element. Script elements are not restricted by the same-origin policy and therefore can load data (code) from other servers.
The server will return a JavaScript file which contains a single function call. The name of the function is specified by you via a query parameter. So, if the JSON response is usually:
{"message":"accurate","cod":"200", ...}
by adding the argument callback=foo to the URL, the server returns
foo({"message":"accurate","cod":"200", ...});
(follow this URL to see an example for your service)
This response can be evaluated as JavaScript. Note that you can not turn every JSON response into JSONP. JSONP must be supported by the server.
Here is a complete example:
// this function must be global since the script is executed in global scope
function processResponse(obj1) {
document.getElementById("placeholder").innerHTML =
obj1.message + " " + obj1.list[0].name;
}
function httpGet() {
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
// the following line is just to explictly show the `callback` parameter
url += '&callback=processResponse';
// ^^^^^^^^^^^^^^^ name of our function
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
DEMO
If you google for JSONP, you will find more information [Wikipedia] and tutorials.
I think ur xmlhttprequest instance is not getting created. It is some time browser dependent try this..
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)
{ your code }
In addition to needing a cross browser xmlhttpquest (which for that alone I'd use jQuery), you also need to wait for the document ready before accessing the city by id... that is, move your script block after your city definition (and I think you may need a form, depending on browser).
Perhaps something like this
<body>
<form>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
</form>
<script type="text/javascript">
function httpGet() {
if (typeof (document.getElementById("city")) == 'undefined') {
alert("Maybe console.log our alarm... but the sky appears to be falling.");
}
var xmlHttp = null;
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) {
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
}
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp.open("GET", url, false);
xmlHttp.send();
}
</script>
<div id="placeholder"></div>
</body>
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.onreadystatechange = function(){
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
xmlHttp.send();
}
I'm trying to use Ajax to tell me whether my server is up or not. I've made a simple page with just one Ajax call. When the server is up, it comes back with the xmlhttp.responseText. IF the server is down it is supposed to say "SERVER DOWN"...but when I load the page, then turn off Apache, it still says that the server is up. Is there some other way I should be doing this?
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
var url = "http://192.168.0.5/ajax_info.txt";
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc(url,function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else
{
document.getElementById("myDiv").innerHTML = "Server Down!";
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
Thanks for the help
Your page is probably cached, use a cache buster in the url. e.g.
xmlhttp.open("GET",url+'?_dc='+(new Date()).getTime(),true);
Hi i tried to call a rest webservice from ajax get request.
Following is the code i tried for that.
function callRestService(){
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");
}
$.ajax({
xmlhttp.open("GET","http://mywebservice/test/",false);
xmlhttp.send();
alert(xmlhttp.responseText);
});
}
And following error am getting while running this code/
missing : after property id
[Break On This Error]
xmlhttp.open("GET","http://mywebservice/test..
/AjaxC...ervice/ (line 30, col 13)
In the first case i tried something like following
$.ajax({
type: "GET",
url: "http://mywebservice/test/",
cache: false,
success: function(data){
alert(data);
//var obj = eval(data);
},
error: function (msg, url, line) {
alert('error trapped in error: function(msg, url, line)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
and in the above case control comes into the error block, but i didn't get what's the reason for that .and that's why i tried the first case.
Is there any problem with this code..??Can anyone help in this.?
Your code is all wrong.
Assuming that$.ajax is jQuery ajax call, then Your code should look like this:
function CallRestService() {
$.ajax({url:'http://mywebservice/test'}).done(function(data) {
alert(data);
})
);
}
You don't need to create xml http request if you're using jquery ajax call.
See this: http://api.jquery.com/jQuery.ajax
for reference.
If you don't want to use jQuery:
function callRestService(){
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.open("GET","http://mywebservice/test/",false);
xmlhttp.send();
if (xmlhttp.status == "200") {
alert(xmlhttp.responseText);
}
}
Reference here: Using XMLHttpRequest
If you are using cross domain calls, see here:
jQuery AJAX cross domain