DIM3NSION
DIM3NSION

Reputation: 1761

Page refresh instead of Ajax Load without

On form submit i want to load a div with an updated list of a mysql table. I'am sending the form variables across to a php and posting them into a mysql table. the same page displays the full table data. I want to load the data into the same div tag as the form. So it appears that the information is being loaded above the form.

My Javascript

$("#formSubmit").submit(function(){

    var name = $("input#name").val();
    var comment = $("input#comment").val();
    var filmnumber = $("input#hidden").val();

    var dataString = 'name='+ name + '&comment=' + comment + '&filmnumber=' + filmnumber;

    $.ajax({
        type: "POST",
        url: "comment.php",
        data: dataString,
        success: function() {
            $('#2').load('comment.php');
        }
    });

My form -

<div id="2">                                    
    <p>Add a Comment</p>
    <form id="formSubmit" method="POST">
        <div>
            <input type="hidden" name="hidden" id="hidden" value="2">
            <label for="name">Your Name</label>
            <input type="text" name="name" id="name" />

            <label for="body">Comment Body</label>
            <textarea name="comment" id="comment" cols="20" rows="5"></textarea>

            <input type="submit" id="comment" class="button" value="Submit" />
    </form>
    </div>

All it is doing is refreshing the page and not loading the information in to div 2 :S

thanks for your help

Upvotes: 3

Views: 1952

Answers (2)

Rooster
Rooster

Reputation: 10077

add a return false to the end to stop the form from submitting. or if you want to be more elegant use the preventDefault(); method. personally for something as simple as this though i just stick with return false;

$("#formSubmit").submit(function(e){ // add the event object as an argument to your function


var name = $("input#name").val();
var comment = $("input#comment").val();
var filmnumber = $("input#hidden").val();

var dataString = 'name='+ name + '&comment=' + comment + '&filmnumber=' + filmnumber;

$.ajax({
  type: "POST",
  url: "comment.php",
  data: dataString,
  success: function() {
   $('#2').load('comment.php');
  }
});
return false;//right here

});

Upvotes: 1

Eli
Eli

Reputation: 17825

You need to prevent the form from redirecting the page using the preventDefault method on the event object:

$("#formSubmit").submit(function(e){ // add the event object as an argument to your function
    e.preventDefault(); // right here

    var name = $("input#name").val();
    var comment = $("input#comment").val();
    var filmnumber = $("input#hidden").val();

    var dataString = 'name='+ name + '&comment=' + comment + '&filmnumber=' + filmnumber;

    $.ajax({
      type: "POST",
      url: "comment.php",
      data: dataString,
      success: function() {
       $('#2').load('comment.php');
      }
    });
});

Upvotes: 3

Related Questions