PHP Ajax live search only working on localhost - php

I'm creating a search form on a navbar to search for users on a mysql table.
I used a script i found online and, when i used it on localhost it all went fine. As soon as i typed the first letter of a name, i would instantly get the results.
But now, i placed the website on a webserver and what happens is the following:
I write 1 to 3 letters and nothing happens;
I write 4/5 letter and a error appears (Fatal error
: Call to undefined function mysqli_stmt_get_result() in
/home/pg22933/public_html/jade/backend-search.php
on line
68);
I write almost the full name of a user, and the result finally appears.
This is the file where i have all the code to do this:
<?php include('headers.php'); ?>
<script type="text/javascript">
function updateentrada(value, id)
{
console.log(value, id);
if(value == 1)
{
$.ajax({
type: 'post',
url: 'loaddata.php',
data: {
idconvidado:id,
entrada: 0
},
success: function () {
location.reload();
}
});
}
else if (value == 0)
{
$.ajax({
type: 'post',
url: 'loaddata.php',
data: {
idconvidado:id,
entrada: 1
},
success: function () {
location.reload();
}
});
}
}
</script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "jade");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if(isset($_REQUEST['term'])){
// Prepare a select statement
$sql = "SELECT * FROM convidados WHERE nome_convidado LIKE ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_term);
// Set parameters
$param_term = $_REQUEST['term'] . '%';
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
// Check number of rows in the result set
if(mysqli_num_rows($result) > 0){
// Fetch result rows as an associative array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$idconvidado = $row["id_convidado"];
$nome = $row["nome_convidado"];
$entrada = $row["entrada_convidado"];
if ($entrada == 1){
echo "<button value='". $entrada ."' name='". $idconvidado . "' onclick='updateentrada(this.value, this.name)' class='btnsearch'>" . $nome . " <i class='fa fa-check-circle-o check aria-hidden='true'></i></button>";
}
else if ($entrada == 0){
echo "<button value='". $entrada ."' name='". $idconvidado . "' onclick='updateentrada(this.value, this.name)' class='btnsearch '>" . $nome . " <i class='fa fa-circle-o check aria-hidden='true'></i></button>";
}
}
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// close connection
mysqli_close($link);
?>
What am i doing wrong?

http://php.net/manual/en/mysqli-stmt.get-result.php
It requires the mysqlnd driver, you need to install it on your web server

Related

ajax receives response from php but can not use with ajax

I have the following php and ajax code when I check in google chrome with ctrl+shift+I in network tab it shows the response as <{"response" : "2"} but this response can't be assigned to <h3> having id as respo
my php is
<<?php
$id = $_POST['reccount'];
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "testsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "SELECT * FROM paper WHERE ID=$id";
if(mysqli_query($link, $sql)){
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($result)) {
$data['response']= $row['response'];
$data['ansnum'] = $row['q_no'];
}
echo json_encode($data);
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
and ajax is
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
data: {reccount: reccount},
dataType:"JSON",
success: function(data){
alert (data.response);
$('#respond').text(data.response);
}
}) ;
and html is
<h3 ID="respond"style="margin-left:30px;">response</h3>
If the response from your PHP is:
<{"response" : "2"}
This would be an incorrectly formatted JSON string. This would be created by the extra < you have at the beginning of the document. I would advise you have the following PHP Opener:
<?php
This should correct the issue so the JSON Response would be:
{"response" : "2"}
It will be properly parse at that point.
Example
<?php
$id = (int)$_POST['reccount'];
$link = mysqli_connect("localhost", "root", "", "testsite");
header('Content-Type: application/json');
if($link === false){
die("{\"error\": \"Could not connect. " . mysqli_connect_error() . "\"}");
}
$sql = "SELECT * FROM paper WHERE ID=$id";
if(mysqli_query($link, $sql)){
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($result)) {
$data['response']= $row['response'];
$data['ansnum'] = $row['q_no'];
}
echo json_encode($data);
} else {
echo "{\"error\": \"Unable to execute $sql. " . mysqli_error($link) . "\"}";
}
mysqli_close($link);
?>
In my example, I cast the POST data to Integer to help ensure a malicious user does not get to send anything other than a digit. I also only send JSON data, even when sending an error. Using the header() helps define the data for the browser.
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
data: {reccount: reccount},
dataType:"JSON",
success: function(data){
console.log(data);
if(data.error !== undefined){
alert(data.error);
} else {
$('#respond').text(data.response);
}
}
});
Hope that helps.

AJAX responseText is unreliable

I'm trying to send form data to a php script without a redirect.
The problem i have is that the responseText function doesn't seem to work reliably.
NOTE: The PHP script works as intended. And is writing to the database and so on.
AJAX code:
$(document).ready(function(){
$('#registreer').click(function(){
$.ajax({
type: "POST",
url: "assets/PHP/registreer.php",
data: $('form').serialize(),
success: function(jqXHR, textStatus) {alert("Succes" + jqXHR.responseText);},
error: function(jqXHR, textStatus) {alert("Error" + jqXHR.responseText);}
})
});
});
PHP code:
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ($passwordPost != $passwordRetypePost) {
echo "Paswoorden zijn niet hetzelfde!";
} else {
if (!($stmt = $conn->prepare("SELECT * FROM `Gebruikers` WHERE `Email` = ?"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
} else {
$stmt->bind_param("s", $emailPost);
$stmt->execute();
$stmt->bind_result($id, $email, $paswoord, $rol);
$stmt->store_result();
if ($stmt->num_rows > 0) {
echo "Email bestaat al!";
} else {
$stmt->close();
$hash = password_hash($passwordPost, PASSWORD_DEFAULT);
if (!($stmt = $conn->prepare("INSERT INTO `Gebruikers`(`Email`, `Paswoord`) VALUES (?,'$hash')"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
$stmt->bind_param("s", $emailPost);
$stmt->execute();
echo 'Gelukt!';
}
}
}
$mysqli->close();
So for some reason the only response i can get is:
echo "Email bestaat al!";
All the other echo's do not seem to be working on my HTML page. No matter what i try.
Any suggestions are welcome!
You receive that message because you're checking if there is already the $emailPost in the database and the answer is true. This is why you've received this message.
Have you tried with another email adress ?
Also, in your jQuery callbacks (success and error) you will always receive "success" things, because you doesn't throw any error, in any case, on the PHP side.
You should better use something like throw new Exception('Prepare failed[...]') on every 'echo' or 'die' statement that you have in php, except for the success one where you can correctly use echo 'Gelukt!';.

Update Text Value in PHP form display using jQuery & MySQL database

I have a table display and I want to enable users to edit the values of the table in a live way using jQuery. The table is simple, it just has 1 column with a list of names. I have it all built out but at the moment the table doesn't update the value. All the code is below, I am still learning everything so it's probably not written very well/correctly! Thanks in advance.
Form Display:
<?php
echo "<div class=\"table-responsive\"><table class=\"table table-striped\">";
echo "<thead><tr><th>Employee Name</th><th></th></tr></thead><tbody>";
require_once 'connectionsettings.php'; // Gets connection settings
$sql = "SELECT id, employees FROM Employees ORDER BY employees ASC";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// what it's saying is that if there's rows do something
while($row = $result->fetch_assoc()) {
// now it's saying get the data and put it in rows
echo "<tr><td data-id='{$row['id']}' contenteditable=\"true\">" . $row["employees"] . "</td><td><span data-id='{$row['id']}' name='remove_{$row['id']}' class='employee glyphicon glyphicon-remove' aria-hidden='true'></span></td></tr>";
}
}else{
echo "No Employees! Let's add some.";
}
$mysqli->close();
echo "</tbody></table></div>";
?>
Jquery Info:
$(function(s){
$("td[contenteditable=true]").blur(function(){
var id = $(this).attr("id") ;
var name = $(this).text() ;
var formURL = "updateemployeename.php";
$.ajax({
url : formURL,
type: "POST",
data : {name: name, id: id},
success:function(data, textStatus, jqXHR)
{
$('#successmessage2').slideDown('fast').delay(1500).slideUp('fast');
$('div#employeedisplay').hide();
$('div#updatedemployeedisplay').load('employeedisplay.php').fadeIn(3000);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
});
s.preventDefault(); //STOP default action
});
SQL Info:
<?php
require_once 'connectionsettings.php'; // Gets connection settings
$name = htmlspecialchars(trim($_POST['name']));
$id = htmlspecialchars(trim($_POST['id']));
$sql = "UPDATE Employees SET employees='$name' WHERE id='$id'";
if($mysqli->query($sql) === TRUE) {
echo "status updated successfully";
}else{
echo "Error updating status" . $mysqli->error;
}
$mysqli->close();
?>

Getting 0 as a value sending to my database during an AJAX call form submission

I am trying to send the user id and the value 'Approved' through the AJAX call to my prepared statement to send into my database. As of right now I am getting the id part of this correctly. However, the value for the Approved part is sending and updating my database as a 0.
Does anyone see why?
My Form
$con = mysqli_connect("localhost", "root", "", "db");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
?>
<form action="" method="POST" id="status">
<input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id'/>
<?php
if ($pending_firstname == true) {
echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" .
"Username - ". $pending_username . "</br></br>"
//echo print_r($_POST);
?>
<button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button>
<button class="deny" type="submit" form="status" name="deny" value="<?=$pending_id;?>">Deny</button>
</form><br><br><br>
My AJAX call
$(document).ready(function () {
$('.approve').click(function () {
$.ajax({
url: 'userRequest_approve.php',
type: 'POST',
data: {
id: $(this).val(), //id
status: 'Approved' //status
},
success: function (data) {
//do something with the data that got returned
$("#success").fadeIn();
$("#success").show();
$('#success').html('User Status Changed!');
$('#success').delay(5000).fadeOut(400);
},
//type: 'POST'
});
return false;
});
});
My Prepared Statement
$pending_id = $_POST['id'];
$status = $_POST['status'];
$con = mysqli_connect("localhost", "root", "", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("UPDATE user_requests SET status=?, date_responded=NOW() WHERE id=?");
if ( false===$stmt ) {
// Check Errors for prepare
die('User Request update prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('ii', $status, $pending_id);
// comment added by php-dev : should be false === $stmt->bind_param ...
if ( false===$stmt ) {
// Check errors for binding parameters
die('User Request update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
// comment added by php-dev : should be false === $stmt->execute ...
if ( false===$stmt ) {
die('User Status update execute() failed: ' . htmlspecialchars($stmt->error));
}
By ajax form you are providing "status" as string with value "Approved" to server while you are assuming it integer in binding. Just change "status" in ajax code to '1'
Based on the other answer it clicked what I was doing wrong. I had my php parameters set as both being integer when it needed to be 'si' not 'ii'.

Sending AJAX call to a php file to INSERT a value into my database

I I have a db table called user_requests where I have a column called 'status'. I output the status' on the page userRequests.php. I output all of the user requests via while loops. What I am trying to accomplish is being able to hit the button 'approve' or 'deny' to change the 'status' in my user_requests table. I am trying to do this with AJAX and this is my first attempt at making an AJAX call. When I click on approve I want it to grab the id of the user I selected Accept next to and then carry the value of 'Accept' and INSERTthat into my user_requests db table in the 'status' row.
As I have it now nothing happens at all. Does anyone see anything wrong with how how I am trying to do this?
userRequests.php
<?php
$con = mysqli_connect("localhost", "root", "", "db");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
?>
<form action="" method="POST" id="status">
<input type='hidden' value='<?php echo $pending_id; ?>' id='pending_id'/>
<?php
if ($pending_firstname == true) {
echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" .
"Username - ". $pending_username . "</br></br>"
?>
</form>
<button id="approve" type="submit" form="status" name="approve" value="Approved">Approve</button>
<button id="deny" type="submit" form="status" name="deny" value="Denied">Deny</button><br><br><br>
<?php
;} else {
echo "There are no Pending Requests at this time.";
}
}
}
}
?>
AJAX call
<script>
$(document).ready(function(){
$('#submit').click(function(){
var id_val=$("#pending_id").val();
var id_val=$("#approve").val();
$.post("userRequest_approve.php", $("#status").serialize(), function(data) { });
$('#success').html('User Status Changed!');
$('#success').hide(2000);
});
});
</script>
userRequest_approve.php file
<?php
require_once 'core/init.php';
$term = mysql_escape_string($term); // Attack Prevention
$pending_id = $_POST['id'];
$status = $_POST['approve'];
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("INSERT INTO user_requests (status, date_responded) VALUES (?, NOW())");
if ( false===$stmt ) {
// Check Errors for prepare
die('User Request update prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('s', $status);
if ( false===$stmt ) {
// Check errors for binding parameters
die('User Request update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
if ( false===$stmt ) {
die('User Status update execute() failed: ' . htmlspecialchars($stmt->error));
}
?>
I think you javascript is the weakest part of your code, here is some simple example for your ajax call, just change some values around and try it out
$('.approve').click(function(){
$.ajax({
url: '/whereEver/itNeedsToGo',
data: {
id: $(this).val(), //the value of what you clicked on
status: 'Approved' //you clicked on it so you know the status might aswell hardcode it
},
success: function(data) {
//do something with the data that got returned
},
type: 'POST'
});
});
EDIT: i would make it a little "dirty" to achief what you want... there are more ways to solve it but for now i will do it the easy way....
change ID into class
<button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button> give the approve button the value of the pending ID..... and i edit the ajax call above accordingly....this should work

Categories