I am trying to send some variables to PHP script and then to upload them in MySQL db.
Here is my JS script:
$.ajax({
url: '/insert.php',
type: 'POST',
data: {endadres:endadres,stadres:stadres,amount_of_carriers:amount_of_carriers, price_finalized:price_finalized },
success: function(data) {
console.log(data);
}
})
All of variables are extisting inside the same function (I checked it via "alert()").
Here is my PHP code:
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['FirstName']);
$last_name = mysqli_real_escape_string($link, $_REQUEST['LastName']);
$start_adress = $_POST['startadress'];
$end_adress = $_POST['endadress'];
$Price = $_POST['finallprice'];
$CarriersQuant = $_POST['carriersamo'];
// Attempt insert query execution
$post = "INSERT INTO Orders (FirstName, LastName, StartAdress, EndAdress, Price, CarriersQuant) VALUES ('$first_name', '$last_name', '$start_adress', '$end_adress', '$Price', '$CarriersQuant')";
LastName and FirstName are taken from .html, and I can upload them into my DB, but I am not able to get variables from js.
The variable names in the ajax post doesn't correspond with what you try to extract in the receiving end (PHP). If you stick with these names in JavaScript:
data: {
endadres,
stadres,
amount_of_carriers,
price_finalized
},
You must use the same key to collect them in PHP:
$foo = $_POST["endadres"]
To debug, I often find it useful to add this debug output to see all posted variables:
var_dump($_POST);
On a second note (unrelated to your question though), your SQL insert statement is very dangerous. You are concatenating the variables directly from the external request into the database query string, which means that a potential offender could post something like:
carriersamo: "'; DROP TABLE Orders;"
which would drop your Orders
table from your database. I recommend you read up on PHP's PDO module, where it's quite easy to prepare "safe" statements to the database. http://php.net/manual/en/book.pdo.php