There are two files, in the first one there is a form and javascript, in the second there is a php code that sends data from the first file to the database. I try to ensure that when you enter data and press the send button, a message about successful sending is displayed, otherwise there is an error, but it does not display these messages, although the data is added to it. Help me please.

File 1 (html)

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Добавление клиента</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $("document").ready(function() { $ ("#send").click(function(){ var dannie = $("form").serialize(); $.ajax({ url:'insert.php', type: 'POST', data: dannie, success: function (data) { if (data) { alert("Успешно добавлена") ; } else { alert("Ошибка"); } } }); }); }); </script> </head> <body> <form> клиент<br/> <input type="text" name="klient" /><br/> ОП_форма <br/> <textarea name="op_forma" ></textarea> <br/> <!-- cols="10" rows="10" --> <input type="submit" id="send" value="Добавить" /> </form> </body> </html> 

File 2 (php)

 <?php $connection=mysql_connect("localhost","reklama","reklama") ; mysql_select_db('reklama'); mysql_set_charset("SET NAMES utf8"); $ret=true; mysql_query(" INSERT INTO `klienti` (klient,op_forma) VALUES ('". $_POST ['klient'] ."' , '" . $_POST ['op_forma'] ."')") or $ret=false; echo $ret; ?> 

    1 answer 1

    In parallel with ajax, you have the usual form submission, and the page reloads before the answer to ajax comes. To prevent standard (not ajax) submit forms:

     $("#send").click(function() { var dannie = $("form").serialize(); $.ajax({ ... }); return false; // !!! }); 

    Or - as recommended by @Other:

     $("#send").click(function(event) { event.preventDefault(); // !!! var dannie = $("form").serialize(); $.ajax({ ... }); }); 

    A also:

     $("form").submit(function(event) { event.preventDefault(); // !!! var dannie = $("form").serialize(); $.ajax({ ... }); }); 
    • Maybe event.preventDefault(); better event.preventDefault(); ? Maybe he will need a surf. - user207618