I'm trying to get the value of the checkbox using an Ajax/Javascript response which passes the value to PHP so i can perform a query based on the value ("Checked","Not checked")
<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">
The Javascript/Ajax code for the function "updateStatus" is as followed
function updateStatus(id,value) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id + "&checked="+value, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null)
The PHP function inside functions/ajax.php
if(isset($check) and $check == 'update_status' and isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
echo "Checked";
} elseif($checked == false) {
echo "Not checked";
} else {
echo "Invalid response";
}
when using this code it always returned "Checked" any idea why ?
In the JS. value will be true or false. When you stringify either of those, you will get a string ('true' or 'false').
Thus $_GET['checked'] will be either "true" or "false" both of which == true.
To fix this on the PHP side, compare to the string "true" and the string "false"; not the boolean.
You are getting $_GET['checked'] as a String.
Change to something like:
if($checked == "true") {
echo "Checked";
} elseif($checked == "false") {
echo "Not checked";
} else {
echo "Invalid response";
}
This might help you in your answer https://stackoverflow.com/a/4228827/90648
You can try replacing the code
"&checked="+value
with
(value ? "&checked=true" : '')
This way you will only send the value true when it is checked, and not send anything (which you can check in PHP with isset)
or you can go with
(value ? "&checked=true" : '&checked=')
which will again, not send anything, thus empty string will be interpreted as false.
Related
I'm trying to create an AJAX script that calls a PHP script to check the entered username and password. The PHP script simply returns "true" if the entered details are correct and false if otherwise.
At the end of the AJAX script, I've placed a simple if else condition for true/false returns. Every time the PHP script returns true, the AJAX scripts jumps to else part overlooking the if.
I know there might be some stupid mistake or it is probably a ludicrous question but I'm stuck on it since many days. Stack is the last resort!
Here's my AJAX SCRIPT
function authenticate()
{
//XMLHttpRequest Object
var xhttp = new XMLHttpRequest();
var email = document.getElementById('email').value;
var pass = document.getElementById('pass').value;
var url = "php/user_authentication.php";
var url2 = "php/user_authentication.php?email=" + email + "&pass=" + pass;
var result = "";
xhttp.open("GET", url2, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
xhttp.onreadystatechange = function f()
//f() would be called everytime the onreadystatechange property changes the value
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
alert(this.responseText);
result = this.responseText;
if (result == "true")
//!! -> NOT ENTERING THIS PART EVEN WHEN result="true" !!
{
alert("Inside true");
document.getElementById('email_pass').innerHTML = 'login successful';
} else {
document.getElementById('email_pass').innerHTML = 'login failed';
alert("2 " + xhttp.responseText);
}
}
}
}
Here's the PHP script [user_authentication.php]
<?php
//User Authentication
//1.Including the database_connection.php
include "database_connection.php";
//2.1.Fetching the user id and password from the form
$email = $_GET['email'];
$pass = $_GET['pass'];
//2.2.Defining th select query
$qry = 'select * from user_auth where Email="'.$email.'" and Password = "'.$pass.'"';
//3.Executing the query and storing it to result
$result = mysqli_query($connection,$qry);
//authenticating
if(mysqli_num_rows($result)>0)
{
echo "true";
}
else
{
echo "false";
}
?>
Obligatory comment about prepared statements in php and sql PHP Manual.
But I would try to cast the comparison
if (result == "true")
to boolean like so
if (Boolean(result) === true)
I admit, my knowledge of ajax and JS is limited but in such cases Ive learned to not trust JS automatic type casting. Note also that I would definately use 3x= if we are casting result to a boolean.
The issue was,
I was getting some extra spaces along with my responseText that made the following condition false every time I got "true" in my responseText.
if (result == "true")
//Turns false because result.length = 11 (extra empty spaces due to some unknown reasons)
The solution was as follows :
Changing the return value in my PHP to 't' and 'f'
Using the slice method to slice the first variable of responseText to eliminate all the white-spaces in the string and then making further comparison
xhttp.onreadystatechange = function f()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
result = this.responseText;
var temp = result.slice(0,1);
//This will only select the first char in the result string
if (temp == "t")
document.getElementById('email_pass').innerHTML = 'login successful';
else
document.getElementById('email_pass').innerHTML = 'login failed';
}
}
$result not getting "true" make sure or double check below:
Html element IDs are (email, pass)
Database connection work properly,
$qry: select query related fields have matched with table columns
$result will get true only if requested email and password exits in database user_auth table
I think it may help...good luck
The code should make a pop up window, asking for confirmation "press ok to confirm the action for user" but it doesn't. i'm all out of ideas.
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
if(conf != true){
return false;
}
$(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "php_parsers/friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
$(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
$(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
$(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&user="+user);
}
</script>
PHP code:
<?php
$friend_button = '<button disabled>Request As Friend</button>';
$block_button = '<button disabled>Block User</button>';
// LOGIC FOR FRIEND BUTTON
if($isFriend == true){
$friend_button = '<button onclick="friendToggle(\'unfriend\',\''.$u.'\',\'friendBtn\')">Unfriend</button>';
}
else if($user_ok == true && $u != $log_username &&
$ownerBlockViewer == false){
$friend_button = '<button onclick="friendToggle(\'friend\',\''.$u.'\',\'friendBtn\')">Request As Friend</button>';
}
// LOGIC FOR BLOCK BUTTON
if($viewerBlockOwner == true){
$block_button = '<button onclick="blockToggle(\'unblock\',\''.$u.'\',\'blockBtn\')">Unblock User</button>';
} else if($user_ok == true && $u != $log_username){
$block_button = '<button onclick="blockToggle(\'block\',\''.$u.'\',\'blockBtn\')">Block User</button>';
}
?>
Opening up the console i see "Uncaught SyntaxError: Invalid or unexpected token"
The console issue is with lines 2 & 3 of your JavaScript code;
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
You have a multi-line String which the console is not interpreting as one String value. In order to resolve, ECMAScript 6 (ES6) introduced template literals which can be utilized like below to handle multi-line Strings;
var conf = confirm(`Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.`);
(i.e. use back-ticks rather than double quotes to start & end the multi-line String)
Or, if ES6 isn't supported you can use good old String concatenation like below;
var conf = confirm("Press OK to confirm the '"+type+"' action for user" +
"<?php echo $u; ?>.");
this is changepassword.php file
<?php
include 'core/init.php';
if (empty($_POST) === false) {
if (md5($_POST['current_password']) === $user_data['password']) {
} else {
$errors[] = 'Your current psasword is incorrect';
}
}
if (empty($_POST) === false && empty($errors) === true) {
change_password($session_user_id, $_POST['password']);
} else if (empty($errors) === false) {
$error = output_errors($errors);
this variable
}
?>
this is the jQuery file
$('#save_pass').click(function(){
var current_password = $('#current').val();
var password = $('#new').val();
var password_again = $('#confirm').val();
if ((password == password_again) && (password.length >= 8)) {
$.post('changepassword.php', {current_password: current_password, password: password, password_again: password_again });
$('#show').html('password changed').fadeIn(500).delay(2000).fadeOut(500);
} else if ((current_password ==0) || (password_again.length == 0) || (password.length == 8)) {
$('#show').html('all fields are required').fadeIn(500).delay(2000).fadeOut(500);
} else {
$('#show').html('your password must be at least 8 characters').fadeIn(500).delay(2000).fadeOut(500); }
$('#current').val(null);
$('#new').val(null);
$('#confirm').val(null);
});
i want to echo out $error variable when a user enters an incorrect password and click on the change password button with id="#save_pass"
You cannot echo php variables within a javascript file. Instead, put the javascript in your php file and echo it there - eg:
<script>
function something() {
alert('<?php echo $error; ?>');
}
</script>
In order to get back the errors from your $.post() ajax call, you need to echo $errors in your php script. Then add a success/done function to your $.post():
$.post('changepassword.php', {current_password: current_password ...})
.done(function (data) {
alert(data);
}
This should be the basics for getting back the raw echo data, but look at $.post documentation for more guidance on how to refine this.
After having multiple issues requesting data from my server I posted this question. Never got that code to work so I ended up rewriting the whole ajax request and now I'm able insert data in the database.
However, the issue I'm having now is that the responseText that is being sent back to my ajax request is not updating my html.
At the end of my registration script, after all values have been inserted into the database, I have this code which tests to make sure the registration email has been sent to the user and sends a string back to the ajax request:
if (mail($to, $subject, $message, $headers)) {
echo "email_success";
exit;
} else {
echo "email_failure";
exit;
}
Once a response has been received I have this condition to test what string has been returned:
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
if (hr.responseText == "email_success") {
window.scrollTo(0,0);
gebi("signupform").innerHTML = "<p>Sign up successful. Check you email to activate you account.</p>";
} else {
gebi("status").innerHTML = hr.responseText;
gebi("signupbtn").style.display = "block";
}
}
}
The issue I'm have is that the "signup_success" string is not being recognised as true and instead it fires this else statement.
What am I doing wrong?
Probably your error is that you have to trim the response text before do the comparation.
Trim code:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
and then
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var responseText = hr.responseText.trim();
if (responseText == "email_success") {
window.scrollTo(0,0);
gebi("signupform").innerHTML = "<p>Sign up successful. Check you email to activate you account.</p>";
} else {
gebi("status").innerHTML = hr.responseText;
gebi("signupbtn").style.display = "block";
}
}
}
During the process of trying to develop an checkbox activated mySQL query based on the value inside a checkbox i've incurred an problem which i can't get past, I've tried the following at the moment
<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">
The Javascript/Ajax code for the function "updateStatus" is as followed
function updateStatus(id,value) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id + "&checked="+value, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null)
The PHP function inside functions/ajax.php
if(isset($check) and $check == 'update_status' and isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
echo "Checked";
} elseif($checked == false) {
echo "Not checked";
} else {
echo "Invalid response";
}
when using this code it always returned "Checked" any idea why ?
try this (code tested),
<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">
You will get second parameter as true or false;
function updateStatus(id,checked) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id+"checked="+checked, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null)
You PHP will be:
if(isset($check) and $check == 'update_status' and isset($_GET['id']) AND isset($_GET['checked'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
$query = mysql_query("SELECT * FROM `check_status` WHERE `user_id` = '$_SESSION[userid]' and `id` = '$id'");
else
//some other query
//Then i can insert the query based on if the checkbox checked or not.