samedi 27 juin 2015

PHP file is not triggered using jQuery/AJAX

got a strange problem today. So I was trying to insert data into database using AJAX so the page wouldn't need to reload to see changes. But when i try to insert data, dont know how to put it, the insert.php file does not get "triggered", e.g the line "Hello Im insert.php" is not shown. But the ajax code works fine, success block gets triggered.

form:

<form action="insert.php" method="post" class="form-inline" id="forma">
    <input type="text" class="form-control" name="inputName" id="inputName" placeholder="Name">
    <input type="text" class="form-control" name="inputPrice" id="inputPrice" placeholder="Price">
    <input type="text" class="form-control" name="inputStore" id="inputStore" placeholder="Store">
    <input type="text" class="form-control" name="inputDate" id="inputDate" placeholder="Date"></br>
    <button id="submit" type="submit" class="btn btn-success">Submit</button>
</form>

jQuery:

$('#forma').submit(function() {
    var name = $("#inputName").val();
    var price = $("#inputPrice").val();
    var store= $("#inputStore").val();
    var date = $("#inputDate").val();

    $.ajax({
        type: "POST",
        url: "insert.php",
        data: {
            inputPavadinimas: name,
            inputKaina: price,
            inputParduotuve: store,
            inputData: date,
        },
        success: function() {
            $("#success").show();
            alert('success');
        },
        error: function(){
            alert('error');
        }
    });
    return false;    
});

insert.php:

<?php
error_reporting(0);
require 'db/connection.php';

echo 'Hello Im insert.php';

if(!empty($_POST)){
    print_r($_POST);
    if(isset($_POST['inputName'],$_POST['inputPrice'],$_POST['inputStore'],$_POST['inputDate'])){
    $name = trim($_POST['inputName']);
    $price = trim($_POST['inputPrice']);
    $store = trim($_POST['inputStore']);
    $date = trim($_POST['inputDate']);

    if(!empty($name) && !empty($price) && !empty($store) && !empty($date)){
        $insert = $db->prepare("INSERT INTO prekes(name, price, store, date) VALUES (?, ?, ?, ?)");
        $insert->bind_param('ssss',$name, $price, $store, $date);

        if($insert->execute()){
            echo 'INSERTED';
        }
    }
}

};

Aucun commentaire:

Enregistrer un commentaire