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
Related
I'm a newbie to Jquery , my question is simple , I'm trying to pass data using Jquery Post method, I have read a lot , but I can't figure it out:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="TestAd" id="TestAd">
<iframe data-aa='58593' src='https://ad.a-ads.com/58593?size=468x60' scrolling='no' style='width:468px; height:60px; border:0px; padding:0;overflow:hidden' allowtransparency='true' frameborder='0'></iframe>
</div>
<button>Send request</button>
<br>
<?php
if(!empty($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var height = $('.TestAd').height();
$("button").click(function()
{
if (height==0)
{
$.post("", {block:true});
}
}
</script>
</body>
</html>
The script is a simple AdBlocker checker, thanks for your help
<form method="post">
<input type="hidden" value="true" name="block">
<input type="submit" value="Send request">
</form>
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
if you want to redirect it to the same page why dont you use simple form tag to pass the block value.By default it will redirect it on the same page
Change your PHP to this:
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
And Change your jQuery to this:
<script>
var height = $('.TestAd').height();
$("button").click(function () {
if (height == 0) {
$.post("somepage.php",{block: true}, function (data) {
// data is the response
// do something with it here
alert(data);
});
}
}
</script>
Here are the docs for $.post(), essentially, the way you had it, ignores the response. You have to pass the anonymous function (function (data) {}) callback as the 3rd argument to be able to work with the response.
From the docs:
Examples:
Request the test.php page and send some additional data along (while still ignoring the return results).
$.post( "test.php", { name: "John", time: "2pm" } );
I have a PHP page included called 'leaguestatus.php'. This page allows the user to post a message/status update and the intent is to have only this part of the div refreshed; however, on submit, the entire page is reloaded.
In the current implementation I'm simply printing all the $_POST variables to the div so I can see what's coming through. The MsgText textarea DOES get posted, however, it's only after the whole page loads. I'm trying to get just the div and that included file to reload.
div id="statusupdates"><? include 'leaguestatus.php'; ?></div>
leaguestatus.php
<form id="statusform" method="POST">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
<? print "<pre>POST Variables:<BR>";
print_r ($_POST);
print "</pre>";
$MsgText = $_POST["MsgText"];
?>
</div>
The jQuery I'm running in the header is:
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response) {
$("#formbox").html(response);
}
}).success(function(){
});
}
});
Here are my includes:
html header
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
Edit: updated code to reflect use of #sazedul's response. Only issue now is on first click page acts as expected (no page refresh). On second click the entire page reloads. On third click we're back to normal.
Use this following code for ajax submit hope it will work.
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl)
{
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response)
{
$("#formbox").html(response);
}
});
}
Made the following changes in your leaguestatus.php remembar to put double quote in the name="MsgText" in text area.
<form id="statusform" method="POST">
<textarea name="MsgText" rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
</div>
<?php
if(isset($_POST['MsgText'])){
$message=$_POST['MsgText'];
echo $message;
}
?>
check for .load() like the code below....
$(document).ready(function() {
$("#statusform").submit(function() {
$("div").load();
});
});
You have to preventDefault of submit then other thing
so,you have to use e.preventDefault() to prevent submit.then do what ever you want
$("#statusform").submit(function(e) {
e.preventDefault();
......
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.
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.
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';
}