Reputation: 1489
I am absolutely new to jQuery and ajax. Currently I am trying to create a table on my local sql server from a javascript file from which I am posting the statement to .php file to execute the statement.
.js file:
function executeStatement(sqlStatement){
$.ajax({
type: "post",
data: sqlStatement,
cache: false,
url: "api.php",
dataType: "text",
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
success: function ()
{
alert ("Success!!");
}
});
}
.php file:
require_once('PhpConsole.php');
PhpConsole::start();
debug('HERE!!!');
$sqlStatement = $_POST['sqlStatement'];
$host = "*****";
$user = "*****";
$pass = "*****";
$databaseName = "db_user_data";
// Create connection
$con = mysqli_connect($host, $user, $pass, $databaseName);
// Check connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
$con->query($sqlStatement);
header('Location: success.php');
}
I use PHP Console to debug .php files but in this case even the first log 'HERE!!!' is not printed to the console so I am wondering whether it even reaches this .php file. Anyway the event success
within executeStatement method is reached and 'Success' printed even though there are no changes in the database.By the way the .php file is also executed on the local server. Does someone has any ideas where the problem can be??
Thanks in advance
Upvotes: 1
Views: 330
Reputation: 58
There is a typo in your PHP code at the "$pass" variable:
require_once('PhpConsole.php');
PhpConsole::start();
debug('HERE!!!');
$sqlStatement = $_POST['sqlStatement'];
$host = "*****";
$user = "*****";
**$pass = "*****";**
$databaseName = "db_user_data";
// Create connection
$con = mysqli_connect($host, $user, $pass, $databaseName);
// Check connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
$con->query($sqlStatement);
header('Location: success.php');
}
EDIT: Here is my revised JS code - this works perfectly for me as I am able to pass the code from an AJAX call to the PHP code and back. Try this:
var sqlStatement = "sqlStatement=SQLSTATEMENTHERE";
$.ajax({
type: "POST",
data: sqlStatement,
cache: false,
url: "api.php",
success: function ()
{
alert ("Success!!");
}
});
Place the variable outside of your function and the ajax call inside to replace the old one. As for the PHP, i'll check that out in a second.
Upvotes: 2