php file not working from ajax call - php

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.

Related

How to pass variable in real time?

I have a simple code:
ajax.html
<html>
<head>
<title>AJAX</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$(document).on("click", "#ajax-button", function() {
$.ajax({type: 'POST', url: 'ajax.php', data: ({ ajax: $('input[name="ajax"]').val() }),
success:function(data){
$('#result-ajax').html(data);
}
});
});
});
</script>
<input type="text" name="ajax" /> <button id="ajax-button">OK</button>
<div id="result-ajax"></div>
</body>
</html>
ajax.php
<?php
$ajax = intval($_POST['ajax']);
for ($i=0; $i < $ajax; $i++) {
echo $i;
sleep(3);
}
?>
I want get variable in real time, but now i get variable after loop, how I can update my variable in real time? I am tried set async: false, but it just freeze window browser.
HTTP functions as a request-response protocol, so you cant have response by the server on every 3 seconds without making new request. Another way is to use sockets. I hope its helpfull.

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

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.

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

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';
}

How to use different pages for form input and results using AJAX

So, I have a search form in a php page (top.php) which is an include for the site I'm working on, one php page where all the mySQL stuff happens and the results are stored in a variable and echoed (dosearch.php) and lastly a php page where the results are displayed in a div through jQuery (search.php). This is the javascript code:
$(document).ready(function(){
$('#search_button').click(function(e) {
e.preventDefault();
var searchVal = $('#search_term').attr('value');
var categoryVal = $('#category').attr('value');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: "search_term=" + searchVal + "&category=" + categoryVal,
beforeSend: function() {
$('#results_cont').html('');
$('#loader').html('<img src="layout/ajax-loader.gif" alt="Searching..." />');
if(!searchVal[0]) {
$('#loader').html('');
$('#results_cont').html('No input...');
return false;
}
},
success: function(response) {
$('#loader').html('');
$('#results_cont').html(response);
}
});
});
});
The #search_term and #category fields are in top.php, the other divs (#loader and #results_cont) are in search.php. How would I go by in order to make the form submit and display the results in search.php from the top.php without problems? It works perfectly if the form and javascript are in search.php but I can't seem to separate those and make it work. What am I doing wrong?
PS. Sorry if I'm not clear enough, am at work, really tired. :(
SPLITTING:
<? include('functions-or-classes.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<? include('js-script.php'); ?>
</head>
<body>
<? include('results-div.php'); ?>
<? include('search-form.php'); ?>
</body>
</html>
You should just respect this order then you can split the code in different pieces and include it into your main php file;
PS: peraphs your code should look like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
$(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var searchVal = $('#search_term').val();
var query = $(this).serialize(); // search_term=lorem&category=foo
if (!searchVal) {
$('#results_cont').html('No input...');
} else {
$('#results_cont').html('<div id="loader">'+
'<img src="layout/ajax-loader.gif" alt="" /><div>');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: query,
success: function(response) {
$('#results_cont').html(response);
}
});
}
});
});
</script>
</head>
<body>
<form id="search-form">
<input type="text" id="search_term" name="search_term" />
<select id="category" name="category">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input type="submit" name="search_button" />
</form>
<div id="results_cont"></div>
</body>
</html>
you can make your search_button redirect to your search.php an do the work when the pages is loaded instead of doing it on the click event.
and use $_GET['Search'] on the search page
and your url should look like this
/search.php?Search=1337

Categories