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.
Related
Okay, so here's my problem.
I have "page1.php", with following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<textarea id="note-textarea"></textarea>
<script>
$( "#note-textarea" ).keyup( function() {
$( "#output_div" ).html( $( this ).val() );
setTimeout(function () {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("XMLHTTP");
}
xmlhttp.open("GET", "/upload-note?note="+$('#note-textarea').val(), true);
xmlhttp.send(null);
}, 1000);
});
</script>
</body>
</html>
And "upload-note.php", which should upload the content of the textarea from "page1.php", to a MySQL database. For demonstration-purpose, let's just say, that it's going to echo the content of the textfield instead.
<?php
echo($_GET['note']);
?>
Now this setup works actually just fine, BUT it's ignoring linebreaks. Any suggestions on how to handle these?
The browser ignores linebreaks (\n) in HTML documents. You have to change them with <br> tags like so..
echo nl2br($_GET['note']);
Change to POST instead of GET
xmlhttp.open("POST", "/upload-note", true);
xmlhttp.send("note="+$('#note-textarea').val());
...
echo nl2br($_POST['note']);
I am having some troubles today. I am trying to get Javascript to load content into a <div>. Now, this is my JavaScript source code:
function loadXMLDoc(filename) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
after_load_function(xmlhttp.responseText);
}
}
xmlhttp.open("GET", filename, true);
xmlhttp.send();
}
function after_load_function(responseText) {
document.getElementById("right").innerHTML = responseText;
}
window.onload = function () {
loadXMLDoc("welcome.html");
}
And my div:
<div id="right"></div>
Does anyone know the problem?
Is there any reason you aren't using an abstraction like the JQuery load method?
$( document ).ready(function() {
$("#right").load( "welcome.html" );
})
looks pretty good to me.
Just had a similar issue, here is what I have and it seems to be working really well,
HTML:
<html>
<head>
<title> pageOne </title>
<script src="jquery-1.11.1.min.js"></script>
</head>
<body>
<input class='loadBtn' type='submit' value='Load a Different Page!:'>
<div id="page"></div>
</body>
</html>
JS:
//click function:
$(".loadBtn").click(function(){
//div to hide/replace
$('#page')
//fadeOut div content:
.delay(200).fadeOut('slow')
//load method:
.load
//url #divToReplace
('pageTwo.php #page')
//fadeIn new div content:
.hide().delay(300).fadeIn('slow');
//prevent default browser behavior
return false;
});
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>
Hi I don't know javascript but I am required to use it in one of my templates. I was googling around and found a solution whic is like this:
My Index.php file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("aside").innerHTML="<img src='loadingImage.gif'>";
if(XMLHttpRequest) var x = new XMLHttpRequest();
else var x = new ActiveXObject("Microsoft.XMLHTTP");
x.open("GET", "other_content_1.php", true);
x.send("");
x.onreadystatechange = function(){
if(x.readyState == 4){
if(x.status==200) document.getElementById("aside").innerHTML = x.responseText;
else document.getElementById("aside").innerHTML = "Error loading document";
}
}
}
</script>
</head>
<body>
<div id="aside">This is aside</div>
</body>
</html>
My other_content_1.php file
<div id='other-content-1'>
<?php echo 'This text is loading via php command'; ?>
</div>
As this is the only Javascript function in my site I see no reason to load additional JQuery for it. I am sure there must be a way to do this with plain JavaScript / ajax without the need to load JQuery. Can anybody suggest the correct syntax to do so?
I want to happen asynchronously while the page continues to load.
from http://www.tutorialspoint.com/ajax/ , using plain XHR (XmlHttpRequest)
function loadPage() {
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "ajax-example.php", true);
ajaxRequest.send(null);
}
loadPage();
Try this:
window.onload = function(){
aside = document.getElementById("aside");
aside.innerHTML="<img src='loadingImage.gif'>";
if(XMLHttpRequest) var x = new XMLHttpRequest();
else var x = new ActiveXObject("Microsoft.XMLHTTP");
x.open("GET", "other_content_1.php", true);
x.send();
x.onreadystatechange = function(){
if(x.readyState == 4){
if(x.status == 200) aside.innerHTML = x.responseText;
else aside.innerHTML = "Error loading document";
}
}
}
And it is cross browser compatible, you never need the extra 32KB just to make a simple function supported cross browser.
Below is my html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
<script type="text/javascript">
function Data_Check()
{
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest(); }
catch (e)
{
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;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
alert(xmlHttp.responseText);
}
}
var RES = document.getElementById("Remarks").innerHTML;
var params ="RES="+RES;
xmlHttp.open("POST","Data_Check.asp",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
</script>
</head>
<body>
<textarea id="Remarks" rows="5" name="Remarks" cols="79" style="font-family: Arial; font-size: 11px">please, accept my submit form.</textarea>
<br>
<img id="Submit" onclick ="return Data_Check();" border="0" src="submit.png" width="145" height="28">
</body>
<img
</html>
Here i facing the problem is,
When i submit "Remarks" textarea innerhtml to my "Data_Check.asp"
<%
RES = Request.Form("RES")
%>
and this remarks save in my sql database.( database field is "Remarks_text" and datatype is "text")
In the data base textarea data is read ("please, accept my submit form.") textarea data with out space.
like this
please,acceptmysubmitform.
I need to save
please, accept my submit form.
hoping your support
Try url encoding:
var RES = encodeURIComponent(document.getElementById("Remarks").value);
Change
document.getElementById("Remarks").innerHTML;
to
document.getElementById("Remarks").value;
I suspect spaces are not supported in URLs or HTTP headers, hence old URLs had %20 instead of a space. Modern browsers and servers now do this behind the scenes.
I found replacing spaces with %20 using formValues = formValues.replace(/ /gi,"%20"); prior to sending solved the problem.
Yes this is fixed!
Example :
var dataString = "textcontent="+test.replace(/ /gi,"%20");