Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax to PHP on the same page

Tags:

jquery

ajax

php

I’m trying to send variables to the same page that makes the AJAX call.

I receive successful result only if I separate the PHP script (e.g. process.php and change the AJAX url accordingly).

index.php

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(function() { 
        $('form').submit(function(e) { 
            e.preventDefault();
            $.ajax({
                type        : 'POST',
                url         : 'index.php',
                data        : $(this).serialize(),
                dataType    : 'json',
                encode      : true
            })
            .done(function(data) {
                $('#result').html(data);    
            })
        });
    }); 
</script>
</head>

<body>
<?php
    $data = array();
    if(isset($_POST['name'])) {
        $data = 'You entered: ' . $_POST['name'];       
        echo json_encode($data);        
    }
?>
    <form>
        <input type="text" name="name">
        <input type="submit" value="Submit">
    </form>

    <div id="result"></div>
</body>

Is it possible for the same page to capture and process variables we pass using AJAX?

like image 825
blsn Avatar asked Mar 14 '15 16:03

blsn


1 Answers

You set dataType : json in AJAX settings, so that you should echo a json object instead of a String (HTML).
Use exit() instead of echo, and put your PHP at the very top of the page. So that no HTML is echoed before you check if $_POST['name'] exists.

Another thing is that your $data = array() is converted to string on that line:

$data = 'You entered:' . $_POST['name'];

it should be $data[] = ...

<?php
    $data = array();
    if(isset($_POST['name'])) {
        $data[] = 'You entered:' . $_POST['name'];
        exit(json_encode($data));       
    }
?>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(function() { 
        $('form').submit(function(e) { 
            e.preventDefault();
            $.ajax({
                type        : 'POST',
                url         : 'index.php',
                data        : $(this).serialize(),
                dataType    : 'json',
                encode      : true
            })
            .done(function(data) {
                $('#result').html(data);    
            })
        });
    }); 
</script>
</head>

<body>
    <form>
        <input type="text" name="name">
        <input type="submit" value="Submit">
    </form>
    <div id="result"></div>
</body>
like image 119
Artur Filipiak Avatar answered Oct 18 '22 23:10

Artur Filipiak