Make div text change on click based on PHP data using Ajax - php

Let's say I have in a PHP file a div called myDiv, an image called myImg, and a PHP variable called $x.
When someone clicks on myImg, I need myDiv's text to change based on the value of $x.
For example, let's say I want myDiv's text to change to "Hello" if $x==1, and to "Bye" if $x==2.
Everytime the text changes, the value of $x will change too, in this case, let's say if $x==1 when myImg is clicked, then $x's value will become 2($x=2), and viceversa.
I'm using jQuery, but I read that I need to use Ajax too for this (To check on the server the value of $x), but I can't figure out how to do it. I read about Ajax, but none of the examples explains something like this.

I'll add the revised solution in a new answer so you can still see the earlier examples as the code may provide useful examples.
In this example, we use a session variable to store the value between ajax calls.
FILE1.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#myImg').click(function() {
$.ajax({
type: "POST",
url: "FILE2.php",
data: '',
success:function(data){
alert(data);
}
});
});
});
</script>
<div id="myDiv">
Click picture below to GO:<br />
<img id="myImg" src="http://www.gravatar.com/avatar/783e6dfea0dcf458037183bdb333918d?s=32&d=identicon&r=PG">
</div>
FILE2.php
<?php
session_start();
if (isset($_SESSION['myNum'])) {
$x = $_SESSION['myNum'];
}else{
//No session set yet, so initialize with x = 1
$x = 1;
}
if ($x == 1) {
$_SESSION['myNum'] = 2;
echo 'Hello its a one';
}else{
$_SESSION['myNum'] = 1;
echo 'Goodbye TWO';
}
?>

You don't need ajax, but you could use it. If you use AJAX, then you'll need a second php file that simply echoes back the Hello or Bye.
This first example gives the result you want without ajax. Just save this into a PHP file and browse to that page:
<?php
$x = 2;
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#myImg').click(function() {
if (<?php echo $x;?> == 1) {
alert ('Hello, its a one');
}else{
alert('Goodbye TWO');
}
});
});
</script>
<div id="myDiv">
Click on the image below:<br />
<img id="myImg" src="http://www.gravatar.com/avatar/783e6dfea0dcf458037183bdb333918d?s=32&d=identicon&r=PG">
</div>
To do the same thing using AJAX, change it to be like this:
First file: FILE1.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#myImg').click(function() {
var theNumber = $('#myInput').val();
$.ajax({
type: "POST",
url: "FILE2.php",
data: 'myNumber=' + theNumber,
success:function(data){
alert(data);
}
});
});
});
</script>
<div id="myDiv">
Enter number to send to FILE2:
<input type="text" id="myInput"><br />
<br />
Click picture below to GO:<br />
<img id="myImg" src="http://www.gravatar.com/avatar/783e6dfea0dcf458037183bdb333918d?s=32&d=identicon&r=PG">
</div>
and FILE2.php
$x = $_POST['myNumber'];
if ($x == 1) {
echo 'Hello its a one';
}else{
echo 'Goodbye TWO';
}

Related

Why is my PHP echo returning a 0 in some places (yet working in others)?

When a form submits, the AJAX code below replaces anything with id = levelreplace with the word in the char column titled level in the MYSQL database. (For reference, the word in this column is "Easy.")
<script type='text/javascript'>
$(document).ready(function () {
$('#form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : "test.php",
type: "POST",
data: $(this).serialize(),
success: function (data) {
$(".levelreplace").text(data.level);
},
});
});
});
</script>
I also have this bit of JQuery which is supposed to take a div with id = classadderpanel and append the class "Easy" (using the AJAX above).
<script type='text/javascript'>
$(document).ready(function () {
$('#classadderpanel').addClass('<?php echo "<span class='levelreplace'>" + $data['level'] + "</span>"; ?>');
});
</script>
However, instead of adding the class "Easy" it adds the class "0". I know that there's nothing wrong with the AJAX returning the correct MYSQL data because, elsewhere, I have the code:
<?php echo "<span class='wordlevelreplace'>" .$data['WordLevel']."</span>"; ?>
...and that successfully echoes the word "Easy."
I'm guessing this has something to do with either my quotes or my concatenation, but I've played around with every iteration that I can think of and the problem does not resolve.
Full code (only with components relevant to the problem):
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
//AJAX to replace everything with id = "levelreplace" with the word in MYSQL column "level"
<script type='text/javascript'>
$(document).ready(function () {
$('#form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : "test.php",
type: "POST",
data: $(this).serialize(),
success: function (data) {
$(".levelreplace").text(data.level);
},
});
});
});
</script>
//Code to add class equal to the word in column titled "level"
<script type='text/javascript'>
$(document).ready(function () {
$('#classadderpanel').addClass('<?php echo "<span class='levelreplace'>" + $data['level'] + "</span>"; ?>'); // Returns 0
});
</script>
</head>
// ECHO SHOWING THAT THE AJAX SOMETIMES RETURN THE WORD "EASY" IN THE COLUMN LEVEL...AND SOMETIMES IT DOESN'T
<?php
echo "<span class='levelreplace'>" .$data['level']."</span>"; //Returns Easy; This is how I want everything with class = "levelrelace" to get replaced
?>
// DIV THAT SHOULD HAVE THE CLASS ADDED
<div id="classadderpanel" style="background-color: orange;">
<form id ="form" class = "classtest" action="aplayground_classadderform.php" method="POST">
<input type="submit" >
</div>
</html>
You are using JS Syntax in your php on this line:
$('#classadderpanel').addClass('<?php echo "<span class='levelreplace'>" + $data['level'] + "</span>"; ?>');
It should be:
$('#classadderpanel').addClass('<?php echo "<span class='levelreplace'>" . $data['level'] . "</span>"; ?>');
The string (produced by PHP) <span class='levelreplace'>Easy</span> just cannot be a valid class to add to the element $('#classadderpanel').
This method expects a string, not an element.
I can't say where the zero comes from...
But I think you want to add a span to the div.
So just use .append() or .prepend() instead of .addClass().
That probably is what you are looking for.
Or just add the span using PHP !
Because I don't know what can be the use to make it on client-side on document ready.
Why not just to this and forget about appending with jQuery?
<div id="classadderpanel" style="background-color: orange;">
<span class='levelreplace'><?php echo $data['level']; ?></span>
<form id="form" class="classtest" action="aplayground_classadderform.php" method="POST">
<input type="submit">
</div>

Ajax text to PHP duplicates text and button when passing value

I am working on a bit of ajax that gets the value from a text input and passes it into a php variable. I have got the following code doing what I want, however it duplicates the text input and the button when it passes the value into php and I can't work out why, any ideas:
<html><head><title>Ajax Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function callAjaxAddition() {
arguments0 = $("input[name='arg1']").val();
$.ajax({
type: "POST",
url: "refresh.php",
data: {arguments: arguments0},
success: function(data) {
$("#answer").html(data);
}
});
return false;
}
</script>
</head>
<body><div id="exampleForm">
<input name="arg1" /><div id="answer"></div>
<br />
<button onClick="callAjaxAddition()">Click Me to Add</button>
</div>
<?php
if(isset($_POST['arguments']))
{
$a = $_POST['arguments'];
echo $a;
var_dump($a);
}
?>
</body></html>
You are sending request to a php file that has html code in it. So it renders current html, it has text box in it. And you are putting it in answer div. That's why it is duplicating. If you make a request to refresh.php, it response whole page not only echo $a; part. Create aseparate page like service.php and
service.php:
<?php
if(isset($_POST['arguments']))
{
$a = $_POST['arguments'];
echo $a;
}
?>
Use service.php in your ajax call

php file not working from ajax call

I have the following ajax function that is called from a form button that gets the number used in the php loop below. The php file loads but code stops working after " Fields With Red Asterisks * Are Required"
Any Help would be great!
function loadMulti() {
var num_to_enter = $('#num_to_enter').val();
$.ajax({
type: "POST",
url: "myphpfile.php",
data: "num_to_enter=" + num_to_enter,
success: function(){
$("#multi").load('myphpfile.php')
}
});
return false;
}
and the php :
<?php
$num_to_enter = $_POST["num_to_enter"];
echo $num_to_enter;
$i=1;
?>
<form class="my_form" name="addReg" id="addReg" method="post" />
<span class="red">Fields With Red Asterisks * Are Required</span>
<?php
while($i <= $num_to_enter){
?>
The html form here repeated by $num_to_enter
<?php
$i++;
}
?>
For starters you can clean up your code a bit. See if this helps (tested and its working)
JS File
function loadMulti ()
{
var num_to_enter = 2;//$('#num_to_enter').val();
$.ajax({
type: "POST",
url: "temp.php",
data: "num_to_enter=" + num_to_enter,
}).done (function (data){ //success is deprecated
$("#test").html (data);
});
return false;
}
$(document).ready (function (){
loadMulti ();
});
Or maybe you want a js post??
function loadMulti ()
{
var num_to_enter = 2;//$('#num_to_enter').val();
$ ("#check").on ("click", function (){
$.ajax({
type: "POST",
url: "temp.php",
data: "num_to_enter=" + num_to_enter,
}).done (function (data){ //success is deprecated
$("#test").html (data);
});
});
return false;
}
$(document).ready (function (){
loadMulti ();
});
PHP File
<?php
$num_to_enter = $_POST["num_to_enter"];
$string = "";
echo $num_to_enter;
$i=1;
while ($i <= $num_to_enter)
{
$string .= "The html form here repeated by {$num_to_enter}<br/>";
$i++;
}
?>
<span class="red">Fields With Red Asterisks * Are Required</span>
<?php echo $string; ?>
PHP File that makes the call.
<!doctype html>
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src='test.js'></script>
</head>
<body>
<div id="test">test</div>
</body>
</html>
or with the post
<!doctype html>
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src='test.js'></script>
</head>
<body>
<div id="test">results will show here.</div>
<form class="my_form" name="addReg" id="addReg" method="post" />
<input id="check" type="button" name="sendpost" value="Get Data">
</form>
</body>
</html>
EDIT: Added the php file that makes the call, I changed the .load () to .html ()
with its respected selector.
Also I am not sure if you wanted the message to print out more then once, so if you need it printed that way just change $string to an array.
Your PHP script 'works' fine, but you end up in a while loop that has no end because you never update $i. You need to increment it in the while loop:
<?php
$num_to_enter = $_POST["num_to_enter"];
echo $num_to_enter;
$i = 1;
?>
<form class="my_form" name="addReg" id="addReg" method="post" />
<span class="red">Fields With Red Asterisks * Are Required</span>
<?php
while ($i <= $num_to_enter) {
?>The html form here repeated by $num_to_enter <?php
// You need to increment this so the while loop stops when $i hits
// the same amount as $num_to_enter.
$i++;
}
?>
Change this:
data: "num_to_enter=" + num_to_enter,
to this:
data: {num_to_enter: num_to_enter},
$.ajax() expects an object, not a string. The docs do say that it can accept a string, but you have to serialize it yourself in that scenario; it's easier just to let jQuery deal with that.
Regarding the PHP: make sure you increment $i in your while loop, or it will never end, as #putvande pointed out, and make sure you include a closing </form> tag.
Finally, change this: $num_to_enter = $_POST["num_to_enter"]; to this: $num_to_enter = intval($_POST["num_to_enter"]); to force PHP to treat it as an integer.

Pass javascript variable to php with ajax and the result doesn't show anything

This is my code and i want to pass javascript variable with ajax to php when i click submit button then the result doesn't show var_data variable from javascript What code is wrong?
This is edit order one before everybody help me
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<?php
$test = $_GET['var_PHP_data'];
echo $test;
?>
</body>
</html>
and this is source code now
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
this statement if(isset($_GET['var_PHP_data'])) output false and then show Hello World What should i do to do for isset($_GET['var_PHP_data']) is true?
Your solution has PHP issues: you don't check if the data exists, and also, you don't do anything with the result. I've modified the script to do the following:
Check if the var_PHP_data var is set (in PHP, on the server).
If yes, just send a blank text response containing that data.
If no, then draw the form and everything else.
In the form, I've created a #result div.
Ajax response will be shown in this div.
Also make sure that you host the script at localhost and that it is called test.php. To make sure this is resilient, you can change the Ajax URL to
<?php echo $_SERVER['PHP_SELF'];?> to make sure that you'll hit the correct script.
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
Try jQuery Form its this will help to solve many problems.
For you question: try url without domain name, add tags 'form', change event click to submit, add data type
what are the contents of PassVariable.php ? if is the same where you have they jquery bit wont work coz php will print all the page again, if the file is different try
success: function(data) {
alert('databack = '+ data);
}
Try placing your input into a form and attaching the ajax call to the form onsubmit event. The way it happens in the provided happen is when you click in the field, in which case it submits before you can write anything really.
$(document).ready(function() {
$('#brn').click(function() {
var var_data = "Hello World";
alert("click works");
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { x: var_data },
success: function(data) {
alert(data);
}
});
});
});
change it to this code
then in PassVariable.php put
make button
<input type="button" id="btn" value="click me" />
it should work because it is very basic example. If it doesn't work check your console if there are any JavaScript errors and remove them.

HTML to jQuery to PHP, then from PHP to jQuery to HTML

Ok, I have this code:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function get() {
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#age').html(output).show();
});
}
</script>
</head>
<body>
<input type="text" id="name"/>
<a id="grabe" href="javascript: get()">haller</a>
<div id="age">See your name</div>
</body>
</html>
Here's what I want: get the id of an anchor tag from the anchor tag that has been clicked by the user via jQuery and then past that to a PHP file. The PHP file will then echo the id name of the anchor tag that was clicked by the user back to the jQuery which will then display the output into the specified element.
Here's the PHP file:
<?
$name=$_POST['name'];
if ($name==NULL)
{
echo "No text";
}
else
{
echo $name;
}
?>
Bind your event like this, since you are using jQuery
$('a').click(function(){
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#age').html(output).show();
});
});
And remove the javascript from the href
<a id="grabe" href="#">haller</a>
<a id="kane" href="#">haller 2</a>
$('#grabe').click(function() {
$('#age').load('yourphp.php', {'name':$(this).prop('id')});
});
You can use $(this) to access almost anything about "what brought you here" in the code. You'll also need a listener for the event. In this way too brief example below, I have it listening for any clicks to <span class="edit_area"> spans.
<script>
$(document).ready(function(){
$('span.edit_area').click( function(){
var fieldname = $(this).attr('id');
...
});
});
I dont know why you want to send an id to a server and then receive that id back again from the ajax call as it is already there in your client script. Anyway this is the code.
This code will does this functionalirty for all a tag with a class called"crazyLink" and show the data received from the server page in a div with id anotherCrazyDiv
HTML
<a class="crazyLink" href="#">I am crazy</a>
<a class="crazyLink" href="#">I am crazy2</a>
<div id="anotherCrazyDiv"></div>
Script
$(function(){
$(".crazyLink").click(function(){
var id=$(this).attr("id");
$.post("data.php", { name : id } ,function(data){
$("#anotherCrazyDiv").html(data);
});
return false; // to prevent normal navigation if there is a valid href value
});
});
Keep in mind that, in your scenario, the value in id variable and value in data variable (after getting response from ajax call ) are same.
you may want to separate your javascript from your html. it makes things easier. it should probably look something like this.
HTML
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> </script>
<script type="text/javascript" src="javascript/somescript.js"></script>
</head>
<body>
<input type="text" id="name"/>
<a id="grabe" class="someclass">haller</a>
<div id="age">See your name</div>
</body>
</html>
javascript
$(document).ready(function() {
$('.someclass').click(function() {
$('#age').load(
url: 'tt.php',
data: { name: $(this).attr('id')}
);
});
});

Categories