eqinna eqinna - 7 months ago 31
Javascript Question

Get page content from separate page into div on form submit without reloading current page

I'm attempting to fetch data from another page and load its response and content into a div in the page where I have my form - without reloading the form page. When I try this code it refreshes the page and doesn't fetch the results.

The current jquery code where I have my form - form.php:

<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script>
<script>
$('#skipreload').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('GET'), // GET or POST
url: $(this).attr('dbresults.php'), // the file to call
success: function(response) { // on success..
$('#form_output').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
</script>
</head>
<body>

<form id="skipreload" method="GET" action="form.php">
<input type="text" name="id">
<input type="submit" value="Get results">
</form>

<div id="form_output">
<!--Show the result here from dbresults.php-->
</div>

</body>
</html>


The code in the page I want to fetch results from - dbresults.php:

include("dbsettings.php");

$id = "";

if ($_GET)
{
$id = $_GET['id'];

$sql = "SELECT Results FROM Table WHERE id = '$id';";
$result = mysql_query($sql);

while($row = mysql_fetch_array($result))
{
echo $row["Results"]";
}
}


When I'm submitting the form in form.php the page reloads without getting the result into the div "#form_output" from getresults.php - why doesn't it work?

Answer

There is not attribute GET , that is a value for the method and there is no attribute 'dbresults.php' that is a value for the action attribute.

In addition your code is being called before form exists

Try:

$(function(){ // wait until documented is ready so element exists

    $('#skipreload').submit(function() { // catch the form's submit event
        $.ajax({ // create an AJAX call...
            data: $(this).serialize(), // get the form data
            type: $(this).attr('method'), // GET or POST
            url: $(this).attr('action'), // the file to call
            success: function(response) { // on success..
                $('#form_output').html(response); // update the DIV
            }
        });
        return false; // cancel original event to prevent form submitting
    });

});