AJAX, get the data returned through the POST request in PHP

0

I have a form with four selects, the selects send data using a POST method to a page called prices.php, once there, prices are calculated and an integer is returned indicating the price.

The thing is that I would like to show the result inside a DIV in the Index of the page, and I do not have AJAX knowledge, I used it a long time ago, but now I have no idea.

I have the following:

Index.php

 <script src="http://code.jquery.com/jquery-1.10.2.min.js"> </script>
 <script>

    $(function)(){
      $("#btn-enviar").click(function()){
        var url = "prices.php";
        $.ajax({
          type: "POST",
          url: url,
          data: $("#form").serialize(),
          success: function(data)
          {
            $("#contenedor").html(data);
          }
        });
        return false;
      });
    });
</script>


<form method="post" id="form">
    <select class="custom-select mr-sm-2" name="Objetos" required>
      <option value="Casa">Casa</option>
      <option value="Coche">Coche</option>
      <option value="Caramelo">Caramelo</option>
      <option value="Caña">Caña</option>
    </select>
  <input type="submit" id="btn-enviar" value="Prices" style="width:100%" />
</form>

<div id="contenedor"> </div>

On the prices.php page I have a case, evaluating the response that is passed and returning with a price echo.

However, when I click on the button, I only get the index page refreshed.

What am I doing wrong? Thanks in advance.

Update:

  

failed to load the source   " link ".   Page: 103: 1 SyntaxError: missing (before formal parameters)

Update:

    
asked by Georgia Fernández 18.12.2018 в 02:01
source

2 answers

1

You must fix the following line:

$(function)(){

by:

$(function(){

The error is that you passed a parentheses closing ) after function)

Code

$(function() {
  $("#btn-enviar").on("click", function(e) {
    e.preventDefault();
    var url = "prices.php";
    $.ajax({
      type: "POST",
      url: url,
      data: $("#form").serialize(),
      success: function(data) {
        $("#contenedor").html(data);
      }
    });
    return false;
  });
});
    
answered by 18.12.2018 / 02:31
source
2

Try adding this to your handler:

$("#btn-enviar").click(function(e)){
    e.preventDefault();

And in your HTML:

<form method="post" id="form" onSubmit="return false;">
    
answered by 18.12.2018 в 02:06