1

Normally works but when trying for ajax insert does not work.

Here is my form(no form action in html):

name: <input type="text" name="name" id="name">
<input type="submit" name="submit" value="add" id="submit">

Here is the add.php file code

require_once('conn.php');
$name = $_POST['name'];
$query = mysql_query("insert into toy(name) values('$name')");
if ($query) {
    echo "Data inserted";
}else{
    echo mysql_error();
}

And here is the javascript code

$(document).ready(function() {
$('#submit').click(function(){
    $.ajax({
    url: "add.php",
    type: "POST",
    data: {
        name: $("#name").val()
    },
    success: function(data){
          alert("Data Save: " + data);
     }
});
});

});

Thanks in advance for suggestion.

2
  • Are you getting the MySQL error (failure to insert), or does the Ajax call fail before that? Edit: Nevermind. See you got it fixed! Commented Oct 5, 2015 at 21:26
  • no. Solved after adding preventDefault Commented Oct 5, 2015 at 21:27

1 Answer 1

1

You need to prevent default form submit:

$('#submit').click(function(e){
   e.preventDefault()
   // do your ajax

});
Sign up to request clarification or add additional context in comments.

2 Comments

If I change my code data: $('#form').serialize(), dataType: 'json', Alert not working. How to fix that
you are returning text from server not json, so will cause a json parsing error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.