0

How can I get the results of the result.php into the welcome div using ajax or any other method to prevent loading a new page?

    <div id="welcome">
                    <form action="result.php" method="post">
                        <input type="hidden" id="date" name="selected"/>

                        <select id="city" class="cities" data-role="none" name="City">
                            <option value="">Anyplace</option>
                            .
                            .
                            .
                        </select>
                        <select id="type" class="cities" data-role="none" name="Event">
                            <option value="">Anything</option>
                           .
                           .
                           .
                        </select>                   
                    <input type="submit" class="button" value="Ok Go!"/>
        <input id="current" name="current" type="hidden"/>​
                </form>
    </div>
EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179
  • 3
    Possible duplicate: http://stackoverflow.com/questions/1218245/jquery-submit-form-and-then-show-results-in-an-existing-div?rq=1 – Pieter Jul 22 '13 at 15:14
  • Yobac is right that the `action` param makes your page reload, and Ankit has the right idea in using `$.ajax()` (although the code has some syntax errors). But there is no need to use the `
    ` tags at all. Please see my answer for full details.
    – cssyphus Jul 22 '13 at 19:55

3 Answers3

1

You can do something like this using jQuery Ajax

Use following code inside your head tag or footer

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>


    <script type='text/javascript>
     $('document').ready(function(){ //after page load
        $('.button').on('click', function(e){
             e.preventDefault(); //prevent default action
             $.ajax({
              'url': 'result.php',
              'type: 'POST',
              'success': function(response){
                 $('#welcome').html(response);
               }
             });
            });
    });
 </script>
Konsole
  • 3,447
  • 3
  • 29
  • 39
1

valit's the action="result.php" who makes your page reload

You shloud try to give an id to your form, and using a simple ajax call :

$("#formId").submit(function() {
    $.ajax({
        url: 'result.php',
        success: function(response) {
            $("#welcome").setValue(response); // update the DIV
        }
    });
    return false; // prevent form submitting
});

Cheers

Yobac
  • 43
  • 8
1

If you are doing this through AJAX, then there is no need for the <form> codes. The <form> codes are only useful if you are posting to a different page and expecting the view to change/refresh anyways.

Also, using <form> codes in this example will cause the page to refresh (and values inserted by jQuery to be lost) for the additional bit with the "Set value for hidden field CURRENT" button. Not that it likely matters in your real world app, but just FYI.

Ajax goes in your javascript code, and looks like this:

$('#mySelect').change(function() {
    var sel = $(this).val();
    //alert('You picked: ' + sel);

    $.ajax({
        type: "POST",
        url: "your_php_file.php",
        data: 'theOption=' + sel,
        success: function(whatigot) {
            alert('Server-side response: ' + whatigot);
        } //END success fn
    }); //END $.ajax
}); //END dropdown change event

Note that the data ECHO 'd from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.

For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:

$('#myDiv').html(whatIgot);

Presto! Your DIV now contains the data echoed from the PHP file.


Here is a working solution for your own example, using AJAX:

HTML MARKUP:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function() {

                $('#mybutt').on('click', function(e){
                    e.preventDefault(); //prevent default action
                    var ct = $('#city').val();
                    var dt = $('#date').val()
                    var ty = $('#type').val();
                    var curr = $('#current').val();
                    $.ajax({
                        url: 'result.php',
                        type: 'POST',
                        data: 'ct=' +ct+ '&dat=' +dt+ '&t=' +ty+ '&curr=' +curr,
                        success: function(response){
                            $('#welcome').html(response);
                        }
                    });
                });

                $('#mycurr').click(function(){
                    var resp = prompt("Please type something:","Your name");
                    $('#current').val(resp);
                });


            }); //END $(document).ready()

        </script>
    </head>
<body>

    <div id="welcome">
        <input type="hidden" id="date" name="selected"/>

        <select id="city" class="cities" data-role="none" name="City">
            <option value="sumwhere">Anyplace</option>
            <option value="anutherwhere">Another place</option>
        </select>
        <select id="type" class="cities" data-role="none" name="Event">
            <option value="sumthing">Anything</option>
            <option value="anutherthing">Another thing</option>
        </select>                   
        <input type="submit" id="mybutt" class="button" value="Ok Go!"/>
        <input type="submit" id="mycurr" class="button" value="Set value for hidden field CURRENT"/>
        <input id="current" name="current" type="hidden"/>
    </div>


</body>
</html>

PHP Processor file: result.php

$ct = $_POST['ct'];
$date = $_POST['dat'];
$typ = $_POST['t'];
$cu = $_POST['curr'];

if ($date == '') {
    $date = 'Some other date';
}

$r = '<h1>Results sent from PHP</h1>';

$r .= 'Selected city is: [' .$ct. ']<br />';
$r .= 'Selected date is: [' .$date. ']<br />';
$r .= 'Selected type is: [' .$typ. ']<br />';
$r .= 'Hidden field #CURRENT is: [' .$cu. ']<br />';

$r .= '<h2>And that\'s all she wrote....</h2>';

echo $r;
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • There has got to be a better way to do this. It appears as if every result you want returned must be in ajax "var" and "data:". Not to mention again in the PHP. I'm getting the PHP file to show in the hidden div, but with no results. But I have likely 50 questions w/various results. Gotta be a better way????? – flipflopmedia Jul 28 '17 at 17:52
  • (1) Usually, for an application like a quiz, you would store the answers in a MySQL database on the server (for security reasons). In result.php` you would add some code to send (to the server) the data that identifies the question to MySQL, and receive back the correct answer. You can then (still in result.php) decide if the user's response is correct and return only the boolean result back to that ajax code block on your HTML page. – cssyphus Aug 05 '17 at 14:02
  • (2) Some advantages to using AJAX here is that you (a) do not expose your answers to someone using DevTools, (b) you check the db and return a result without refreshing the HTML page – cssyphus Aug 05 '17 at 14:02
  • (3) Note that each time the user triggers an event to check the answer in the server-side database (such as by clicking a button saying "submit" or "check answer"), the overhead for AJAX to read the answer on the server and return a response is negligible. Usually, the AJAX routine will check and return the response in far less than a second each time the button is pressed. If it takes longer than that, you _really_ have a poor webhost (or a free one, in which case how can one complain?) – cssyphus Aug 05 '17 at 14:06