Variable getting via Ajax is empty ( Phonegap-Ajax-Json-PHP-MySQL ) - javascript

I created an android application using Phonegap. I made an account in 000webhost and I've added my PHP files on the server. In the phpMyAdmin, I've created my database.
Right, now I tried to connect my project with the online database and insert or check some data in it.
PROBLEM:
When I run the application in my mobile phone i get this alert from the success: ... part of code in ajax :
There is no such username.
(my PHP had in comments all the echo, except the: echo json_encode)
When I added this line (var_dump($_POST);) right after i am getting the $usernamefrom ajax in the PHP and run my app, I saw this alert: array(1){ [\"username\"]=> string(2) \"hi"\" }
When I added these lines: if (empty($username)) { echo '...' } , after I run my app, I saw that in the alert inside the error: ... part of the ajax, it is printed the echo that is inside this if. So, the $username is empty for sure.
This is my JavaScript file: (I get correctly for sure all the values from html so Focus on the two Ajax parts of code)
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
var el = document.getElementById("register");
el.addEventListener("click", Register, false);
}
function Register() {
var username = document.getElementsByName('username')[0];
var password = document.getElementsByName('password')[0];
var email = document.getElementsByName('email')[0];
var strong_flag_user = 0;
var user = username.value;
if (username.value == "") {
$("#username").focus();
document.getElementById('username').style.boxShadow = "0 0 7px #f00";
navigator.notification.vibrate(500);
}
else{
$.ajax({
url: "http://www.guidemeforall.freeiz.com/phps/check_for_dublicates/check_username.php",
type: "POST",
crossDomain: true,
data: { username: user },
dataType:'json',
success: function(response){
if (response.status == 'success') {
alert(response.message);
document.getElementById('username').style.boxShadow = "none";
strong_flag_user = 1;
}
else if (response.status == 'error') {
alert(response.message);
navigator.notification.alert("This username is already taken! Please use another one!", null, 'Username', 'Okay');
document.getElementById('username').style.boxShadow = "0 0 7px #f00";
navigator.notification.vibrate(500);
strong_flag_user = 0;
//window.location("main.html");
}
else {
alert("error");
strong_flag_user = 0;
}
},
error: function(error){ //function(error){
alert(JSON.stringify(error));
strong_flag_user = 0;
//window.location = "main.html";
}
});
}
//>5 characters, 1 upper case, at least 1 lower case, at least 1 numerical character, at least 1 special character
var passExp = /(?=^.{6,15}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*/;
var strong_flag_pass = 0;
if (!(password.value.match(passExp))) {
$("#password").focus();
document.getElementById('password').style.boxShadow = "0 0 7px #f00";
navigator.notification.alert("Please enter a strong Password! It has to have at least: 6 characters, 1 upper case, 1 lower case, 1 numerical character and 1 special character!", null, 'Password', 'Okay');
navigator.notification.vibrate(500);
strong_flag_pass = 0;
}
else{
document.getElementById('password').style.boxShadow = "none";
strong_flag_pass = 1;
}
var emailExp = /^.+#[^\.].*\.[a-z]{2,}$/;
var strong_flag_email = 0;
if (!(email.value.match(emailExp))) {
$("#email").focus();
document.getElementById('email').style.boxShadow = "0 0 7px #f00";
navigator.notification.alert("Please enter a correct Email!", null, 'Email', 'Okay');
navigator.notification.vibrate(500);
strong_flag_email = 0;
}
else {
document.getElementById('email').style.boxShadow = "none";
strong_flag_email = 1;
}
var gender;
if (document.getElementById("gender").value == "female")
gender = 'F';
else
gender = 'M';
var about_you = document.getElementById("about_you").value;
var age = document.getElementById("radio-choice").value;
if (document.getElementById('radio-choice-1').checked) {
age = document.getElementById('radio-choice-1').value;
}
else if (document.getElementById('radio-choice-2').checked) {
age = document.getElementById('radio-choice-2').value;
}
else if (document.getElementById('radio-choice-3').checked) {
age = document.getElementById('radio-choice-3').value;
}
else if (document.getElementById('radio-choice-4').checked) {
age = document.getElementById('radio-choice-4').value;
}
else if (document.getElementById('radio-choice-5').checked) {
age = document.getElementById('radio-choice-5').value;
}
else if (document.getElementById('radio-choice-6').checked) {
age = document.getElementById('radio-choice-6').value;
}
if (strong_flag_user == 1 && strong_flag_pass == 1 && strong_flag_email == 1){
//add to db
register_db(email.value, password.value, username.value, gender, about_you, age);
}
}
function register_db(em, pass, user, gend, about, ag) {
$.ajax({
url: "http://www.guidemeforall.freeiz.com/phps/sign-up.php",
type: "POST",
crossDomain: true,
data: { username:user, password:pass, email:em, gender:gend, about_you:about, age:ag },
dataType:'json',
success: function(data)
{
if (data.status == 'success')
{
alert("Success!");
}
else if (data.status == 'error')
{
alert("Failure!");
}
}
});
}
This is my PHP file in which I check if the username already exists (Username = Primary Key):
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
//require_once('../database_config.php');
$server = "my***.000webhost.com";
$database = "a1****37_guideme";
$username = "a1****37_guideme";
$password = "*****";
$con = mysql_connect($server, $username, $password);
// if($con) { //echo "Connected to database!"; }
// else { //echo "Could not connect!"; }
mysql_select_db($database, $con);
$topost = file_get_contents('php://input');
$thedata = json_decode($topost, true);
$username = $thedata['username'];
//var_dump($_POST);
//if (empty($username)) {
// echo 'The username is either 0, empty, or not set at all';
//}
$sql = "SELECT COUNT(*) as Count FROM `user` WHERE `username`='$username'";
$result= mysql_query($sql, $con);
$rows = mysql_fetch_array($result);
$count = $rows['Count'];
if (!$result) {
die('Error: ' . mysql_error());
//$response_array['status'] = 'error';
//echo json_encode($response_array);
}
else {
if ($count == 0) {
echo json_encode(array('status' => 'success','message'=> 'There is no such username'));
//$response_array['status'] = 'success';
//echo json_encode($response_array);
}
else
{
echo json_encode(array('status' => 'error','message'=> 'The username already exists'));
//$response_array['status'] = 'error';
//echo json_encode($response_array);
}
}
mysql_close($con);
?>
And this is the PHP file in which I tried to insert the new entry in my database ( my credentials are for sure correct):
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
//require_once('database_config.php');
$server = "mys****.000webhost.com";
$database = "a***37_guideme";
$username = "a***37_guideme";
$password = "******";
$con = mysql_connect($server, $username, $password);
// if($con) { //echo "Connected to database!"; }
// else { //echo "Could not connect!"; }
mysql_select_db($database, $con);
$topost = file_get_contents('php://input');
$thedata = json_decode($topost, true);
$username = $thedata['username'];
$password = $thedata['password'];
$email = $thedata['email'];
$gender = $thedata['gender'];
$age = $thedata['age'];
$about_you = $thedata['about_you'];
$sql = "INSERT INTO user (username, password, email, gender, age, about_you) ";
$sql .= "VALUES ('$username', '$password', '$email', '$gender', '$age', '$about_you')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
// $response_array['status'] = 'error';
// echo json_encode($response_array);
}
else {
echo json_encode(array('status' => 'success','message'=> 'No problem'));
// $response_array['status'] = 'success';
// echo json_encode($response_array);
}
mysql_close($con);
?>

My problem solved by changing the way I get the data in my PHP to -> $user = $_POST['username']; instead of the way with Json (json_decode e.t.c.).

Related

I can't redirect user after login

I have login page which take username and password from user after user will be login. I am getting response for successfully login. but I can not redirect to index.php.
I am getting console message that User successfully login, But then page is not redirect on other page.
My JS file is like this.
$(document).ready(function() {
//alert('ss');
$("#login-form").submit(function(e){
e.preventDefault();
var username = $("#email").val();
var password = $("#password").val();
var isValid = true;
var re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!re.test($("#email").val())){
isValid = false;
$("#message").html("Please enter valid email.");
}
if($('#remember').is(':checked')){
$.cookie('adminCookie', $("#loginUser").val(), { expires: 7 });
}
else{
if($.cookie('adminCookie') == null) {
$.removeCookie("adminCookie");
}
}
if(password == ""){
isValid = false;
$("#message").html("Please enter password.");
}
if(isValid){
$.ajax({
type : "POST",
url : "process/login.php?rand="+Math.random(),
data : {
username : $("#email").val(),
password : $("#password").val(),
}
}).
done(function(response){
//alert(response);
var JSONArray = $.parseJSON(rawJSON);
console.log(response);
if(jsonObj.success=="1"){
window.location("index.php");
}else{
$("#userDiv").addClass("form-group has-error");
$("#passDiv").addClass("form-group has-error");
$("#passWarning").css("display","");
$("#passWarning").html("Invalid User Name or Password");
$.when($('#passWarning').fadeOut(5000)).done(function() {
$("#userDiv").attr('class', 'form-group');
$("#passDiv").attr('class', 'form-group');
});
}
}).fail(function(){
}).always(function() {
});
}
});
});
my PHP file is looks like this.
<?php
include "../connection.php";
extract($_POST);
$data = array();
$resArr = array();
if (isset($_POST['username']) && isset($_POST['password'])) {
$check_user = mysqli_query($conn, "select * from cut_users where email like '$username' and password like '$password' and user_role like 'A'");
if ($check_user) {
if (mysqli_num_rows($check_user) > 0) {
$message = "Login successfully.";
$success = 1;
while ($row = mysqli_fetch_array($check_user)) {
if ($row['is_active'] == "0") {
$message = "Your account is blocked. Please contact admin.";
$success = 0;
}
$data["id"] = $row['cut_users_id'];
$data["name"] = $row['name'];
$data["emailID"] = $row['email'];
$data["device"] = $row['device_type'];
$data["is_reset"] = $row['is_reset'];
$_SESSION['userID'] = $row['cut_users_id'];
$_SESSION['name'] = $row['name'];
$_SESSION['emailID'] = $row['email'];
}
$resArr = array("success" => $success, "data" => $data, "message" => $message);
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Email or password invalid.");
}
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Something went wrong!!!" . mysqli_error($conn));
}
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Parameter Missing");
}
header('Content-Type: application/json');
echo str_replace("\/", "/", json_encode($resArr, JSON_UNESCAPED_UNICODE));
?>
1) Why you are using variable jsonObj instead of response ?
2) Modify your if statement like this
if(response.success==1){
window.location.href="index.php";
}
window.location is not a function it is an object. Please change href property in window.location object to redirect to new url.
window.location.href = "./index.php";
Simple redirect to specific file
if(jsonObj.success==1)
{
window.location.href = "http://www.example.com/index.php";
}

JSON_encode not outputting anything

I want to send a query result from one php file to my javascript, I've used an AJAX which seems to work as it is getting data from my BaseClass.php. However when using JSON_encode, it is not outputting anything at all. So I can't work out how to send a query result from one php file(MySQLDao.php) to my BaseClass.php so I am then able to send it to my Javascript file.
My Code:
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
//$param=$_REQUEST['action'];
//echo json_encode($_GET);
//echo var_dump(json_encode($_GET));
$handle = fopen("php://input", "rb");
$param = $_REQUEST['action'];
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
ob_clean();
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
}
$dao->closeConnection();
//Return the result of the query
ob_clean();
echo json_encode("param" .$param);
echo json_encode("body" .$body);
echo json_encode("recieved" .$recieved);
echo json_encode("result" .$result);
exit();
}
?>
output for the above echo statements:
"paramgetResults""body""recieved""result"
MySQLDao.php - this file holds the query result that I want to pass to my js
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults()
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
// echo($obj);
// return $obj;
//}
echo json_encode($result);
//echo($result);
//return false;
}
}
?>
My AJAX code in my js file:
$.ajax ({
type: "GET",
datatype: "application/json",
url: "BaseClass.php",
data: { action : 'getResults' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
//alert(output);
}
//error, function(err){console.log(err)}
});
Any help is appreciated thanks!

PHP, phpmyadmin, html, javascript

I am having an issue ordering into a table primary id values which auto-increment from phpmyadmin and adding them into a table from recent to latest (greatest to lowest) can i get some help? I am using json to get php to javascript. This code only shows the table from latest to recent.
$app->get('/proyects/all', function () use($servername, $dbname, $dbuser, $dbpassword)
{
$response = array();
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbuser, $dbpassword);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM proyectos");
if ($stmt->execute()) {
$result = $stmt->fetchAll();
}
$conn = null;
if(!empty($result))
{
$response['proyects'] = array();
foreach ($result as $key => $value)
{
$response['proyects'][$key] = $value;
}
$response['success'] = true;
echo json_encode($response);
return;
}
else
{
$response['success'] = false;
$response['message'] = "Proyects not found";
echo json_encode($response);
return;
}
}
catch(PDOException $e)
{
$response['success'] = false;
$response['message'] = $e->getMessage();
echo json_encode($response);
return;
}
});
<script type="text/javascript">
$(document).ready(function()
{
$.ajax(
{
url: path+'/proyects/all',
type: 'get',
dataType: "json",
success: function(json)
{
console.log(json);
if (json.success)
{
$.each(json.proyects, function( index, value ) {
$('#proyecs').append('<tr><td>'+value.idproyect+'</td><td>'+value.pdescription+'</td><td>'+value.presponsible+'</td><td>'+value.pdateini+'</td><td>'+value.pdatefin+'</td><td>'+value.pstatus+'&#37</td><td><button type="button" class="btn btn-default">Details</button></td></tr>');
});
}
else
{
Materialize.toast(json.message, 5000, 'red accent-4');
}
},
error : function(e, settings, exception)
{
Materialize.toast("Oops! an error has ocurred", 5000, 'red accent-4');
}
});
});
</script>
#sesonrario #rex sorry forgot the code
Could
$stmt = $conn->prepare("SELECT * FROM proyectos order by id");
solve your problem?

PHP AJAX script not working properly on all conditions

I have a script where I want to process form data using ajax. The script is returning the success message but not the error message. Have a look at the scripts below.
AJAX Script
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val()
};
$.ajax({
type: "POST",
dataType : "json",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#submit").show();
$("#loading").hide();
},3000);
}
});
return false;
});
});
PHP Script
<?php
session_start();
include'config/db.php';
$msg = null;
$sessionid = (!empty($_SESSION['login']))?$_SESSION['login']:null;
$wp = $pdo->prepare("SELECT set_cointoss_wp, set_cointoss_prob FROM settings");
$wp-> execute();
$sp = $wp->fetch();
$percent = $sp['set_cointoss_wp'];
$probablity = $sp['set_cointoss_prob'];
$bal = $pdo->prepare("SELECT mb_acbal, mb_wallet FROM mem_balance WHERE mb_id = :mem");
$bal-> bindValue(':mem', $sessionid);
$bal-> execute();
$bf = $bal->fetch();
$balance = $bf['mb_acbal'];
$wallet = $bf['mb_wallet'];
$coin = (!empty($_POST['flip']))?$_POST['flip']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
if($_POST){
if($wallet < $amount){
$msg = "<div class='message-error'>Sorry buddy! You have insufficient balance. Please <a href=''>recharge</a> your wallet.</div>";
}else{
$deduct = $wallet-$amount;
$prob = rand(1, 10);
//set new wallet balance after bet amount deduction
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_wallet = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $deduct);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
if($coin == ''){
$msg = "<div class='message-error'>Sorry buddy! Fields cannot be left empty.</div>";
}else{
if($coin == "head"){
if($prob <= $probablity){
$result = 1;
}else{
$result = 2;
}
if($result == 1){
// win
$wa = $amount*$percent;
$win_amount = $wa/100;
$final_cash = $win_amount+$balance;
// update database with winning amount
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $final_cash);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
$msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
}else{
// loose
$msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
}
}else{
if($prob <= $probablity){
$result = 2;
}else{
$result = 1;
}
if($result == 1){
// loose
$msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
}else{
// win
$wa = $amount*$percent;
$win_amount = $wa/100;
$final_cash = $win_amount+$balance;
// update database with winning amount
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $final_cash);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
$msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
}
}
}
}
echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>
Here in the scripts above, when if($wallet < $amount) condition is false and else condition is executed, the scripts works fine and returns <div class='message-success'> as required. But, if if($wallet < $amount) condition is true then its not returning <div class='message-error'> and the loading image keeps on moving (as if waiting for the response) but does not receives any response in return. I am stuck since a few days on this but not being able to find any solution for the same. Please help.
I am not sure but I think in your php script $deduct has been declared inside the else block.
so when the script executes and if ($wallet < $amount) condition evaluates to true, then the else part is skipped and you directly return this:-
return echo json_encode(array(
'status' => $msg,
'deduct' => $deduct
));
so it might be the case that $deduct is not recognized. try executing by declaring the $deduct before the if block.

jQuery POST not executing php script

I have the following jQuery in my index.php file (www root):
$(document).ready(function() {
$('#loginForm').submit(function() {
var username = $("#username").val();
var password = $("#password").val();
$.post("php/login.php",
{
username: username,
password: password
},
function(data,status){
$("#loginstatus").html(data);
alert(data);
}
);
});
});
and the following php script in the folder php:
<?php
$username = isset($_POST["username"]) ? $_POST["username"] : '' ;
$password = isset($_POST["password"]) ? $_POST["password"] : '' ;
$dbhost = "localhost";
$dbuser = "s150314";
$dbpass = "password";
$dbname = "users";
$loginerror = "";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$sqlu = "SELECT username FROM users WHERE username LIKE '$username' ";
$sqlp = "SELECT password FROM users WHERE password LIKE '$password' ";
$sqlfn = "SELECT FirstName,LastName FROM users WHERE username LIKE '$username' ";
$resultu = mysqli_query($conn, $sqlu) ;
$resultp = mysqli_query($conn, $sqlp) ;
$resultfn = mysqli_query($conn, $sqlfn) ;
if (mysqli_num_rows($resultu) > 0 && mysqli_num_rows($resultu) > 0 ) {
while($row = mysqli_fetch_assoc($resultfn)) {
$_SESSION["FirstName"] = $row["FirstName"];
}
echo "Success!";
header("Location: ../pages/redirect.php");
} else {
echo "Error!";
}
?>
However there is no change on the submission of the form. In theory I am supposed to be redirected to redirect.php... if I replace the php code back into index.php it works flawlessly.
Use window.location
<script>
$.post("php/login.php",
{
username: username,
password: password
},
cache:false,
success:function(data){
if(data.status == 'success'){
window.location.href="http:\\www.site_name.php/pages/redirect.php"";
}else if(data.status == 'error'){
alert(data);
}
}
</script>
PHP
<?
header('Content-type: application/json');
$SqlQuery = "SELECT FirstName,LastName,username FROM users WHERE username LIKE '$username' AND password LIKE '$password'";
$resultu = mysqli_query($conn, $SqlQuery) ;
if (mysqli_num_rows($resultu) > 0 && mysqli_num_rows($resultu) > 0 ) {
while($row = mysqli_fetch_assoc($SqlQuery)) {
$_SESSION["FirstName"] = $row["FirstName"];
}
$response_array['status'] = 'success';
} else {
$response_array['status'] = 'error';
}
?>

Categories

Resources