Unable to Use String Result From AJAX Request - javascript

The issue I am having is that I cannot seem to USE the result passed back to the original JS file from the PHP file called from the request. This is the result and handler:
if(creds_verification() == true){
$.ajax({
url:"scripts/scripts.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {url: URL, user: USER, password: PASS},
success:function(result){
var verdict = result
if(verdict == "Yes"){
Call another external function
}else{
console.log(results.abc)
}
}
});
}
The console is constantly printing "Yes", aka the result of results.abc... why would this happen? It SHOULD be executing the next function...
Added Info
PHP script running shell command and echoing the result:
scripts.php
<?php
$URL = $_POST['url'];
$USER = $_POST['user'];
$PASSWORD = $_POST['password'];
echo json_encode(array("abc" => shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2>&1 $URL $USER $PASSWORD")));
?>
And the JS file this is calling from the shell command:
test.js
var system = require('system')
var page = require('webpage').create()
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.11.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var URL = system.args[1]
var USER = system.args[2]
var PASS = system.args[3]
var steps = [
function() {
page.open('http://'+URL+'/login.html')
},
function() {
page.evaluate(function(USER, PASS) {
document.querySelector('input[name="log"]').value = USER
document.querySelector('input[name="pwd"]').value = PASS
document.querySelector('form').submit()
}, USER, PASS)
},
function(){
var newURL = page.url
if(newURL == 'http://'+URL+'/user.html'){
console.log('Yes')
}else{
console.log('No?')
}
}
]
var stepindex = 0
var loading = false
setInterval(executeRequestsStepByStep, 5000)
function executeRequestsStepByStep(){
if (loading == false && steps[stepindex]) {
steps[stepindex]()
stepindex++
}
if (!steps[stepindex]) {
phantom.exit()
}
}
page.onLoadStarted = function() { loading = true }
page.onLoadFinished = function() { loading = false }

It's because the code you call on the server (this means the result of scripts/scripts.php) instead of returning 'Yes' as the result is putting the 'Yes' in the abc property of a returned object.
Change the php code to:
<?php
$URL = $_POST['url'];
$USER = $_POST['user'];
$PASSWORD = $_POST['password'];
$res = shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2>&1 $URL $USER $PASSWORD");
echo json_encode($res == 'Yes' ? $res : array("abc"=>$res));
?>
Edit if the result of test.js is just "Yes" or "No" then change the PHP to
<?php
$URL = $_POST['url'];
$USER = $_POST['user'];
$PASSWORD = $_POST['password'];
$res = shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2>&1 $URL $USER $PASSWORD");
echo json_encode(preg_replace("/[^A-Za-z]/", '', $res));
?>
and the javascript to
if(creds_verification() == true){
$.ajax({
url:"scripts/scripts.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {url: URL, user: USER, password: PASS},
success:function(result){
if(result == "Yes"){
Call another external function
}else{
console.log(result)
}
}
});
}

Related

How to fix error between JSON, jQuery, AJAX and PHP

I'm having problems figuring out what is wrong with my json. I used php's json_encode.So, on every page I have the some form which need be sent on each page to different email address. However, if I comment jQuery file, then the form is submitted correctly, all data inserted into database correctly, and in place of jQuery AJAX response I get valid JSON, like
{"response":"success","content":{"3":"Thanks John Doe! Your message is successfully sent to owner of property Hotel Milano!"}}
If I want to read and process this data with jQuery instead of get valid response I get just empty [] I was try a lot of options and so if I add JSON_FORCE_OBJECT instead of get empty [] I get empty {}. However if I write json data which need to encode after closing tag for if (is_array($emails) && count($emails) > 0) { just then json data it's encoded correctly and when a form is submitted I get valid response, but in this case form isn't sent and data isn't inserted into db. Bellow is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// define variables and set to empty values
$fname = $tel = $email_address_id = "";
$error = false;
$response = [];
//Load the config file
$dbHost = "localhost";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "booking";
$dbCharset = "utf8";
try {
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$response['response'] = 'error';
$response['errors'][] = $e->getMessage();
echo json_encode($response);
die();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['submit'])) {
//print_r($_POST);
$fname = $_POST['fname'];
$tel = $_POST['tel'];
if (empty($fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can not be empty!';
} else {
if (!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can contain just letters and white space!';
}
}
if (empty($tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can not be empty!";
} else {
if (!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can contain from 9 to 15 numbers!";
}
}
if (!$error) {
// Instantiate a NEW email
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret.com';
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Username = 'booking#secret.com';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->setFrom('booking#secret.com');
$mail->clearAddresses();
$mail->Subject = "New message from secret.com";
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM booking.owners_email INNER JOIN booking.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1, $pages_id);
$dbstmt->execute();
//var_dump($dbstmt);
$emails = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
if (is_array($emails) && count($emails) > 0) {
foreach ($emails as $email) {
//var_dump($email['email_address']);
$mail->addAddress($email['email_address']);
$body = "<p>Dear {$email['owner_name']}, <br>" . "You just received a message from <a href='https://www.secret-booking.com'>secret-booking.com</a><br>The details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "</p>";
$mail->Body = $body;
if ($mail->send()) {
$mail = "INSERT INTO booking.contact_owner (fname, tel, email_address_id) VALUES (:fname, :tel, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'email_address_id' => $email['email_address_id']]);
$response['response'] = "success";
$response['content'][$email['email_address_id']] = "Thanks " . ucwords($fname) . "! Your message is successfully sent to owner of property {$email['owner_property']}!";
}//end if mail send
else {
$response['response'] = "error";
$response['content'][$email['email_address_id']] = "Something went wrong! Try again..." . $mail->ErrorInfo;
}
}//end foreach for email addresses
} //end if for array of emails
/* If use this else for response I allways get this response. Even, if I write JSON for success hier I get it but data isn't sent and isn't inserted into db
else {
$response['response'] = 'error';
$response['error'][] = '$emails is either not an array or is empty'; // jQuery just read this
}//end if else for array of emails
*/
}//end if validation
}//end submit
echo json_encode($response);
}//end REQUEST METHOD = POST
And this is jQuery for submitHanfdler
submitHandler: function (form) {
//Your code for AJAX starts
var formData = jQuery("#contactOwner").serialize();
console.log(formData); //this work
jQuery.ajax({
url: '/classes/Form_process.class.php',
type: 'post',
data: formData,
dataType: 'json',
cache: false,
success: function (response) {
jQuery("#response").text(response['content']);
// debbuger;
console.log(response);
//console.log(response.hasOwnProperty('content'));
},
error: function (response) {
// alert("error");
jQuery("#responseOwner").text("An error occurred");
console.dir("Response: " + response);
}
}); //Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} //submitHandler
Thanks in advance for any kind of your help, any help will be highly appreciated!
I suspect the issue is the dataType: 'json' attribute. This is because the serialize function does not provide json data. See if this works:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: jQuery("#contactOwner").serialize()
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
Alternatively, if you want to use dataType: 'json', you will need to send in json data:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: {
firstName: jQuery("#contactOwner .first-name").val(),
lastName: jQuery("#contactOwner .last-name").val(),
...
}
dataType: 'json',
cache: false,
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
If you add you data using an object as shown above this should work with dataType: 'json'.

Ajax window.location not working with PHP login Script

I have a PHP login script which executes with ajax. The ajax request now starts the session in the login successfully but the window.location function doesn't work (doesn't redirect to exporter.php) in the ajax request. Below are my codes.
php Login Script
if(isset($_POST['log_name']) && isset($_POST['log_password'])) {
$username = $_POST['log_name'];
$password = $_POST['log_password'];
$sql = $db->prepare("SELECT * FROM users WHERE uname = ?");
$sql->bindParam(1, $username, SQLITE3_TEXT);
$ret = $sql->execute();
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$id = $row['userid'];
$regas = $row['regas'];
$uemail = $row['uemail'];
$pword = $row['pword'];
$uname = $row['uname'];
$package = $row['package'];
if (password_verify($password, $pword))
{
$_SESSION['log_id'] = $id;
$_SESSION['log_name'] = $username;
$_SESSION['regas'] = $regas;
$_SESSION['uemail'] = $uemail;
$_SESSION['package'] = $package;
//header("Location: index.php?log_id=$id");
//echo "Sigining In...";
//die("<script>window.location='exporter.php?userid={$id}';</script>");
exit();
}
else
{
echo "Information incorrect";
exit();
}
}
}
Ajax Request
$("#submit_log").click(function() {
//e.preventDefault();
username=$("#log_name").val();
password=$("#log_password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "log_name="+username+"&log_password="+password,
success: function(html){
if(html=='true') {
window.location.assign = "exporter.php";
}
else {
$(".logresult").html('Incorrect Username and Password');
}
},
beforeSend:function()
{
$(".logresult").html("Loading...")
}
});
return false;
});
Beginning part of exporter.php
session_start();
require_once ("db.php");
$db = new MyDB();
if (!isset($_SESSION['log_name']) || !isset($_SESSION['log_id']) || !isset($_SESSION['regas']))
{
header("Location: index.php");
}
What could be wrong here and how do i fix this redirecting issue please!!!.Thanks.
your php login script needs echo 'true'; according to your ajax callback.
and use location.href = "/exporter.php"; to redirect page with JavaScript
You should use like this:
window.location.href= "/exporter.php";
window.location.assign = "exporter.php";
will not work, use
window.location = "exporter.php";
You are using assign incorrectly.
window.location.assign("exporter.php")
Or you can use href instead.
window.location.href = "exporter.php";
Try using assign like this:
window.location.assign(data);
if this method not work for you let me know.
and if the Success:html is boolean then you're checking it in wrong way delete the single quotes it's not a string it is boolean datatype.

How to add php form validation with ajax error handling

How can I add validation and php error handling with ajax. Now the success message come correctly but how can I implement error message on it? I might need to add some php validation please help.
Here is my JS.
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
$(".msg-ok").css("display", "block");
$(".msg-ok-text").html("Profile Updated Successfully!!");
},
error: function() {
//Error Message
}
});
});
PHP
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "<p>Succcessfully Updated</p>";
} else {
echo "Erorr while updating record : ". $connect->error;
}
$connect->close();
}
?>
ajax identifies errors based of status code, your php code will always return status code 200 which is success, even when you get error in php code unless its 500 or 404. So ajax will treat response as success.
if you want to handle php error, make following changes in your code
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "true";
} else {
echo "false";
}
$connect->close();
}
?>
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function (res) {
if(res == 'true') {
//success code
} else if(res == 'false') {
//error code
}
},
error: function() {
//Error Message
}
});
});

Ajax code is not working in JavaScript

I am using this code for my php MySql validation.
CheckID = document.getElementById('checkID_' + idCounter).value;
$.ajax({
type: "POST",
url: "checkval.php",
data: { check : CheckID }
}).done(function( data ) {
if(data !== "success");
{
var val = confirm(data);
if (val === false) {
return false;
}
}
});
This code is not working, Script wrote after that also not working. No idea about check the bug. help me.....
this is my php script
<?php
$check = $_POST['check'];
$host = 'localhost';
$database = 'database';
$username = 'user';
$password = 'password';
$dbc = mysqli_connect($host,$username,$password,$database);
$counter = count(checkArray);
$checkno = $check;
$sql = "select claimno from check_details where checkno = $checkno";
$result = mysqli_query($dbc,$sql);
$rows = mysqli_num_rows($result);
if($rows != 0)
{
$claim = mysqli_fetch_array($result,MYSQLI_BOTH);
$claimno = $claim['claimno'];
$str = "Check Number:$checkno is already applied for $claimno.Are you sure to contniue ???";
echo $str;
}
else
{
echo "success";
}
?>
You could write your function to return "a promise to return the boolean status value":
function getMeStatus(checkID){
var def = $.Deferred(); // Create a deferred object
$.ajax({ // Make the ajax call
type: "POST",
url: "checkval.php",
data: {check: CheckID}
}).done(function (data) {
if (data !== "success"); {
var val = confirm(data);
if (val === false) {
// Status was false?
def.resolve(false);
}
else {
// Status was true?
def.resolve(true);
}
}
else {
// Status was true?
def.resolve(true);
}
}
// return a promise to supply the boolean status value later
return def.promise();
});
and use it like:
CheckID = document.getElementById('checkID_' + idCounter).value;
getMeStatus(checkID).done(function(status){
alert(status); // Use the value here
});
Note:
(Before everyone jumps on this,) this is not an anti-pattern if the return value has to be changed
This can be shortened a little, but the required logic from the question is not clear :)

Ajax login issues

I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.

Categories

Resources