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.
Related
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>
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>
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!
i previously asked this question but the example i provided did not provide my real problem.
I want to get the input from a form using a php variable and use it in a javascript function. I do not use javascript directly because the content of the variable in question is obtained from a mysql database and i do not think that there is a way for me to access the database using javascript.
below its the code that i have so far:
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var slon1 = '<?php echo (json_encode($siteLon1)); ?>';
self.alert(slon1);
//some code goes here.
}
</script>
</head>
<body>
<div align="center">
<form method="get">
<label>Choose Site</label>
<select name='ps' id="ps" data-inline="true">
<?php
$use = $fgmembersite->getsites($fgmembersite->UserFullName());
$fields_num = mysql_num_fields($use);
while($row = mysql_fetch_row($use))
{
echo "<option value='".$row[0]."'>".$row[0]."</option>";
}
?>
</select>
<input type="submit" name="submit" value="View">
</form>
</div>
<div id="map-canvas"></div>
</body>
</html>
Suprisingly enough, the result displayed on self.alert(slon1) is null; be it when i just load the page or when choose from the drop down box and click on View. Please someone help me on this.
Thanks.
JSON encoder should quote variable, so using single quotes manually would trigger JavaScript parse error. Check JS console. This should generate valid JS code:
var slon1 = <?php echo (json_encode($siteLon1)); ?>;
I am just started with PHP and have a rather simple problem I can't seem to figure out. I have set up a basic PHP script with will send me the content from my sites contact page. The script itself is fine - and so is the validator. Now what I am trying to achieve is getting a simple popup (similar to an alert function in javascript). Here is my try:
if ($valid) {
//*isUTF8($subject);
//*isUTF8($formcontent);
sendMail();
$body = $successMarkup . $backMarkup;
$title = "Form sent";
#header("location:formsent.php");
} else {
$body = $errorMarkup . $errorMarkupEnd . $backMarkup;
$title = "Form errors";
}
The file formsent.php I am refering to here only includes basic html markup as well as an javascript alert which is executed as soon as you open the page:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Contact Success</title>
</head>
<body>
<script language="Javascript">
<!--
alert ("Thank you for your message! I will come back to you as soon as possible!")
//-->
</script>
</body>
</html>
Here my question:
After I send the filled out contactsheet via the send button I get a popup with the message shown above - BUT to do so it leaves the actual page I am on and shows me only a white screen.
How can I get that popup message implemented without leaving the page I am on?
Try using this one: http://jquery.malsup.com/form/ with jQuery to make an Ajax form submit simple.
The examples, shown on that page are quite enough to implement your type of a story.
just put:
<script>
$(document).ready(function(){
$('form#form_id').ajaxForm(
function(data){
alert(data);
}
)
})
</script>
And so everything you need to do in your sendmail script is to echo the needed message, no redirecting required.
header("Location: <url>") results in a proper redirect. You need to use Ajax here to send the data (when the user submits it), receive the contents of the popup box and then display it.