jQuery POST not executing php script - javascript

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';
}
?>

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";
}

How to embed Javascript function in restful api in php?

I have the following code in one of api files(DispatchJob_Public) and i need ajax here to call the other file(selectDriverForJobResult) after 2 minutes. I can do that in php with sleep(), but that will keep the server busy. Ajax call is at the end of the php code. Can i embed js in api code? Or is there any alternate to do what i am trying to do.
Moreover i have got response from the first file(DispatchJob_Public), but no response from the second file(selectDriverForJobResult) when i called the endpoint in postman. Because the call wasn't made. If the second file was called, it should have return some response. The strange thing is that i get response from second file when i run it in browser. I think that is because the browser supports the javascript but the call made from android to the end point doesn't support that.
Please can i get any solution for this?
<?php
include_once ('connection.php');
include_once ('fcm_notification.php');
//error_reporting(E_ERROR | E_PARSE);
$user_id = $_REQUEST["user_id"];
$customer_name = $_REQUEST["customer_name"];
$group_id_fk = $_REQUEST["group_id_fk"];
$readynow_checkbox = $_REQUEST["readynow_checkbox"];
$job_points = '';
date_default_timezone_set('Australia/Melbourne');
$date = date('Y-m-d H:i:s');
if(strcasecmp($benefits_type, 'Points') == 0){
if(strcasecmp($fixed_price, '') == 0){
$fixed_price_new = $estimated_price;
}else{
$fixed_price_new = $fixed_price;
}
$sql_job_points = "SELECT `points` FROM `hg_job_points` WHERE '$fixed_price_new' BETWEEN `min_price` AND `max_price`";
$res_jobPoints = mysqli_query($conn, $sql_job_points);
$row_job_points = $res_jobPoints->fetch_assoc();
$job_points = $row_job_points["points"];
}
if(strcasecmp($commission_percent, 'Amount') != 0 && strcasecmp($fixed_price, '') != 0){
$commision_price = ($commission_percent / 100) * $fixed_price;
}
//insert job in job table
$sql = "INSERT INTO `hg_jobs`(`customer_name`, `pickup_address`, `dropoff_address`, `customer_phone`, `instruction`,
`via`, `user_id_fk`, `group_id_fk`, `pickup_time`, `flight_no`, `car_type`, `post_time`)
VALUES ('$customer_name', '$pickup_address', '$dropoff_address', '$customer_phone', '$instruction', '$via', '$user_id', '$group_id_fk',
'$pick_time', '$flight_no', '$car_type', '$date')";
if(mysqli_query($conn, $sql)){
//get job id from jobs table
$job_id = $conn->insert_id;
//insert new record in advance job table
$sql_adv = "INSERT INTO `hg_job_details`(`no_of_passenger`, `no_of_bags`, `child_seats`,
`car_type_specific`, `job_type`, `job_price`, `estimated_amount`, `payment_type`, `benefits_type`, `benefit_percent`,
`benefit_amount`, `job_points`, `ready_now_job`, `job_id_fk`)
VALUES ('$passenger','$bags','$child_seats','$car_type_specific','$job_type','$fixed_price', '$estimated_price',
'$payment_type','$benefits_type','$commission_percent','$commision_price', '$job_points', '$readynow_checkbox', '$job_id') ";
$res_adv = mysqli_query($conn, $sql_adv);
if($res_adv){
echo json_encode(Array('message' => 'job success'));
//get black list users
$sql_black = "SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id'";
$res_black = mysqli_query($conn,$sql_black);
//if specif type car is any
if(strcasecmp($car_type_specific, 'ANY') == 0){
if ($res_black->num_rows > 0) {
//get all fcm key and send notification (if blacklist table not empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type' AND u.user_id !=
(SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id') ";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}else{
//get all fcm key and send notification (if blacklist table empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}
}else{
//if specific car type
if ($res_black->num_rows > 0) {
//get all fcm key and send notification (if blacklist table not empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'
AND cd.car_type_specific = '$car_type_specific' AND u.user_id !=
(SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id') ";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}else{
//get all fcm key and send notification (if blacklist table empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'
AND cd.car_type_specific = '$car_type_specific'";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}
}
?>
<script>
function callDispatch()
{
nIntervId = window.setInterval(myCallback, 5000);
var baseUrl = document.location.origin;
function myCallback()
{
var user_id = '<?=$GLOBALS["user_id"];?>';
var job_id = '<?=$job_id;?>';
$.ajax({
url: baseUrl+'/android/selectDriverForJobResult.php',
type: 'POST',
dataType : 'json',
data: {'user_id': user_id, 'job_id': job_id} ,
success: function(response) {
clearInterval(nIntervId);
var resp = response.toString();
if (resp.includes('true') === true)
{
console.log('true'+ resp);
}
else
{
console.log(resp);
}
},
error: function(response)
{
console.log('Error in ajax'+response.statusText);
clearInterval(nIntervId);
}
});
}
}
callDispatch();
</script>
<?php
}
} else{
echo json_encode(Array('message' => 'error job post'));
}
$conn->close();
?>

Empty POST on Angular/PHP

I'm new to Angular 4. I've added a simple HTTP POST login & connected it to another, simple, PHP receiver which then connects to the DB to check if the credentials are correct.
Bad Code:
login(username: string, password: string){
var headers = new Headers();
var creds ='http://localhost/crm/login/login.php';
headers.append('content-type', 'application/X-www-form=urlencoded');
return this._http.post(creds, {username: username, password: password}, {headers})
.map((response: Response) => {
let user = response.json();
if(user && user.accid){
this.isLoggedIn = true;
this.loginType = user.accid;
sessionStorage.setItem('accid', JSON.stringify(user.accid));
sessionStorage.setItem('status', JSON.stringify(user.status));
sessionStorage.setItem('username', JSON.stringify(user.user));
sessionStorage.setItem('uniqid', JSON.stringify(user.uniqid));
return user;
}else
return false;
});
}
The issue is, if I POST, the PHP server does not read any input at all, as if I POSTed nothing.
This is how I "fixed" it, but really this isn't a fix at all. This is basically using GET, except that I format the string itself. Obviously this is a horrible walkaround since now I have to accept GET requests on the PHP body, and the request itself is literally printed out in the browser's console on login.
login(username: string, password: string){
var headers = new Headers();
var creds ='http://localhost/crm/login/login.php?' + 'username=' + username + '&password=' + password;
headers.append('content-type', 'application/X-www-form=urlencoded');
return this._http.post(creds, '', {headers})
.map((response: Response) => {
let user = response.json();
if(user && user.accid){
this.isLoggedIn = true;
this.loginType = user.accid;
sessionStorage.setItem('accid', JSON.stringify(user.accid));
sessionStorage.setItem('status', JSON.stringify(user.status));
sessionStorage.setItem('username', JSON.stringify(user.user));
sessionStorage.setItem('uniqid', JSON.stringify(user.uniqid));
return user;
}else
return false;
});
}
PHP body
<?php
require_once '../config.php';
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$parmSir = [];
if($_GET)
foreach($_GET as $gettie)
$parmSir[] = $gettie;
if($_POST)
foreach($_POST as $postie)
$parmSir[] = $postie;
$username = isset($parmSir[0]) ? $parmSir[0] : NULL;
$password = isset($parmSir[1]) ? $parmSir[1] : NULL;
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = sha1($password, true);
$response = [];
$query = mysqli_query($connection, "SELECT * FROM user_accounts WHERE password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);
if ($rows == 1){
$query = mysqli_query($connection, "SELECT account_type, employee_ID FROM user_accounts WHERE username ='$username'");
$row = $query->fetch_assoc();
$response['status'] = 'loggedin';
$response['accid'] = $row['account_type'];
$response['user'] = $username;
$response['uniqid'] = $row['employee_ID'];
}
else
$response['status'] = 'error';
echo json_encode($response);
?>
Not exactly sure why the PHP isn't recognizing POST/GET requests unless if I format the string in that specific manner. What am I doing wrong?
The solution is to ensure the header's 'content-type' is 'application/json'. Otherwise, _POST and _GET will not read the content as required (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).
Other posts have recommended to use $HTTP_RAW_POST_DATA (now deprecated, replaced with php://input which I now use).
Here is how it now looks like:
login(username: string, password: string){
var headers = new Headers();
var creds ='http://localhost/crm/login/login.php';
headers.append('content-type', 'application/json');
return this._http.post(creds, {username: username, password: password}, {headers})
.map((response: Response) => {
let user = response.json();
if(user && user.accid){
this.isLoggedIn = true;
this.loginType = user.accid;
sessionStorage.setItem('accid', JSON.stringify(user.accid));
sessionStorage.setItem('status', JSON.stringify(user.status));
sessionStorage.setItem('username', JSON.stringify(user.user));
sessionStorage.setItem('uniqid', JSON.stringify(user.uniqid));
return user;
}else if(user.status == "error"){
return false;
}else
return false;
});
}
And the .PHP:
<?php
require_once '../config.php';
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
$input = json_decode(trim(file_get_contents('php://input')),true);
$username = $input['username'];
$password = $input['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = sha1($password, true);
$response = [];
$query = mysqli_query($connection, "SELECT * FROM user_accounts WHERE password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);
if ($rows == 1){
$query = mysqli_query($connection, "SELECT account_type, employee_ID FROM user_accounts WHERE username ='$username'");
$row = $query->fetch_assoc();
$response['status'] = 'loggedin';
$response['accid'] = $row['account_type'];
$response['user'] = $username;
$response['uniqid'] = $row['employee_ID'];
}
else
$response['status'] = 'error';
echo json_encode($response);
?>

Alert message not working using php

I was trying to code where whenever I hit the submit button it will show an alert message when there's no data fetch. Can anyone help me?
if(isset($_POST['submitEstatus'])) {
if($_POST['empValue'] == $valEmp AND $_POST['ageValue'] == $valAge AND $_POST['genValue'] == $valGen){
$query = "SELECT * FROM users $valEmp $valAge $valGen";
$result = mysql_query($query);
if ($result = 0) {
$message = "No Data";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
while($row = mysql_fetch_array($result)){
$lat = $row['lat'];
$lon = $row['lon'];
$fname = $row['fname'];
$address = $row['address'];
echo("addMarker($lat, $lon, '<b>$fname</b><br />$address');\n");
$ageSelected = $valAge;
$empSelected = $valEmp;
$genSelected = $valGen;
}
}
}
I have this error:
mysql_fetch_array() expects parameter 1 to be resource, integer given
in C:\xampp\htdocs\admin\mapcon.php on line 20
On your if statement you are not comparing the value:
if ($result = 0) { ....
You are setting 0 to $result.
You should use
if ($result == 0) { ...

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

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

Categories

Resources