is that possible to retrieve Boolean value from php to javascript?
All I want to do is simple: Retrieve Boolean value from php variable $x into js
Should be true when emails are sent
And False when emails are not sent
Then take that Boolean value with javascript print the appropriate message
Complete code of my work can be found here, on my other case I had opened yesterday
PHP:
if (!$mail->send()) {
$x = false; //when email is not sent
} else {
$x = true; //when email is sent
}
JS Pseudocode
.done(function (data) {
if(php Boolean variable is false) {
("$formText").html("Message sent");
} else (if php Boolean variable is true) {
("$formText").html("Message not sent");
}
});
I am assuming you are already passing data (via AJAX) you just don't know how to encode it.
Use: json_encode()
PHP:
if (!$mail->send()) {
$x = true;
} else {
$x = false;
}
header("Content-type: application/json");
echo json_encode(array('x'=>$x));
Javascript:
.done(function (data) {
if (data.x) {
$("#formText").html("Message sent");
} else {
$("#formText").html("Message not sent");
}
} //end function data
);//end done function
While returning bool value from PHP code use json_encode(). It convert from native PHP types to native Javascript type.
http://php.net/manual/en/function.json-encode.php
using response code and handling them with done and fail
PHP
<?php
// ...
$success = '{"message": "your mail is send"}';
$error = '{"message": "failed sending mail"}';
$code;
$out;
if(mailSend){
$code = 200;
$out = $success;
} else {
$code = 400;
$out = $error;
}
http_response_code($code);
echo $out;
JS
// ...
var data = 'yourData';
$.ajax({
url: 'yourApiUrl'M,
data: data,
method: 'POST',
xhrFields: {withCredentials: true},
crossDomain: true,
dataType: 'json'
}).done(function() {
// mail was send
}).fail(function() {
// error on sending
});
a list of status codes you can find on https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Related
How do I convert Ajax response into plain text string?I have global variable and I store the ajax response to it but when I'm going to compare it with javascript string when even they are equal It returns false.
Here is my code:
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
console.log(response);
myGlobalContainer.usn = response; //convert it to compare with string
$('#status').html(response);
}
});
}
}
in console when I type the existing username in database it logs OK. This OK stores in myGlobalContainer.usn, but when I do comparison like code below it return false.
if(myGlobalContainer.usn == "OK"){
return true;
}else{
return false;
}
I will add php file.
<?php
header("Content-Type: text/plain");
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if(isset($_POST['emp_username'])){
$usn = $_POST['emp_username'];
$checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0){
echo "OK";
}else{
echo "Your Username not exist";
}
exit();
}
if(isset($_POST['emp_pw']) && isset($_POST['emp_usn'])){
$pw = $_POST['emp_pw'];
$usn = $_POST['emp_usn'];
$get_pw = "SELECT emp_password FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $get_pw);
//$get_num_rows = mysqli_num_rows($query);
//echo $get_num_rows;
$row = mysqli_fetch_assoc($query);
//echo $row["emp_password"];
// check if password is match with username
if($pw == $row["emp_password"]){
echo "MATCH";
}else{
echo "Wrong password";
}
exit();
}
?>
Please help Thanks!
By default, jQuery's ajax function will determine the type of data it is receiving from the Content-Type response header.
You can override that with the dataType parameter.
$.ajax({
dataType: "text",
// etc etc
});
… however, since the response seems to be "OK" and not HTML, it is likely that your PHP should be adjusted so it outputs the correct Content-Type:
<?php
header("Content-Type: text/plain"); # Override the default (text/html)
echo "OK";
So also make sure that the response is really simply "OK" and that you are not outputting (for example) "OK" followed by a new line.
I've change my code to
success: function(response){
console.log(response);
myGlobalContainer.usn = response.trim(); //convert it to compare with string
$('#status').html(response);
and It works but Guys thanks for your help very appreciated!
also thanks to this question
Ajax response doesn't equal what I think it should
i seem you should use a function in ajax success.
var myGlobalContainer.usn = "";
function signAndCompare(str)
{
myGlobalContainer.usn = str
if(myGlobalContainer.usn == "OK")
{
console.log("true");
return true;
}
console.log("false");
return false;
}
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
console.log(response);
signAndCompare(response);//this line: **compare** and sign response
$('#status').html(response);
}
});
}
i have a form with some text inputs, then i have an ajax event to send this value via POST to my database php script, the issue is that i dont know how to send special chars from my ajax event, if the string has ' " \ or similar chars, it wont insert data to my database, but if the string only contains Numbers/Letters and no special chars...i can insert the data without a problem.
Ajax event
$$("#message").click(function(e) {
var nick_ = window.localStorage.getItem("username");
var message_ = $.trim(($("#msgtext").val()).replace(/(\r\n|\n|\r)/gm,""));
if (message_ .length>0 && message_ .length<=500)
$.ajax({type: "POST",
url: "insert.php",
data: ({nick: nick_, mensaje: message_ }),
cache: false,
dataType: "json",
success: function(data) {
if(data.status == 'success'){
$('input[type=text], textarea').val('');
}
}});
else myApp.alert('Min:1 Max:500','Chars:');
});
And this is my database script
<?php
//jSON
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
//Connect to DB
include('con.php');
//POST vars
$nick=htmlspecialchars(trim($_POST['nick']));
$message=htmlspecialchars(trim($_POST['mensaje']));
$date=date("Y-m-d H:i:s");
//DB insert
$mysqli->real_query("INSERT INTO messages VALUES ('0','$nick','$message','$date')");
if ($mysqli) $response_array['status'] = 'success';
else
$response_array['status'] = 'error';
echo json_encode($response_array);
?>
before sending your data ({nick: nick_, mensaje: message_ }) in ajax, you can verify it using:
function isValid(data){
for (i in data){
if(!data[i].match(/^[a-zA-Z0-9]*$/))
return false;
}
return true;
}
use it like:
isValid({nick: nick_, mensaje: message_ })
this will return true if the data is either letter or character, and false otherwise.
Moreover, you should not be relying on any client side script for this kind of validation.
The problem is in your php script. Try this
$v = trim($_POST['mensaje']);
$message = htmlspecialchars($conn->escape_string($v));
All i did is to escape the post value.
And also the way you are checking if your query was sucessfull should be changed. you are checking the conn object instead of catching a return boolean value from the $conn->real_query () which should give you the real outcome of your query processing (True of false).
$result = $conn->real_query("........);
if ($result){
//do something
}else{
echo $conn->error;
}
If you have a form you can try data:$(this).serializeArray() which escapes those characters
OR
You can use an editor which I would recommend something like tinyMCE.
I have sent an email address via an ajax post from javascript to php. I have then searched the database in php to find out if this email exists in the database. How can i then send a message back to the javascript/html to say that the value was present?
This is what I used to send the request:
function postEmail(){
var checkEmail = "someone#gmail.com";
var dataString = 'checkEmail1='+ checkEmail;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "myfile.php",
data: dataString,
cache: false,
success: function(result){
alert("Sent successfully");
}
});
}
and then in the PHP:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
if ($row == 0 ) {
echo "email doesnt exist";
}
}
Not sure if I should do a get request? Or if you return values or something. Thanks.
(p.s, Im developing a hybrid app so need to use JSON to send/retrieve from PHP)
I think you need to remove second condition! output json or any other format you want. I use json_encode for arrays
try:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
echo "email doesnt exist";
}
JAVASCRIPT
from your success function, print the result to the console to see the output
console.log(result);
What you echo from the PHP script is sent back to the success function in the javascript, as the result parameter. So the result parameter will contain "email already exists" or "email doesnt exist"
I'm trying to implement a ReCaptcha with AJAX to verify it so that I can stop the page from submitting if the ReCaptcha fails.
Here's my JavaScript:
function verify_recaptcha(){
jQuery.post(
'verify_recaptcha.php',
{
recaptcha_challenge_field: jQuery('#recaptcha_challenge_field').val(),
recaptcha_response_field: jQuery('#recaptcha_response_field').val()
},
function(data){
if(data == "true"){
alert("ReCaptcha Verified");
}
else{
alert(data);
}
}
);
}
And the contents of verify_recaptcha.php
<?php
require_once('recaptchalib.php');
$privatekey = "-- my private key --";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
echo "false";
} else {
echo "true";
}
?>
The problem is that my test Alert is showing "true" if the recaptcha verifies (and false if it doesn't), which I don't think should be possible. It should evaluate data == "true" in that if statement and display "ReCaptcha Verified".
Most anything I search on the subject the problem is that people are trying to return a value out of the AJAX call, which I know I can't do and am not doing here.
What am I missing?
Reframed your code a bit. Try,
PHP:
...
...
$json = array();
if (!$resp->is_valid)
$json['result'] = true;
else
$json['result'] = false;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
JS:
...
...
jQuery.post(
'verify_recaptcha.php',
{
recaptcha_challenge_field: jQuery('#recaptcha_challenge_field').val(),
recaptcha_response_field: jQuery('#recaptcha_response_field').val()
})
.done(function(response){
console.log(response);
if(response.result == true)
{
// Entered captcha is correct
}
else
{
// Entered captcha is incorrect
}
});
Explanation:
1) Always return boolean true/false and not in form of string.
2) Use .done(). Won't make much difference from your code, but .done() make your ajax call code much clear.
3) Always open your console and try printing objects and see the output if it is what you are expecting.
I am using ajax to submit a login form in Yii. Here is my ajax function:
$("#login-form").submit(function() {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin",
type: "post",
data: "email=" + email + "&password=" + password,
success: function(response) {
if (response === "1") {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
}
else
{
//Dispaly response errors above login form
}
},
error: function() {
alert("Could not perform the requested operation due to some error.");
return false;
}
});
});
My PHP controller function is validatelogin as follows:
$email = $_POST['email'];
$password = $_POST['password'];
$model = new LoginForm();
$model->email = $email;
$model->password = $password;
if ($model->validate() && $model->login()) {
echo "1";
} else {
print_r($model->getErrors());
}
If the user enters correct credentials I send 1 as response to view and user is redirected to dashboard.
But if user enters incorrect credentials then different errors are received in ajax response depending upon the type of error.
I want to display those errors above login form in else part of success function through a loop.
But when I run the loop over response then that array has very large length i.e for example if the error in response was "Incorrect password" then the response array has length of 18(the number of characters) in the error message. In short the response array is like:
array('I','n','c','o','r','r'....)
rather than
array([0]=>"Incorrect password")
How do I convert response array in the latter format and iterate over each index to display error message to the user above the login form?
Encode it to JSON.
In your php:
echo json_encode($model->getErrors());
In your js (in the else):
var errors = $.parseJSON(response);
Edit:
In your case it would be better to always return JSON.
Your JS could be changed to:
var jqxhr = $.post("<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin", {
email: email,
password: password
}, 'json');
jqxhr.done(function(response) {
if (response.valid) {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
} else {
if (response.errors) {
...
}
}
});
jqxhr.error(function(response) {
alert("Could not perform the requested operation due to some error.");
});
Your PHP:
$response = array('valid' => false);
if ($model->validate() && $model->login()) {
$response['valid'] = true;
} else {
$response['errors'] = $model->getErrors();
}
header('Content-type: application/json');
echo json_encode($response);
In addition to #sroes's answer, use Yii library for JSON
echo CJSON::encode($response);
instead of
echo json_encode($response);
why ?
Why use CJSON encode when we have json_encode