Ajax POST request does not work - javascript

I don't know what I am doing wrong, but all looks good. I am working on localhost and I am having trouble trying to load a file.
This is my code. I am working in NetBeans and console is clear without any errors.
<!DOCTYPE html>
<html>
<head>
<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("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_post.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
When I execute this code, I get no results.

In between your .open() and .send() invocations, set your request header like so:
xmlhttp.open("POST", "demo_post.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
At least, that's how you'd do it if you didn't want to use jQuery.

As some of the comments suggest - you need to look in the error console of the Browser. NOT NETBEANS. Also, understand how to set breakpoints in JS, etc.
Below is an example of what you are trying to achieve using jQuery which is much simple than using pure Javascript.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
// jQuery allows you to use selectors rather than onClick, etc
// So when anything with a class called "loadData" is clicked this function will run
$(".loadData").click(function (event) {
$.ajax({
url: 'demo_post.php', // The URL that your making the request to
type: 'POST', // Type - GET or POST
dataType: 'html', // DataType - can be html, json or jsonp
cache: false, // true or false - whether you want data to be cached
data: 'foo=bar', // Any data that your submitting with the request.
error: function (error_response) {
// An error has occured so empty your #myDiv and put the error in there.
$("#myDiv").empty().append(error_response.status);
},
success: function (response) {
// Everything has worked - empty #myDiv and put the replace with response
$("#myDiv").empty().append(response);
}
});
});
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" class="loadData">Request data</button>
<div id="myDiv"></div>
</body>
</html>
You can find more information on jQuery here: http://api.jquery.com and more specifically on jQuery's AJAX functions here - http://api.jquery.com/jQuery.ajax/

i found that your code is actually designed for GET method.And in this case is not important to use POST instead of get.(because no parameter is passed and also its not a form..) and also agrees to #Jackson
<!DOCTYPE html>
<html>
<head>
<!--you can use online js file but in here i download the js file from code.jquery.com/jquery-2.0.3.min.js and kept it in localhost same folder -->
<script type="text/javascript" src="/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","demo_post.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>

Related

AJAX won't get PHP - echo

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&param2=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>

Ajax won't Display on web page

I am currently trying to use a Ajax in netbeans using JavaScript and PHP file. The following code I should click the button and the contents of the php fill should appear but it doesn't. When I use firebug in firefox the response shows the full php file has returned but will not display on webpage. Why???
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttp() {
var xmlHttp
try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
My PHP file is
<?php
echo "This is a php response to your request!!!!!!";
?>
Apart from the fact that HTML code is barely decent, why not use jQuery?
<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>
<script type="text/javascript">
$("#get").click(function() {
$.get( "ajax.php", function( data ) {
$( "#result" ).html( data );
});
});
</script>
PHP is server side and is not made to be run on the client side. Your response should come from a URL and not the contents of a file. Ensuring that your response contains on HTML and not PHP should lead you to your solution.
Try replacing your PHP file with
<p>This is a php response to your request!!!!!!</p>
If this enables you to show your content, you have your problem and solution.

Javascript innerHTML not working with a servlet response

What is wrong with the following code? I am getting a proper response from the servlet, but for some reason cannot get it inside the div. If necessary, the response is:
lukas requests to be your friend &nbsp <button value="lukas"onclick="accfr(this.value)">Accept request</button>&nbsp<button value="lukas" onclick="decfr(this.value)">Decline</button><br>
Code:
<html>
<head>
<title>Friend panel</title>
</head>
<body>
Your requests:<br><br>
<div id="req"></div>
</body>
<script>
function getreqs(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "/ServletTest/DisplayFrRequests", "false");
xmlhttp.send();
var response = xmlhttp.responseText;
document.getElementById("req").innerHTML=response;
}
//var counter = window.setInterval(function(){getreqs()}, 5000);
getreqs();
function accfr(){ }
function decfr(){ }
</script>
</html>
For an asynchronous call, the parameter true/false should not be in quotes
xmlhttp.open("GET", "/ServletTest/DisplayFrRequests", false);

Cannot get a 'bad response' from Ajax call

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

how to store a xmlhttprequest into a variable

I have a quick question that you brainy guys perhaps have the answer to.
Why does this work
<html>
<head>
<script type="text/javascript">
var xmlhttp;
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("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xlmhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
but if I replace
document.getElementById("myDiv").innerHTML=xlmhttp.responseText;
whit this
var txt=xlmhttp.responseText;
document.getElementById("myDiv").innerHTML=txt;
it don't work anymore, txt is
undefined
. How can I store the xlmhttp.responseText into a string, or into a variable that I can perform a search on? Please give an example on how I can do it. Thanks in advance =)
Might be because you have misspelled variable "xmlhttp" - you have "xlmhttp" in your code.

Categories