简体   繁体   中英

Pass data to PHP file using Ajax

I'm trying to pass data to PHP file using Ajax and then save to MySQL database. From some reasons it's not working. I tested PHP code with passing data from HTML form and it's working. When use Ajax, after click on submit button nothings happen. I think that the problem is in Ajax data parameter.

Here is the code:

HTML

<body>
<div class="container">
  <form class="search" action="" method="">
    <div class="form-group">
      <div class="input-group input-group-lg">
        <span class="input-group-addon"><i class="fa fa-search" aria-hidden="true"></i></span>
        <input type="text" class="form-control form-control-lg" id="trazi" name="trazi" placeholder="Pretražite artikle - upišite naziv, barkod ili šifru artikla">
      </div>
    </div>
  </form>
  <form class="articles" id="novi_artikl" action="" method="">
      <div class="form-group row">
        <label for="sifra" class="col-sm-4 col-form-label col-form-label-lg">Šifra artikla</label>
        <div class="col-sm-8">
          <input type="text" class="form-control form-control-lg" id="sifra" name="sifra" placeholder="Upišite šifru">
        </div>
      </div>
      <div class="form-group row">
        <label for="barkod" class="col-sm-4 col-form-label col-form-label-lg">Barkod artikla</label>
        <div class="col-sm-8">
          <input type="text" class="form-control form-control-lg" id="barkod" name="barkod" placeholder="Upišite barkod">
        </div>
      </div>
      <div class="form-group row">
        <label for="naziv" class="col-sm-4 col-form-label col-form-label-lg">Naziv artikla</label>
        <div class="col-sm-8">
          <input type="text" class="form-control form-control-lg" id="naziv" name="naziv" placeholder="Upišite naziv artikla" required>
        </div>
      </div>
      <div class="form-group row">
        <label for="mjera" class="col-sm-4 col-form-label col-form-label-lg">Jedinična mjera</label>
        <div class="col-sm-8">
          <input type="text" class="form-control form-control-lg" id="mjera" name="mjera" placeholder="Upišite mjeru" required>
        </div>
      </div>
      <div class="form-group row">
        <label for="cijena" class="col-sm-4 col-form-label col-form-label-lg">Cijena artikla</label>
        <div class="col-sm-8">
          <div class="input-group input-group-lg">
            <input type="text" class="form-control form-control-lg text-right" id="cijena" name="cijena" placeholder="Upišite cijenu" required>
            <span class="input-group-addon">KM</span>
          </div>
        </div>
      </div>
      <div class="form-group row">
        <label for="kolicina" class="col-sm-4 col-form-label col-form-label-lg">Količina artikla</label>
        <div class="col-sm-8">
          <input type="text" class="form-control form-control-lg text-right" id="kolicina" name="kolicina" placeholder="Upišite količinu" required>
        </div>
      </div>
      <div class="form-group row">
        <label for="ukupno" class="col-sm-4 col-form-label col-form-label-lg">Ukupna vrijednost artikla</label>
        <div class="col-sm-8">
          <div class="input-group input-group-lg">
            <input type="text" class="form-control form-control-lg text-right" id="ukupno" name="ukupno" placeholder="Ukupna vrijednost" required>
            <span class="input-group-addon">KM</span>
          </div>
        </div>
      </div>

    <br>
    <div class="float-right">
      <button type="submit" class="btn btn-primary btn-lg" id="spremi" name="spremi">Spremi</button>&nbsp;
      <button type="submit" class="btn btn-primary btn-lg" id="ponisti" name="ponisti">Poništi</button>
    </div>
  </form><!-- Content here -->
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script src="https://use.fontawesome.com/38d56b17e3.js"></script>
<script src="script.js" type="text/javascript"></script>

JavaScript

$('#spremi').click(function(){
var sifra = $('#sifra').val();
var barkod = $('#barkod').val();
var naziv = $('#naziv').val();
var mjera = $('#mjera').val();
var cijena = $('#cijena').val();
var kolicina = $('#kolicina').val();
var ukupno = $('#ukupno').val();

$.ajax({
  type: 'POST',
  url: 'insert.php',
  contentType: "application/json; charset=utf-8",
  dataType:'json',
  data: ({sifra: sifra}, {barkod: barkod}, {naziv: naziv}, {mjera: mjera}, {cijena: cijena}, {kolicina: kolicina}, {ukupno: ukupno}),
  success: function(response){

    alert(response);
  }
});
});

PHP code

<?php
include("connection.php");

if ($_POST["sifra"]) {
$sifra = $_POST["sifra"];
$barkod = $_POST["barkod"];
$naziv = $_POST["naziv"];
$mjera = $_POST["mjera"];
$cijena = $_POST["cijena"];
$kolicina = $_POST["kolicina"];
$ukupno = $_POST["ukupno"];

$query = "INSERT INTO lista (sifra, barkod, naziv, mjera, cijena, kolicina, ukupno) VALUES ('$sifra', '$barkod', '$naziv', '$mjera', '$cijena', '$kolicina', '$ukupno')";

$results = mysqli_query($dbc, $query);

if($results){
  echo "Artikl je uspješno spremljen.";
}
else {
  echo "Artikl nije spremljen. Došlo je do pogreške.";
}
}
mysqli_close($dbc);
?>

You should provide the values to the data property of $.ajax as a single object not as a collection of them:

data: {
  sifra: sifra, 
  barkod: barkod,
  naziv: naziv,
  mjera: mjera,
  cijena: cijena,
  kolicina: kolicina,
  ukupno: ukupno
},

Also, it's very important that you note your PHP code is wide open to SQL injection attacks . You should change the logic to use prepared statements ASAP.

The cause of your problem is the fact you are using type: 'POST' . To quote the docs :

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

POST is a more "old fashioned" method, typically you would POST a <form> where the content automatically is serialized , ie urlencoded, but you try to POST data in a JSON format. What you should do is either consider whether you really need POST. If you change it to GET (or simply remove type: 'POST' ) and access the passed data by $_GET then it will work (as long as you correct data as well).

If not, change the content type to indicate incoming urlencoded data :

$.ajax({
  type: 'POST',
  url: 'insert.php',
  contentType: "application/x-www-form-urlencoded",
  data: {sifra: sifra, barkod: barkod, naziv: naziv, mjera: mjera, cijena: cijena, kolicina: kolicina, ukupno: ukupno},
  success: function(response){
    alert(response);
  }
});

I am pretty sure your code will work now, ie the $_POST works and any message is properly received as plain text you can alert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM