Reputation: 321
In my html I have a simple ajax that's inside a function that gets called on a button press. I want the php script that's called to insert the javascript variable sent into a database.
var myval = 'testuser'; // generated by PHP
$.ajax({
type: 'POST',
url: 'testfile.php',
data: {'variable': myval},
});
In my testfile.php I have tried numerous things to insert into the database but with no luck. I know that ajax is working because doing just the bellow works fine with no errors.
<?php
$myval = $_POST['variable'];
echo $myval;
?>
I tried doing this bellow first with global variables. Then even tried putting in the values manually and I kept getting the 500 error even though I have the exact same code in another script (not being called by ajax) and it works fine.
$db = new PDO('mysql:host='. DB_HOST .';dbname='. test_user, DB_USER, DB_PASS);
So I tried opening it a different way.
$con = mysqli_connect('localhost','username,'pass','newdb');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
and that worked fine. However putting in the global variables causes it not to work.
Then I tried to insert to a table.
INSERT INTO send (user_id)
VALUES ($myval);
and I get a 500 error again.
I try accessing the php file directly (testsite.com/testfile.php) and get a blank page. Viewing source gives me nothing.
What am I doing wrong as to keep getting these errors?
Upvotes: 0
Views: 1338
Reputation: 2692
PHP:
<?php
//Enter your database connection details here.
$host = 'localhost'; //HOST NAME.
$db_name = 'dbname'; //Database Name
$db_username = 'root'; //Database Username
$db_password = ''; //Database Password
try
{
$myval = $_POST['variable'];
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
$query = $pdo->prepare('INSERT INTO send (user_id) VALUES (?)');
$query->bindValue(1, $myval);
$query->execute();
echo $myval;
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
?>
Javascript:
var myval = 'testuser'; // generated by PHP
$.ajax({
type: 'POST',
url: 'testfile.php',
data: {variable: myval},
});
Don't add quotes around the variable name. I've provided a php script that should work the way you want it to, comment back if you still need help.
Upvotes: 1