How to POST data to php file using AJAX [duplicate] - javascript

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 6 years ago.
I am having trouble sending data to a php file to be processed. I have tried just about everything but cannot find the source of the problem. Below is a php file that sends a product name, price, and ID to a checkout function after a user clicks on a buy button.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT P1.Product_Name, S2.Price, P1.Product_ID FROM Product P1, Sale_Item S2 WHERE P1.Product_ID=S2.Product_ID AND P1.Category='Sports'";
$res = $conn->query($sql);
$counter=0;
while ($row = $res->fetch_assoc()){
$Product_Name = $row["Product_Name"];
$Price = $row["Price"];
$Product_ID = $row["Product_ID"];
echo ('<td><p></p>'.$row["Product_Name"].'<br>'.$row["Price"].'<p></p><input type="button" value="Buy" onclick="checkout(\'' . $Product_Name . '\', \'' . $Price . '\', \'' . $Product_ID . '\')"</td>');
$counter++;
if ($counter==3) {
$counter=0;
print "<br>";
}
}
$conn->close();
?>
And next the checkoutfunction:
<script type="text/javascript">
function checkout(Product_Name, Price, Product_ID) {
//document.write(Product_Name, Price, Product_ID)
var theProduct_Name = Product_Name;
var thePrice = Price;
var theProduct_ID = Product_ID;
$.ajax({
type: "POST",
url: "http://localhost:8888/checkout.php",
data: {Product_Name: theProduct_Name, Price: thePrice, Product_ID: theProduct_ID},
});
window.location.assign("http://localhost:8888/checkout.php")
}
</script>
I am using MAMP's phpMyAdmin's database. Is my url incorrect? I've tried using "http://localhost:8888/checkout.php" and just checkout.php. Below is the php file where I need to process data. For simply learning how to send the data I am just echoing inside the file to make sure it is actually posting. But nothing is being echoed.
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$theProduct_Name = $_POST['Product_Name'];
$theProduct_ID = $_POST['Product_ID'];
$thePrice = $_POST['Price'];
echo $theProduct_Name.$theProduct_ID.$thePrice;
?>
I am new to web-programming so any help or tips would be appreciated. I've been looking at this for hours now and cannot seem to get it to work.

When using Ajax, the request is sent by ajax and you can see the response in the success method. Any direct call to the action URL will sends new request which is empty in this case for the line
window.location.assign("http://localhost:8888/checkout.php")
Remove that line of code and change your jQuery.Ajax like bellow to see what's the response.
var request = $.ajax({
type: "POST",
url: "http://localhost:8888/checkout.php",
data: {Product_Name: theProduct_Name, Price: thePrice, Product_ID: theProduct_ID},
dataType: "html"
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});

You can track the ajax request in browser console. It will show you the request and response and the error you are receiving from your php script.
If on button click you are not able to see any request in the console then try to use "method" instead of "type". Some older jquery version doesn't support type. method: "POST",

I tested your code and it worked, the ajax request occurs normally, try remove this single line from your javascript code.
window.location.assign("http://localhost:8888/checkout.php");
I use this version of jQuery: https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js
In Network tab of Google Inspector I get this:
Request:
Request URL:http://localhost:8888/checkout.php
Request Method:POST
Status Code:200 OK
Remote Address:127.0.0.1:8888
Response:
Bike150

you should have following changes on your code
$.ajax({
method: "POST",
url: "http://localhost:8888/checkout.php",
data: {"Product_Name": "theProduct_Name", "Price": "thePrice", "Product_ID": "theProduct_ID"},
success : function(responseText)
{
alert('success to reach backend');
// you can console the responseText and do what ever you want with responseText
console.log(responseText);
},
error : function(jqXHR, status, error){
if (jqXHR.status === 0) {
alert('Not connected.\nPlease verify your network connection.');
} else if (jqXHR.status == 404) {
alert ('The requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert ('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert ('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert ('Time out error.');
} else if (exception === 'abort') {
alert ('Ajax request aborted.');
} else {
alert ('Uncaught Error.\n' + jqXHR.responseText);
}
}
});

Related

PHP not inserting data into MySQL table with correct SQL syntax

I'm trying to insert a JSON array of objects passed via a jquery $.ajax POST into a MySQL database via PHP. I've seemingly tried everything but for some reason I can't get it to work. Any suggestions would be much appreciated.
PHP
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = json_decode($_POST, true);
foreach ($data as $item) {
$worker_id = $item['worker_id'];
$response_time = $item['time'];
$video_id = $item['video_id'];
$submission = $item['response'];
$test_answer = $item['test_answer'];
$sql = "INSERT INTO nristudy (worker_id, response_time, video_id, submission, test_answer)
VALUES ('$worker_id', '$response_time', '$video_id', '$submission', '$test_answer')";
if (!($conn->query($sql))) {
die($conn->error);
}
}
if (!$conn->commit()) {
echo "Transaction commit failed";
exit();
}
$conn->close();
?>
Javascript
var json = JSON.stringify(submissions);
$.ajax({
type: "POST",
url: "http://hci.cs.wisc.edu/nri/store_data.php",
data: json,
success: function(data){
console.log("Success: " + data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... look at the console for more information!');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
}
});
The solution to your problem depends heavily on what the error is. However, one thing that is pretty clear is that you should be escaping the strings you are trying to put into the query.
I recommend that you switch to using PDO and prepared statements as you will not have to worry about escaping anything and can rely on PDO to take care of it when you prepare the statement.
You might also want to try serialize instead of json_encode but if it works there is a chance that SQL injection is still a real big possibility for you.

Reading a response in Ajax php and mysql

I can't get the code to work and redirect to 2 different pages depending if the information is correct or not...
So far I have this on my login page:
$(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'newfile.php',
data: $('#form').serialize(),
success: function (response){
alert(response);
if (success.text="Username or Password incorrect")
window.location.href = "index.php";
else if (success.text="login successful") {
window.location.href = "login_success.html";
} else {
}
}
})
})
and the information Im reading from is (from another page):
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die(" Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$sql="SELECT myusername, mypassword FROM user WHERE myusername = '" . mysqli_real_escape_string($conn, $myusername) . "' and mypassword = '" . mysqli_real_escape_string($conn, $mypassword) . "';";
$result = $conn->query($sql);
if ($result->num_rows >0) {
echo "login successful";
} else {
echo "Username or Password incorrect";
}
$conn->close();
?>
I hope this will work for you try this:
if (response=="usernames or Password incorrect") {
window.location.href = "index.php";
}
else if (response=="login successful")
{
window.location.href = "login_success.html";
}
else { }
Use this code in ajax success. Actually you are using simple ECHO in PHP and using response.text in ajax success.
UPDATE:
you are using = sign for comparing it should be == operator for compare.
UPDATE 2:
i suggest to use status as true false not long string in php like:
if ($result->num_rows >0) {
echo true;
} else {
echo false;
}
Than in ajax response:
if(response == true){
// Success url
}
else {
// failure url
}
The variable success will be undefined inside the success callback function. So the next line will not be executed. So the page will not be redirected. According to your php code , you need to check if response is equal to the corresponding result of not.

Save data from dataTable to database

how can I save all my datatable data to my database?, im using jquery and php to do this dynamic.
$('#bot_guar').click( function () {
//var rows = $("#tabla1").dataTable().fnGetNodes();
var oTable = $('#tabla1').DataTable();
var data1 = oTable.rows().data();
//alert(data1.length);
$.ajax({
type:"POST",
dataType:'json',
url: "<?= Router::Url(['controller' => 'cab_facturas', 'action' => 'addDetFac'], TRUE); ?>/",//teacher//getdata/3
data:data1,
success: function(data){
alert(data);
}//success
});
});
this is what I had to POST the data from datatable, but I dunno why is the function to send to my php function that will insert.
You can consume the data object sent from your AJAX call as POST parameters or query string parameters depending on your settings. Consider you want to access firstname, lastname and email from your server side script. It can be done using:
$firstname = _POST['firstname'];
$lastname = _POST['lastname'];
$email = _POST['email'];
Now, Connect to your database and insert this data through your php script:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Its good practice to send a response to your call back functions so you can do this:
echo json_encode(array('status'=>"Success", message=""));
Your call back function will contain the data sent back from the php file. Since we are sending back a json string, we can make an object of it like this:
var myCallbackFunction = function(data){
var d = $.parseJSON(data)[0];
if(d.Status=="Success"){
//reload your datatable ajax
}else{
alert(d.message);
}
}
I hope that helped!

Posting Ajax Data to PHP REST SERVICE

I know this question has been asked before but none of the solutions I have tried work, I wrote a php rest service which I'm hosting on a server, I used advanced rest client data on chrome to test my rest service and it works, it posts data to the database, but when I wrote my own client in an ajax post below the browser complains of
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8383' is therefore not allowed
access.
I have tried adding a header to my php code still doesn't work i get another error..., I'm just wondering what I'm doing wrong?
>// MY PHP REST SERVICE
<?php
$servername = "localhost";
$username = "root";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
// Insert data into data base
$sql = "INSERT INTO UserData.register (name, surname, email, password)
VALUES ('$name', '$surname', '$email','$password')";
if ($conn->query($sql) === TRUE) {
$json = array("status" => 1000, "msg" => "Done User added!");
} else {
$json = array("status" => 0, "msg" => "Error adding user!");
}
header('Content-type: application/json');
echo json_encode($json);
$conn->close();
}
> //MY java script ajax client doing the posting.
<script type="text/javascript">
function RegisterUser() {
var name = $("#name").val();
var surname = $("#surname").val();
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "http://xxx.xxx.xxx.xxx/signup.php",
data: '{"name":"' + name + '","surname":"' + surname + '","email":"' + email + '","password":"' + password + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d)
}
});
}
</script>
Try Using .htaccess file
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
CORS guide is here which lists all the possible ways to solve the problem regarding CORS.

How do I connect my ajax post to php and mysql?

I spent hours testing all my code, step by step, and still can't make it work. I eventually got the php file to send a test object to the mysql database but I still can't get the jQuery ajax post to connect to php. Can anyone spot the issue? I get the "500 internal server error" message when I run the code.
Javascript:
var jsonEntry = {"timestamp":"2015/01/21 22:18:00","note":"hi there","tags":["one", "two"]};
// send json converted object to php file via ajax
$("#sendButton").click(function () {
$.ajax({
url: 'php/ajax.php',
type: 'POST',
dataType: 'JSON',
data: jsonEntry,
error :
function(xhr, status, error) {
alert(xhr.status);
alert(error);
},
success :
function(data) {
console.log('send success');
}
});
});
PHP code from "ajax.php:"
<?php
if(isset($_POST["data"])) {
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$timeStamp = $obj[timestamp]; //added semicolon here
$note = $obj[note];
$tags = $obj[tags];
//Connecting to a database
//Connection info
$hostname = "localhost";
$username = "root";
$password = "root";
//Code to connect
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Select database to work with
$selected = mysql_select_db("notes", $dbhandle)
or die("Could not select examples");
//Execute SQL query and return records
mysql_query("INSERT INTO notes (dateAndTime, noteBody, noteTags) VALUES ('$timestamp', '$note', '$tags')");
// Close the connection
mysql_close($dbhandle);
}
?>
UPDATE:
I have added the semicolon where needed in the php file but now get error 200, "SyntaxError: JSON Parse error: Unexpected EOF."
I think the problem is a missing semicolon here:
$timeStamp = $obj[timestamp]
With this error fixed, you switch this line:
$json = file_get_contents('php://input');
to:
$json = $_POST['data'];

Categories

Resources