AJAX responseText is unreliable - php

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!';.

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.

PHP Ajax live search only working on localhost

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

ajax to submit php form to database, ajax part doesn't work

I'm very new to ajax so I followed a tutorial but I can't get it to work. I tried search this forum for an answer but with no luck..
HTML (a bit stripped down from classes and bootstrap-stuff)
<form id="editUserForm" role="form">
<input id="edit_employeenr" type="text" name="employeenr">
<input id="edit_name" type="text" name="name">
<select id="edit_membertype" name="membertype">
<option value="1">Admin</option>
<option value="2">Employee</option>
</select>
<input type="submit" value="Save">
</form>
<div id="editUserMsg">Successfully updated!</div>
JS
$(document).ready(function() {
$("#editUserMsg").hide();
$("#editUserForm").submit(function(event) {
event.preventDefault();
submitUserEdit();
});
function submitUserEdit(){
var dataString = $("#editUserForm").serialize();
$.ajax({
type: "POST",
url: "user_edit_process.php",
data: dataString,
success: function(text){
if (text == "success"){
userEditSuccess();
}
}
});
}
function userEditSuccess(){
$("#editUserMsg").show().delay(5000).fadeOut();
}
});
PHP (user_edit_process.php)
<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];
$stmt = $link->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?");
$stmt->bind_param("isi", $employeenr, $name, $membertype);
$stmt->execute();
if ($stmt) {
echo 'success';
} else {
echo 'fail';
}
?>
if i put the $("#editUserMsg").show().dealy(5000).fadeOut(); just above the $.ajax the message appears, so that must mean that the ajax code isn't working correct. Any suggestions?
EDIT Solved. I had forgotten to include the file where the variable $link wes defined.
It seems that you have a problem in your either in your prepare statement or in the bind_parameter. You should always check for error, so I suggest you do like this to check for errors:
<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];
if (!($stmt = $mysqli->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (! $stmt->bind_param("isi", $employeenr, $name, $membertype)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>
and then in you JS, add this to your success method:
console.log(text);
Check your Firefox console (Ctrl-Shift-Q), and if there is an error you would find it under "Network" -> Click the "user_edit_process.php" in the list -> and in the right window under "Preview".
Is that all code that you have in user_edit_process.php?
Is the $link variable properly initialize?
You can try to comment part of your code in PHP file, and write something like below to test if you Ajax code work properly:
<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];
// $stmt = $link->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?");
// $stmt->bind_param("isi", $employeenr, $name, $membertype);
// $stmt->execute();
if ($employeenr) {
echo 'success';
} else {
echo 'fail';
}
And then if you type something in first employeenr form input it should show Successfully updated!. If you leave this input empty and send form, it shouldn't show.

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'.

INSERT INTO mySQL from client side with AJAX

I want to insert data from the Client side to a remote mySQL database
I am calling a function and passing a variable into it.
function uploadMetrics(email){
var email;
$.ajax({
type: 'post',
url: 'php/insertConvertData.php',
data: {
data: {"email" : email },
//data:email,
},
success: function(result) {
console.log(result);
}
});
}
On the server I have a php file
$user = $_POST['email'];
echo $user;
echo '<pre>';
print_r($_POST); // for viewing it as an array
var_dump($_POST); // for viewing all info of the array
echo '</pre>';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO cms_conversion_funnel (email)
VALUES ('" . $user . "')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
The code runs fine and I can connect to the database and run the insert but in inserts an empty string.
I dumped out the value of 'email' to the console and got this:
(
[data] => Array
(
[email] => teretst#gmail.com
)
)
array(1) {
["data"]=>
array(1) {
["email"]=>
string(17) "teretst#gmail.com"
}
}
It seems like there is a value in the email variable but it is not being picked up an passed into the insert statement. Can anyone help, I am new to php and AJAX.
Because it's $_POST['data']['email'], not $_POST['email'].
Use data: {"email" : email }, email is a parameter, you don't have to declare it again:
function uploadMetrics(email){
$.ajax({
type: 'post',
url: 'php/insertConvertData.php',
data: {"email" : email },
success: function(result) {
console.log(result);
}
});
}
It is because you are taking the variable email as input and then redeclaring the same email which is again turning it empty. Please remove
Var email.
Next thing you have to fetch as $_POST['data']['email']

Categories