Jquery with PHP and AJAX page update - javascript

I have a for loop in PHP and an Ajax call in JavaScript with Jquery library. My problem is that i want to update the page after each php loop. Now its waiting 10 seconds and after that, shows me the page. I want to display in real time line after line.
data.php
<?php
for($i=0;$i<10;$i++) {
echo "lorem ipsum" . "<br>";
sleep(1);
}
?>
And the index.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function ajaxCall(){
$.ajax({url:"data.php",success:function(result){
$("#div1").html(result);
}});
}
setTimeout(ajaxCall(), 1000);
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>

You essentially want to perform 10 page updates, each after one second based on each iteration of your loop on the server side php code. I suggest you redesign so that the looping occurs on the client side, and on the server side you simply respond to each request. I think this approach is easy to understand.
The below client side code is not tested and shows the approach (index.php)
//this is called 10 times, with i being the number of the call starting at 1
function ajaxCall(i){
//note the query string parameter being passed to the php script
$.ajax({url:"data.php?i="+i,success:function(result){
$("#div1").html(result);
if(i<10){ //if we have not reached 10 calls, delay and then call again while incrementing the count
setTimeout(ajaxCall(i+1), 1000);
}
}
});
//make the first ajax call
setTimeout(ajaxCall(1), 1000);
In data.php you need to check that query string parameter. Note there is no loop and no sleeping in your server side code any more.
<?php
$i = $_GET["i"];
//do something with $i which should be in the range 1-10 (you should check this)
echo "lorem ipsum " . $i . "<br>";
?>

In your data.php, there is no need for sleep and for loop. The loop will be done in Javascript (with setTimeout).
So data.php can look something like:
<?php
echo "lorem ipsum" . "<br>";
?>
And your index.php should append the data:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function ajaxCall(){
$.ajax({url:"data.php",success:function(result){
$("#div1").append(result);
}});
}
setTimeout(ajaxCall, 1000);
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>

Related

Trying to get data on a webpage through php and ajax

This might go very basic, but I am not able to understand what is the best way to call AJAX on a button click event on page and get the data from the server to be displayed using php.
What I have is a simple webpage called div.php:
<html>
<head>
<title>
Test
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js">
$(document).ready(function(){
$('#btn').click(function(){
$("#data").html('Loading...');
$.ajax({
url:'test.php',
type:'GET',
success:function(data){
$("#data").html(data);
}
});
});
});
</script>
</head>
<body>
<form method="get">
<button id="btn">
Get Data from PHP file
</button>
<div id="data">
</div>
</form>
</body>
</html>
And then a page behind it doing the database operation, test.php:
<?php
include ("config.php");
$sql = "SELECT * FROM userInfo;";
$result = mysql_query($sql);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$count = mysql_num_rows($result);
if ($count > 0) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["userLogin"] . "<br>";
}
}
?>
It is pretty basic and I am supposed to get the query result on the button click, but it doesn't work. Is there something wrong in here?
Any help or ideas to understand PHP to AJAX to JS flow will be really appreciated.
You need to embed the JS separately, you can't do what you've done but need to split as below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btn').click(function(){
... etc
});
});
</script>
This is difficult to debug based on the limited info available, although I think this may be the issue. Your <button> element is inside a <form> element. This means that when you click the button, it is submitting the form and reloading the page. Your AJAX may have worked but the page has reloaded so you won't see the data. Solution:
Either remove your <form> from the page or look into e.preventDefault() for the button click function in jquery.
On another note, you should migrate your code to using another library such as PDO for accessing databases as the mysql_* functions should no longer be used.

Hide output from echo json_encode

I was passing an array in php to Javascript using json_encode and ajax. It seems that the only way is to use
echo json_encode($var)
which also prints out the information of $var on the page because of echo. Is there an easy way to hide the output? My code was like the follows,
main.php
<?php
include_once('testing.php');
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="testing.js"></script>
</body>
<html>
testing.php
<?php
$var=array('1','2','3','4','5');
echo json_encode($var);
?>
testing.js
$.ajax({
url : './testing.php',
type : "GET",
dataType : 'json',
success : function (result) {
showstaff(result);
}
});
function showstaff(x){
console.log(x);
}
Running main.php print out the array('1','2','3','4','5') on the page and show the array in the console, but what I need is to just show the array in the console (i.e. hide the results from the page).
You don't need include_once('testing.php') in main.php. When main.php is sent to the browser, it will load testing.js, which will then execute testing.php via the AJAX call.
You can try this:
<script type="text/javascript">
var object = <?php echo json_encode($var); ?>;
</script>
Hope it helps, thanks!

Error while using valiable in Jquery.val() funciton

I got no output when I use variable in val() function instead of fixed value. How can I fix this error.
Example: In the below example, when I use variable ($data="Glenn Quagmire"), I get no output.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
<?php $data="Glenn Quagmire"; ?>
$("input:text").val($data);
});
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>
</body>
</html>
Regards
Just use like this:
$("input:text").val("<?php echo $data; ?>");
Full code
<script>
$(document).ready(function(){
$("button").click(function(){
<?php $data="Glenn Quagmire"; ?>
$("input:text").val("<?php echo $data; ?>");
});
});
</script>
Don't use "$" for variables (that's PHP) in jQuery.
<?php echo 'data="Glenn Quagmire";'; ?>
$("input:text").val(data);
JavaScript running in the browser cannot access variables from a PHP program (which has finished running on another computer before delivering the page to the browser so the variable does't even exist any more).
You have to make PHP output the data to the JavaScript.
You can encode it using json_encode (because JSON is (more or less) a subset of JavaScript literal syntax). This will add quotes as needed and escape any special characters in your data (you don't have any in your example, but this is a safe, general approach that protects you from XSS).
$("input:text").val(<?php echo json_encode($data); ?>);
Use <?= $variable ?> to embed variable values in HTML, e.g.:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
<?php $data="Glenn Quagmire"; ?>
$("input:text").val("<?= $data ?>");
});
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>
</body>
</html>

PHP code will not execute in script tags

I can put php code anywhere in my php file, but if i put the php code within the tags it simply will not work.... What am I doing wrong?
<html>
<head>
<?php
$hello3 = 'hello3';
echo 'hello1';
?>
<script>
<?php echo 'hello2'; ?>
$(document).ready(function(){
$("#target").click(function(){
alert('hello');
});
});
</script>
<?php echo $hello3; ?>
</head>
<body>
<button type="button" id="target">Press Me</button>
</body>
</html>
when I execute this page I get this displayed on my screen:
hello1hello3 (then the button)
the echo within the script tags will not execute... at all.
This is the HTML equivalent of your code:
<html>
<head>
hello1
<script>
hello2
$(document).ready(function(){
$("#target").click(function(){
alert('hello');
});
});
</script>
hello3
</head>
<body>
<button type="button" id="target">Press Me</button>
</body>
</html>
What's wrong with your output?
The output of your PHP, within the script element, looks like this:
hello2 $(document).ready(function(){
$("#target").click(function(){
alert('hello');
});
});
It immediately falls over (with a reference error) because you try to use the variable hello2 without declaring it.
Were that not the cause, it would then fall over because you try to use the variable $ without declaring it (i.e. by including jQuery in your script).
The PHP is executing fine. You are just writing PHP that generates completely broken JavaScript.
Yes this does execute. But items in the <script> tag are not displayed on the screen unless done so by a function or method. You just have items like hello2; in JavaScript. For example what would you expect so see if you had this:
<script>
hello1;
</script>
Well, nothing would be on the screen. You are just creating global variables, which are not defined, so what would happen? Try adding some code for example a simple alert:
<script>
<?php echo 'alert("hello")'; ?>
</script>
When writing PHP the items you echo would be exactly the same as you were writing JavaScript normally. So the same rules for writing JavaScript apply. The above item would look like so after PHP executes:
<script>
alert("hello")
</script>

Changing a web page using JavaScript or PHP

I'm a college business student trying to build a website with a business model.
I'm building a website where I want to allow users to signup. Right now I'm using action: signup.php to store the user into the database. After the user is successfully inserted, I redirect the page back to the index.html where the form was submitted.
My question is, how can I reference JavaScript to change the login from display:block to display:none and sign up confirmation from display:none to display:block through my PHP tag?
I'm currently using $_GET to grab the success/fail status from signup.php and I want to use an IF statement to execute the correct JavaScript code.
UPDATE
I was advised to instead set all div's to block and use a PHP IF statement to display the login or signedup divs. However, after implementing the changes, the index.html still cannot distinguish the success/fail status. Here is my code below:
signup.php:
if (mysqli_num_rows($data) == 0)
{
$qry = "INSERT INTO logins (username, password, email) VALUES ('$username', SHA('$password1'), '$email')";
$result=mysqli_query($dbc, $qry);
if($result)
{
header('Location: index.html?signup=success');
}
}
else
{
header('Location: index.html?signup=fail');
}
index.html: Head
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Site</title>
<link type="text/css" rel="stylesheet" href="home.css">
<script type="text/javascript">...</script>
<?php
if(!empty($_GET['signup']))
{
$signup = $_GET['signup'];
}
?>
</head>
index.html: Body
<body>
<div id="container">
<?php
if(!$signup)
{
?>
<div id="login">...</div>
<?php
}
?>
<?PHP
if($signup)
{
?>
<div id="signedup">...</div>
<?PHP
if($signup == 'success')
{
?>
<div id="confirmation">...</div>
<?php
}
?>
<?PHP
if($signup == 'fail')
{
?>
<div id="failure">...</div>
<?php
}
?>
<?php
}
?>
</div>
</body>
As of now, after the user submits the form they are inserted into the database. The problem is that once they are redirected to the index.html, the php does not recognize the success/fail status and consequently only displays the login form.
That PHP code needs to go in your <head> or <body> section. You have it before <html> right now.
And yeah, onload = function(); should probably be window.onload = function;
This code doesn't do what you think it does:
onload=signedup();
You need to attach to the onload handler correctly:
window.onload = signedup;
Now, this isn't the best way to do things (it waits for EVERYTHING to be loaded), so if you happen to have jQuery included in your page, it'll be more efficient:
$(function(){ signedup(); });
Also, move the PHP to inside the HEAD tag since it prints out a script - and scripts should generally be in the HEAD tag.
Now, to take a different direction - why don't you just do it with PHP by printing out the HTML only if it's needed:
<?php if(!$signedup) { ?>
<div id="login"> ... </div>
<?php } ?>
This is probably the way to go in this case!

Categories

Resources