Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP + jQuery + Ajax form submission - return results on the same page

I would like to have the following:

User submits a form by a click (index.php), the form input is processed by an external PHP file (search.php) and results are posted on the original page (index.php) in a div.

I have already got together most of the code. It submits a form on a click and sends it to a PHP script.

What I would need now is that the result from the PHP script are given back to the original page (index.php).

Here is my code so far:

function submit() {
    $(function() {
        var id = "id";
        var dataString = 'id=' + id;
        $.ajax({
            type: "POST",
            url: "inc/search.php",
            data: dataString,
            success: function() {
                goToByScroll("result");
                $('#result').html("<br><br><br><br><br><br><br><br><br><br><
                                   div class='center'><img src='img/loader.gif' /></div>").hide().fadeIn(2500, function() {
                $('#result').html("Finished");
                });
            }
        });
        return false;
    });
}

My PHP file (for testing) is:

<?php function safe($value)
{
    htmlentities($value, ENT_QUOTES, 'utf-8');
    return $value;
}
if (isset($_POST['id'])) {
    $id = safe($_POST['id']);
    echo ($id);
}
elseif (!isset($_POST['id'])) {
    header('Location: error?id=notfound');
} ?>

I would like to have results from search.php (in this case "id") posted into #result, but I can't figure out how :S

like image 753
r0skar Avatar asked Jan 19 '23 23:01

r0skar


1 Answers

I think you've got almost everything. The callback function you have under success needs an argument which stands for the results from search.php

     success: function(res) {
             goToByScroll("result");
             $('#result').html("<br><br><br><br><br><br><br><br><br><br><div class='center'><img src='img/loader.gif' /></div>").hide().fadeIn(2500, function() {
                 $('#result').html(res + "<br /><br /> Finished");
             });
         } 

res is everything outputted be search.php. Echo, stuff outside of php tags, etc Anything you'd see if you loaded search.php itself.

I don't know if you wanted 'Finished' to still be there. Take it out if you dont.

like image 119
jon_darkstar Avatar answered Jan 22 '23 13:01

jon_darkstar