Why isn't the response from Ajax showing? - php

I'm passing values using ajax from a web page to a php file. The purpose is to pass database credentials to be able to test the database connection and get the result in return. I'm passing server name, username and password to the php file. The problem is that I'm not able to see the database connection response from the php file.
This is how I call the function within document ready:
$('#dbconn').click(db_connect)
Here is my ajax code:
function db_connect(dbserver, dbuser, dbpassword) {
var dbserver;
var dbuser;
var dbpassword;
dbserver = $('input:dbserver').val();
dbuser = $('input:dbuser').val();
dbpassword = $('input:dbpassword').val();
$.ajax({
url : "script/create_db.php",
type : "POST",
cache : false,
data : {
dbserver : dbserver,
dbuser : dbuser,
dbpassword: dbpassword,
success: function(result){alert ("response")}
}
});
};
And this is my php code:
$servername = $_GET["dbserver"];
$username = $_GET["dbuser"];
$password = $_GET["dbpassword"];
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
echo "Connection succsess";
}
Any help is highly appreciated

success: function(result){alert ("response")}
When you get the response you alert the string "response".
You ignore the value of result entirely.
You don't see the response because you aren't looking for it.

Related

Ajax call with DB Connection 'include' gives POST 500 error

Does anyone know why when I move a database connection 'include' out of a function and place it at the beginning of the PHP file that I get a POST 500 error? The exact same database connection 'include' works perfectly within the function. Here is the code that causes the error:
<?php
include($_SERVER['DOCUMENT_ROOT'].'/phpscripts/set_path.php'); // DB Connection Path
include 'mysqli_connect_sa.php'; // DB Connection
if(isset($_POST['row']))
{
$uid = $_POST['row'];
$response_bdls = getBDLs($uid);
$response_cg = getCompetencyGaps($uid);
echo json_encode(array($response_bdls, $response_cg));
}
Just in case you want to see the Ajax call:
$.ajax({
type: "POST",
url: '/phpscripts/ss_scbdls.php', //
data: {row : row},
success:(function(response){
response = JSON.parse(response);
loadSC_bdls(response[0]);
loadSC_cg(response[1]);
})
});
Thank you for any insights or direction you can provide.
Requested Information #1
Here is the mysqli_connect_sa.php Content:
// SA Database access information
$hn = 'localhost';
$db = 'xxxxxxxx';
$un = 'xxxxxxxx';
$pw = 'xxxxxxxx';
// Connect to DB
$dbc = new mysqli($hn, $un, $pw, $db);
// Set the Encoding
mysqli_set_charset($dbc, 'utf8mb4');
Function:
function getBDLs($candidate_id)
{
$sc_bdls = [];
$sql_query_bdls = "SELECT bdl_increment AS id, learn_load, start_date, target_date, completed_date, bdl_20, bdl_10, bdl_70, cg, cg_orn, cg_tit, cg_lj FROM bdls INNER JOIN competency_gaps USING (cg_id) WHERE bdls.candidate_id = $candidate_id";
$result_bdls = $dbc->query($sql_query_bdls);
while($bdls = mysqli_fetch_assoc($result_bdls)) {
$sc_bdls[] = $bdls;
}
mysqli_free_result($result_bdls);
return $sc_bdls;
}

How to ask a user input and use it as a parameter for a stored procedure in a PHP script?

Sorry for the newbie question, but I have this task which kind of got me stuck.
So, I made a database in PhpMyAdmin, created a table with data : Products(id, name, city) and created a stored procedure that will actually do a query on the table to find out the product with a certain name (which will be input-ed by the user on the web page). My stored procedure is: proc_test and takes one VARCHAR paramter.
So, how can I do this in a php script? How can i ask the user for some data, (on the site he should have like a box to type it) then click a search button, and get redirected to the page with the query results. This is my code so far:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CALL proc_test('pencil');";
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['numec'] . "<br/>";
}
}
$conn->close();
?>
Here, of course, I manually give the parameter in the script. But I don't know how to change this and ask for a user input instead. Any help is welcome!
You can use ajax to send the data from your website to the php file where you can search for it in the database and send that data back to the user. In my example, the data is being displayed on the same webpage. You could echo the link to the website and redirect the user on the webpage using JavaScript if you really wanted to but my example is just a proof of concept.
index.html
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input required type="text" id="user_input">
<button onclick="sendData()">Search</button>
<p id="result"></p>
<script>
function sendData() {
var var_params = $('#user_input').val();
$.post('test.php', {params: var_params}, function(data) {
document.getElementById('result').innerHTML = "Your search result: " + data;
});
}
</script>
</body>
</html>
test.php
<?php
if(isset($_POST['params'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$param = mysqli_real_escape_string($conn, $_POST['params']);
$sql = "CALL proc_test('$param');";
if($result = mysqli_query($conn, $sql)) {
while($row=mysqli_fetch_assoc($result)) {
echo $row['numec']. "<br/>";
}
}
$conn->close();
}
?>

Simple MySQL login with PHP and AJAX requests

I'm trying to create a very simple MySQL login function using PHP. The username and password are posted the PHP through AJAX. The AJAX function is:
function login(){
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
$.ajax({
url : "login.php",
type : "POST",
data : {
username : user,
password : pass
},
success : function(response){
alert(response);
},
error : function(response){
alert(response);
}
});
}
The login script:
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$user = $_POST['username'];
$pass = $_POST['password'];
$query="SELECT * FROM Users WHERE email = '$user' AND password ='$pass' LIMIT 1";
$result = $conn->query($query);
$count = $result->num_rows;
if($count == 1){
echo "success";
}else{
echo "incorrect login details";
}
$conn->close();
?>
It seems that $count is always zero, even when the username and password are correct. I've verified that the username and password are being successfully retrieved in PHP.
An even simpler query, SELECT * FROM Users also returns a count of 0.
Attempting to echo or var_dump $result results in object Object being displayed.
Can anyone see any glaring issues with this code? A fresh set of eyes would be greatly appreciated.
Note: This simple function is not designed to be secure, hence the insecure query formatting.
I'd suggest changing the following to strings and running the PHP script. If the strings appear in your DB, you can then rule out if it's caused by the PHP script, in which case it will be the html and ajax elements.
//$user = $_POST['username'];
//$pass = $_POST['password'];
$user = 'userTest';
$pass = 'userPass';

Unable to connect to MY SQL DB in Ajax call using PHP

I am performing a DB operation after making an ajax call using php,
1) I see in fiddler that the request and response to the PHP (ajax call) are fine but and 2) I see the error "Access denied for user 'root'#'localhost' (using password: NO" in Fiddler.
I am not trying to connect to root but to a different user.
Here is the view.php file where ajax call is initiated:
$.ajax({
url: 'delete_entry.php',
data: "id="+del_id,
type: 'post',
success: function(output) {
alert("Success");
//document.getElementById("test1").innerHTML = output;
}
});
I recieve the alert message "Success" though.
Code in delete_entry.php:
<?php
$servername = "localhost";
$username = "testdb";
$password = "testdb";
$dbname = "testts";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Connection Failed";
die("Connection failed: " . $conn->connect_error);
}
$id=$_POST['id'];
echo $id; // I get a proper Id here
$delete = "DELETE FROM ExpenseTable WHERE Id='"+$id+"'";
$result = mysql_query($delete) or die(mysql_error());
?>
Please help as I do not understand why the mysql db is trying to connect to root eventhough I specify the db detais as "testdb".
I am able to connect to the same db with these credentials in my view.php
You are not using your created DB connection when you pass the sql query to the DB. Use the mysqli_query method as below..
mysqli_query($conn,$delete);

Angular $http - function/response undefined

I've been unable to retrieve data from a json or php file because angular keeps yelling at me that either the function or response is undefined.
I want to pull up the navigation items from MySQL, when it failed to load php I've put the contents in a regular json file to see what was the problem it seems something in angular itself.
PHP:
<?php
header('Content-type:application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = 'SELECT * FROM navigation';
$result = $conn->query($sql);
$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
?>
Which results in:
[{"nav_id":"0","nav_name":"Home","nav_link":""}, {"nav_id":"1","nav_name":"Contact","nav_link":"contact"}]
So far so good?
Here's my angular code that gets the file:
(function() {
var app = angular.module("headerControl", []);
app.directive("headerNavigation", function() {
return {
retrict:'E',
templateUrl:'views/partials/header-navigation.html'
};
});
app.controller("navController", function($scope, $http) {
$scope.navlist = {};
$http.get('phpservices/nav.php')
.success(function(response) {
alert('success');
})
.error(alert('error'));
});
})();
When I load the page it first gives me the error response and after that the success response... in the console angular tells me this:
Error: [ng:areq] http://errors.angularjs.org/1.4.2/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20undefined
whats wrong about this? I can't seem to figure it out...
The problem is that you are not passing error callback function properly. It should be:
.error(function() {
alert('error')
});
Otherwise you just invoke alert immediately (note ()) and since it doesn't return anything (so it "returns" undefined) error handler receives undefined in it. However, it expects a function. That's why you get this error.

Categories