So I have this script which posts some text using ajax:
<?php
if (isset($_POST['q'])) {
echo 'q is '.$_POST['q'];
} else {
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","aj.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Accept","text/html");
xmlhttp.send("q=some text");
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState===4&&xmlhttp.status===200)
if (r=xmlhttp.response||xmlhttp.responseText)
document.write(r);
else
alert("no response")
}
</script>
</head>
<body>
body
</body>
</html>
<?php } ?>
The output is suppose to be 'q is some text' but in Google Chrome (Windows) it runs repeatedly and all you see is the word 'body' repeating across the page.
Whats going wrong?
jQuery is the way
$.post('ajax.php','q=some text',function(data){
$(document.body).html(data);
});
Related
I would like to have on my HTML page a simple button allowing me if right clicked one, click activate every time my PHP script.
I tried with this code, without any positive result for the moment:
//My html code
<!DOCTYPE html>
<head>
<title><?php echo $pageTitle; ?></title>
<meta charset="UTF-16" />
<link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
<main>
<button onclick="doTheFunction();">Run the script</button>
<script>
function doTheFunction(){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","script.php",true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
}
}
</script>
</main>
<footer>
<?php echo $footer; ?>
</footer>
</body>
A part of my php code :
echo "$result";
Your code is doing nothing with the result of Ajax. I suggest starting here as a reference. The most important thing you're missing is:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
Where "demo" is the Id of the element you want to load the Ajax result into. Otherwise nothing will happen with that result.
EDIT
Let's clean up your code so scripts and html are separate:
function doTheFunction(){
xmlhttp = new XMLHttpRequest();
//Set this before sending!!
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
}
//No reason to post
xmlhttp.open("GET","theme/generator/gensent.php",true);
xmlhttp.send();
}
<head>
<title><?php echo $pageTitle; ?></title>
<meta charset="UTF-16" />
<link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
<main id="demo">
<button onclick="doTheFunction();">Run the script</button>
</main>
<footer>
<?php echo $footer; ?>
</footer>
</body>
I would put the <script> tag at the end of your html, after closing the body, or include it in the header from another file. Note- I use GET since no sensitive info is transferred, the script should load after the HTML- hence put at the end, and finally you need a tag with the Id for this to actually work.
hello here i have i script but this dont work i caant update chat every second can you help me to update chat every second from database (pleasee no uppate div only text)
index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
setTimeout(
function() {updateChat();},
1000);
function updateChat() {
$.get("read.php", function(data)
{
$("#Show_Data").html(data);
});
}
});
</script>
</head>
<body>
<div id="Show_Data"></div>
</body>
</html>
read.php
<?php
include("config.php");
$Data = "SELECT * FROM chat ORDER BY Time ASC";
$Result = mysqli_query($Connection, $Data);
while($row = mysqli_fetch_array($Result,MYSQLI_ASSOC))
{
echo '</br>' .$row['name'];
}
mysqli_free_result($Result);
mysqli_close($Connection);
?>
this is my code but my code when insert data in database my code not update data in html
Option 1:
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
setTimeout(
function() {updateChat();},
1000);
function updateChat()
{
$.get("read.php")
.done(function(data)
{
//You can do futher checks here....
$("#Show_Data").html(data);
setTimeout(function() {updateChat();},1000);
})
.fail(function()
{
//error 404 or 500
});
}
});
</script>
</head>
<body>
<div id="Show_Data"></div>
</body>
</html>
Int the code above, when something wrong with the call it stops and it does not continues the executions.
Option2:
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
setInterval(
function() {updateChat();},
1000);
function updateChat() {
$.get("read.php", function(data)
{
$("#Show_Data").html(data);
});
}
});
</script>
</head>
<body>
<div id="Show_Data"></div>
</body>
</html>
The code aboce executed every 1000 miliseconds the ajax call regardless if it is sucessfull the call or not
You need to use setInterval instead of setTimeout (it runs only once).
If that doesn't help, please post any PHP/JavaScript errors that you are getting.
To make sure PHP errors are set to display, add error_reporting(E_ALL) to the top of your script.
To see JavaScript errors, open the Developer Tools (F12) in your browser and go to Console.
I thought this would be simple enough, but I can't get it to work.
I have two files. main.html and data.php
The two files are in the same folder on a server.
I want to get a string from the PHP file and use it in jQuery. In the example below, I want the browser to create a pop-up, with the text "xxxx". I get no pop-up.
data.php
<?php
$var = "xxxx";
echo json_encode($var);
?>
main.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts/jquery-1.11.1.js"></script>
<script>
$(document).ready(function() {
var testString = <?php $var = json_decode(file_get_contents('data.php'), true); echo $var; ?>;
alert(testString);
});
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
Any takers?
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function() {
$.ajax({
url:"data.php",
success:function(result){
alert(result);
}
});
});
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
The first problem with this is that on many servers .html is not parsed for PHP
The second problem is that the file_get_contents will actually display the full contents of your .php file (including the <?php) which is likely not what you're looking for.
Instead I would use an AJAX request such as http://api.jquery.com/jquery.get/
For this you will need to include jQuery in your <head>
You should get the php data before html initiates, like below
<?php
$var = json_decode(file_get_contents('data.php'), true);
?>
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function() {
var testString = <?php echo $var; ?>;
alert(testString);
});
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
I just make a simple AJAX application so that my html page can get some data from the php file through the ajax.js file, I have already put them in the server, so when I access localhost/mypage, it should be executed, however it seems there are some problems therefore things do not happen as my expected way.
Here is my html file:
<!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=UTF-8">
<title>
My Portal
</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body onload="load()">
<div id="header">
<img src="images/logo.gif" id="logo" alt="Logo"/>
<a href="http://www.google.com">
<img src="images/logo2.png" id="logo2" align="right" alt="google Ltd"/>
</a>
</div>
<div id="container">
<div id="function"></div>
<div id="Display"></div>
<div id="View"></div>
</div>
<div id="footer">
</div>
</body>
</html>
And below is the js file:
function load(){
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("function").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php", true);
xmlhttp.send();
}
At last is the php file:
<?php
print "<h1>hgfkegfalhgj</h1>";
?>
I expect it should print out the above char string in my page, however, nothing can be shown, can anyone tell me where is the problem? I have checked that I have already enabled javascript in my browser, so I am quite sure my html file can call the function in js file.
I don't know PHP but you must set content type to text/plain . Like :
header('Content-Type: text/plain');
Your code works for me.
The problem can be any of the following:
1) Check the path to test.php (I would suggest using absolute path in xmlhttp.open() )
2) Your server may not be returning the page correctly (Try opening test.php, and check the output)
You can use browser plugins like firebug, to analyze the ajax request and response, it can give you a better insight.
instead of onLoad function in body tag try with
<script>
window.onload = function(){
load();
};
function load(){
//your code
}
</script>
or try with script load() function before body. I think it will solve your problem.
Also Try to change id, preferably keywords should not be used as id (function id change it to something else)
I am trying to get the links that appear after clicking the business name to appear in a light box. on a standalone page, it was possible but as soon as I send the same code through ajax, it does not call the light box anymore. help?
This is the original file, which is supposed to represent a 3rd party publisher site, integrating our code:
<html>
<head>
<script type="text/javascript" src="lib/js/jquery-latest.js"></script>
<link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />
<script src="lib/js/jquery.ppo.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/js/sp.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
This is the publisher's website. <br>
<div id="bizname1" onclick="showComp(this.innerHTML)" id="bizname" class="bizname">click here - this event should be substituted for an 'on load'.</div><br><br>
lots of data about the company here
<br />
<div id="txtHint"><b>Company info will be listed here.</b></div>
</body>
</html>
This is the ajax script, showcomp.js:
function showComp(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getbutton.php?q="+str,true);
xmlhttp.send();
}
This is the getbutton.php file called by the ajax function:
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include('config.php');
init_connection();
$sql=select content from db;// this part works fine, so actual sql query not inserted here.
$result = mysql_query($sql);
while ($row = mysql_fetch_object($result)) {
$companyname = $row->result1;
$contenturl = $row->result2;
//echo $companyname;
//echo $contenturl;
?>
<HTML>
<HEAD>
</HEAD>
<BODY>
<a href="http://www.youtube.com/embed/DudfBIxw6do?iframe=true&width=640&height=390" rel="prettyPhoto" title="my caption"> Video in iframe
<img src="images/thumb-1.jpg" width="100" height="40" alt="Video in iframe" />
</a>
<a href="demo/vidrefer.php?iframe=true&width=500&height=410" rel="prettyPhoto" title="my caption"> Vidrefer in iframe
<img src="images/thumb-1.jpg" width="100" height="40" alt="Vidrefer in iframe" />
</a>
<br />
</BODY>
</HTML>
<?php
}
//echo out button here. give the button what it needs to launch the light box.
echo "
<br>
<div id='button'>
this is a button
</div>
";
//mysql_close($con);
?>
<script id="ppready" type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("a[rel^='prettyPhoto']").prettyPhoto();
});
</script>
Please help if you can see why it is not working! Thank you.
I fixed this! the problem was due to the fact that the javascript already acted before I loaded my new elements via ajax. all I had to do was to load my elements in before the ajax call and hey presto!
An alternative solution would have been to use live() or livequery() in jquery. They would have kept the jquery acting on elements both before and after they loaded into the DOM. Simples.
The JS would not run on the client side, when it is just echo'ed from the server side. Try moving your codeblock
$(document).ready(function(){
$("a[rel^='prettyPhoto']").prettyPhoto();
<-- inside-->
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
To look like :
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
$("a[rel^='prettyPhoto']").prettyPhoto();
}