Jump to content

How to pass PHP variable with ajax?


Go to solution Solved by Psycho,

Recommended Posts

Hi. I've been learning ajax with jquery and I am struggling to work out how to pass PHP variable between two PHP pages.
I started with a simple form:

<!DOCTYPE HTML>
<html lang="">
<head>
    <meta charset="UTF-8">
    <title>FORM1</title>
</head>
<body>
<div class="container">
<?php for($a = 0; $a < 3; $a++): ?>
<form action="FORM2.php" method="post">
<input type="hidden" name="var" value="<?php echo $a; ?>">
<input type="submit" name="submit" value="Index <?php echo $a; ?>">
</form>   
<?php endfor; ?>
</div>
</body>
</html>
<?php
header('Content-Type: text/html; charset=utf-8');
$variable = $_POST['var'];  
echo $variable;
?>

How can I do the same without page refresh using ajax?
I have tried using json encoder but I haven't been successful.

<!DOCTYPE HTML>
<html lang="">
<head>
    <meta charset="UTF-8">
    <title>AXAX1</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
        $('form').submit(function(e) {
            e.preventDefault();
            $.ajax({
                url: "AJAX2.php",
                type: "POST",
                dataType: "json",
                success: function(result) {
                    alert(data);
                },
                error: function(jqXHR, data ) {        
                    alert ('Ajax request Failed.');    
                }
            });
        });
    });
    </script> 
</head>
<body>
<div class="container">
<?php for($a = 0; $a < 3; $a++): ?>
<form action="AJAX2.php" method="post">
<input type="hidden" name="var" value="<?php echo $a; ?>">
<input type="submit" name="submit" value="Index <?php echo $a; ?>">
</form>   
<?php endfor; ?>
</div>
</body>
</html>
<?php
header('Content-Type: text/html; charset=utf-8');
$variable = $_POST['var'];  
echo json_encode($variable);
?>
Link to comment
https://forums.phpfreaks.com/topic/302685-how-to-pass-php-variable-with-ajax/
Share on other sites

1. You need to send the form data to AJAX2.php.

data: $(this).serialize(),
2. Your code is confused about what variable to use in the success callback.

success: function(result) {
	alert(data);
},
3. The AJAX page needs to be consistent about whether it returns HTML or JSON.

<?php
header('Content-Type: application/json');
$variable = $_POST['var'];  
echo json_encode($variable);
?>
<?php
header('Content-Type: text/html; charset=utf-8');
$variable = $_POST['var'];  
echo '<p>' . htmlspecialchars($variable) . '</p>'; // for example
?>
(your AJAX code expects JSON so obviously you need to use the former)

I've sent the form data to AJAX2.php properly indicating JSON data in this page and I've used the callback function to insert the data back in the page AJAX1.php with a jquery html method but the page display an alert with a failed request.

$.ajax({
    url: "AJAX2.php",
    type: "POST",
    data: $('form').serialize,
    dataType: "json",
    success: function(data) {
        $('#display').html(data);
    },
    error: function(jqXHR, data ) {        
        alert ('Ajax request Failed.');    
    }
});
<body>
...
<div id="display">
</div>    
</body>
<?php
header('Content-Type: application/json');
$variable = $_POST['var'];  
echo json_encode($variable);
?>

Why does this happen?

  • Solution

OK, there are two problems with this line

data: $('form').serialize,

As requinix said, serialize is a function not a property. Function are called with parens: e.g. serialize().

 

Also, you cannot call 'form' since you have three forms on your page. Even if you correct the serialize function it will always pick the last form (i.e. the 2 value). Fortunately, jquery gives you a way to use the data of the form that called the function. And, requinix gave the the proper way to call it in step #1 of his first response.

Edited by Psycho
  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.