Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery, send a form by staying on the same page

Tags:

jquery

ajax

forms

I want to send a form without leaving my current page, so I'm using:

$('.myForm').on('submit', function(){
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            success: function(html) {
            alert('ok');
            }
        });
    return false; 
});

but it doesn't work... any idea please?

like image 202
Gradislava Bikkulova Avatar asked Mar 12 '13 10:03

Gradislava Bikkulova


2 Answers

Do this way:-

$(document).on('submit', '.myForm', function(e) {
     $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        success: function(html) {
        alert('ok');
        }
    });
    e.preventDefault();
});
like image 159
Siva Charan Avatar answered Oct 13 '22 00:10

Siva Charan


Here is an example

<form name="frm" method="POST" action="">
 <input type="text" name="name" id="name" value="" />
 <input type="text" name="last_name" id="last_name" value="" />
 <input type="submit" name="Update" id="update" value="Update" />
</form>

The jquery part

$("#update").click(function(e) {
  e.preventDefault();
  var name = $("#name").val(); 
  var last_name = $("#last_name").val();
  var dataString = 'name='+name+'&last_name='+last_name;
  $.ajax({
    type:'POST',
    data:dataString,
    url:'insert.php',
    success:function(data) {
      alert(data);
    }
  });
});

The insert.php page

<?php
  $name = $_POST['name'];
  $last_name = $_POST['last_name'];
  $insert = "insert into TABLE_NAME values('$name','$last_name')";// Do Your Insert Query
  if(mysql_query($insert)) {
   echo "Success";
  } else {
   echo "Cannot Insert";
  }
?>

Hope this helps

like image 45
Roger Avatar answered Oct 12 '22 23:10

Roger