Form with PHP sends POST variables to same page with jQuery without reloading

Asked

Viewed 101 times

-1

This basic code below will be used to filter via POST and jQuery a SELECT on a PHP page.

The form sends to the same page, jQuery receives and sends to PHP, which receives via $_POST["campanha"];.

The page shouldn’t be giving refresh but this is happening. Can anyone help me with this mistake, please?

<html> 
<head>
      <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js"></script>
      <script type="text/javascript">
        $(function(){
           $("#bot_enviar").click(function(){
            event.preventDefault();
               var varCampanha = $("#campanha").val();
               $.post('teste.php', {
                   type:"POST",
                   campanha: varCampanha
               }, function(response){
                    alert(campanha);
               });
           });
        })
    </script>
</head> 
<body>

<form action="" method="post" id="bot_enviar">
    <select name="campanha" name="campanha">
      <option value="1">1</option>
      <option value="3">3</option>
    </select>
<br>

<input type="submit" >
</form>



Campanha: <?php echo $_POST["campanha"]; ?>
</body>
</html>

2 answers

2

There are some errors in your code. Your <input type="submit" > is the button that sends and reloads the page. You did not place the event click on that button, and yes you put it in the form. Note that you have put the id="bot_enviar" in the form instead of on the button.

You should put the event click on the button or else put the event submit no form. What does not give is to place the event click in form.

If you prefer to place the event click on the button, then take the id="bot_enviar" form and put it on the button. I would also recommend changing to <input type="button" id="bot_enviar">.

If you prefer to put the event in the form, simply change the $("#bot_enviar").click for $("#bot_enviar").submit. However, in that case I would change the name of that id to something that clearly demonstrates that it is the form, not the button.

1

Complementing the @Cvictor-stafusa response (The amendments cited by him are essential):

You are calling the method preventDefault() without invoking the Event parameter in the event of the click on:

$("#bot_enviar").click(function(){ 

The right thing would be:

$("#bot_enviar").click(function(event){ 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.