How to Submit a form and load target page inside a Div on the Current page?

15,254

Since you provided no code, I'll have to guess, either:

1) You have the AJAX code to load the php response into a division but the page still refreshes, in which case - when the form is submitted you need to prevent the default event triggering, do this with:

event.preventDefault();

Stick that as the first thing inside the function that get's executed inside the onClick(). It should all work now. Incidentally, you probably want onSubmit() instead, in case someone hits 'Enter' instead of clicking the 'submit' button (although I'm not sure if it's part of the standard javascript/DOM). Check out a javascript library called JQuery, it makes javascript a breeze.

2) You actually want AJAX, in which case go to jquery.com, download their javascript library and go through some tutorials on ajax requests. The basics are something like:

$("#id_of_your_form").submit(function(event){
    event.preventDefault();
    $.post( url_of_php_file, $("#id_of_your_form").serialize(), function(data){
        $("#id_of_your_div").html(data);
    });
});

This code is basic, but should work, provided you remember to include the library file in your .html file.

#UPDATED

Is there any particular reason you're using the JSON object? I just haven't used it before myself, so my input here might be limited. Try this:

ajax.html

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

//
$(document).ready(function(){

    $("#button").click(function(event){ //don't forget to pass the event as an argument

        //need this, or your page will follow the url defined in the form
        event.preventDefault();

        var sendu = $("#username").val();
        var sendp = $("#password").val();

        $.ajax({
        type: "POST",
        url: "ajax.php",
        data: "username="+sendu+"&password="+sendp, /*shouldn't the method be GET then?*/
        dataType: "json", 
        success: function(msg){
            $("#result").html(msg.name+'<br />'+msg.password);
        }
        });
    });
});


</script>
</head>

<body>
    <form action="miss.php" method="post">
        Name:<input type="text" id="username" name="username" /><br />
        Password:<input type="password" id="password" name="password" /><p>
        <input type="submit" id="button" />
    </form>
<p><div id="result"></div>
</body>
</html>

ajax.php

<?

$name = $_POST['username']; //use $_POST array instead
$password = $_POST['password'];

$list = array('name'=>$name, 'password'=>$password);

$c = json_encode($list);

echo $c;
?>

(Note: I haven't checked the php code as such, since as I said, I'm not too familiar with JSON objects) If you don't specifically need the json object, you could try using standard text/xml for simplicity. Also, consider using $.post instead of $.ajax, it should make things easier.

Also, don't forget to use the form tags around your input or your html won't be valid(citation needed) and finally, if you're working with html in your javascript it might be a good idea to use single quotes instead of double quotes to indicate your strings. Hope that helped.

#UPDATE 2

Okay, since you don't need JSON for basic stuff(leave JSON for later), use text/xml instead. Also, have a look at the comments. This should all work, provided WAMP is running and both files are in the same folder. Here's the code:

ajax.html

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

//
$(document).ready(function(){

    $("#login_form").submit(function(event){    //don't forget to pass the event as an argument

        //need this, or your page will follow the url defined in the form
        event.preventDefault();

        var sendu = $("#username").val();
        var sendp = $("#password").val();

        $.post("ajax.php", {'username' : sendu, 'password' : sendp}, function(data){
            $("#result").html(data); //data is everything you 'echo' on php side
        });

    });
});


</script>
</head>

<body>
    <form action="miss.php" method="post" id="login_form">
        Name:<input type="text" id="username" name="username" /><br />
        Password:<input type="password" id="password" name="password" /><p>
        <input type="submit" id="button" />
    </form>
<p><div id="result"></div>
</body>
</html>

ajax.php

    <?php
//you used shorthand <? as the php tag, it's probably why your code didn't work
//I would discourage using the shorthand, it's silly

$name = $_POST['username']; //use $_POST array instead
$password = $_POST['password'];

echo $name.'<br />'.$password;

?>

If this doesn't work...check if you have skype running, for some reason WAMP will not work with skype on at the same time, it's weird.

Share:
15,254
BastiaanWW
Author by

BastiaanWW

Updated on June 04, 2022

Comments

  • BastiaanWW
    BastiaanWW almost 2 years

    I am new to Javascript and didn't arrive to find a working script that does the following:

    I have a hidden form in javascript that should be submitted on an onclick event. The fields in the form are used in the target php file to create output. The target php file should be loaded inside a div on the current page without reloading the whole page.

    The problem is that I cannot get the target php file to load inside the div on the current page, but the target php page is simply loaded showing the results that I want to have inside the div.

    Any help would be very appreciated!

    Update #1

    I did a youtube tutorial on jquery ajax request where the result is shown in a div on the same page. I double checked the code many times and it looks the same as in the tutorial. In the tutorial the code is working but for me it isn't. Below are all the files I'm using and the code.

    ajax.html:

    <html>
    <head>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
    
    //
    $(document).ready(function(){
    
    $("#button").click(function(){
    var sendu = $("#username").val();
    var sendp = $("#password").val();
    
    $.ajax({
    type="POST",
    url: "ajax.php",
    data: "username="+sendu+"&password="+sendp,
    dataType: "json", 
    success: function(msg,string,jqXHR){
    $("#result").html(msg.name+"<br />"+msg.password);
    }
    });
    });
    });
    
    
    </script>
    </head>
    
    <body>
    Name:<input type="text" id="username" name="username" /><br />
    Password:<input type="password" id="password" name="password" /><p>
    <input type="button" id="button" value="submit" />
    <p><div id="result"></div>
    </body>
    </html>
    

    jquery.js from this url: http://code.jquery.com/jquery-1.6.2.min.js

    ajax.php:

    <?
    
    $name = $_REQUEST['username'];
    $password = $_REQUEST['password'];
    
    $list = array('name'=>$name, 'password'=>$password);
    
    $c = json_encode($list);
    
    echo $c;
    ?>
    

    I'm using the WAMP server as my localhost, could it have anything to do with a setting?