Why does a Javascript function, issued from PHP not found? - javascript

I am perplexed. I have done this before and know this should work but cannot understand why the function is not found. Perhaps a second set of eyes will uncover the mystery.
I have tested its existence using JavaScript. See the console log below.
PHP (skip to the end to see statement).
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once "dbconnect.php";
$uploadDirectory = '/home/deje/public_html/writers-tryst/uploads/'; //specify upload directory ends with / (slash)
require_once "dbconnect.php";
$result = 0;
$File_Name = basename($_FILES['file2upload']['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.')); //get file extention
$Random_Number = rand(0, 9999999999); //Random number to be added to name.
$NewFileName = $Random_Number.$File_Ext; //new file name
$target_path = $uploadDirectory . $NewFileName;
if (#move_uploaded_file($_FILES['file2upload']['tmp_name'], $target_path)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $uploadDirectory . $NewFileName);
finfo_close($finfo);
if ($mime_type != 'application/pdf') {
unlink($UploadDirectory . $NewFileName);
$data = array('File MUST be a PDF!');
$result = 0;
} else $result = 1;
}
if (!isset($_REQUEST["title"]) || empty(trim($_REQUEST["title"])))
throw new Exception('You must enter a title.');
else {
$title = filter_var(trim($_REQUEST["title"]), FILTER_SANITIZE_STRING);
$title = htmlspecialchars_decode($title, ENT_QUOTES);
}
if (!isset($_REQUEST["userid"]) || empty(trim($_REQUEST["userid"])))
throw new Exception('Userid is missing.');
else {
$userid = filter_var(trim($_REQUEST["userid"]), FILTER_SANITIZE_STRING);
$userid = htmlspecialchars_decode($userid, ENT_QUOTES);
}
if (!isset($_REQUEST["work-type"]) || empty(trim($_REQUEST["work-type"])))
throw new Exception('You must enter a work type.');
else {
$worktype = filter_var(trim($_REQUEST["work-type"]), FILTER_SANITIZE_STRING);
$worktype = htmlspecialchars_decode($worktype, ENT_QUOTES);
}
if (!isset($_REQUEST["genre"]) || empty(trim($_REQUEST["genre"])))
throw new Exception('You must enter a title.');
else {
$genre = filter_var(trim($_REQUEST["genre"]), FILTER_SANITIZE_STRING);
$genre = htmlspecialchars_decode($genre, ENT_QUOTES);
}
if (!isset($_REQUEST["subgenre"]) || empty(trim($_REQUEST["subgenre"])))
throw new Exception('You must enter a sub-genre.');
else {
$subgenre = filter_var(trim($_REQUEST["subgenre"]), FILTER_SANITIZE_STRING);
$subgenre = htmlspecialchars_decode($subgenre, ENT_QUOTES);
}
if (!isset($_REQUEST["nbrPages"]) || empty(trim($_REQUEST["nbrPages"])))
throw new Exception('You must enter the number of pages your work contains.');
else {
$nbrPages = filter_var(trim($_REQUEST["nbrPages"]), FILTER_SANITIZE_STRING);
$nbrPages = htmlspecialchars_decode($nbrPages, ENT_QUOTES);
}
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare(
"INSERT Writers(fkAccounts, Title, WorkType, Genre, SubGenre, Filename)
VALUES(:fk, :title, :worktype, :genre, :subgenre, :filename)"
);
$stmt->bindParam(':fk', $userid, PDO::PARAM_INT, 10);
$stmt->bindParam(':title', $title, PDO::PARAM_STR, 255);
$stmt->bindParam(':worktype', $worktype, PDO::PARAM_STR, 30);
$stmt->bindParam(':genre', $genre, PDO::PARAM_STR, 100);
$stmt->bindParam(':subgenre', $subgenre, PDO::PARAM_STR, 100);
$stmt->bindParam(':filename', $NewFileName, PDO::PARAM_STR, 30);
$stmt->execute();
//echo "<script type='text/javascript'>stopUpload(" . $result . ");</script>";
?>
<script type='text/javascript'>stopUpload(1);</script>;
JS
function startUpload() {
console.log("stopUpload=" + stopUpload)
$("#userid").val(window.localStorage.getItem('user-id'));
showMessage(1, "Uploading...");
return true;
}
function stopUpload (success) {
var result = '';
if (success == 1) {
showMessage(1, "File uploaded successfully");
}
else {
showMessage(0, 'There was an error uploading the file.');
}
return true;
}
console log
stopUpload=function stopUpload(success) {
var result = '';
if (success == 1) {
showMessage(1, "File uploaded successfully");
}
else {
showMessage(0, 'There was an error uploading the file.');
}
return true; } writers.php:1 Uncaught ReferenceError: stopUpload is not defined(anonymous function) # writers.php:1
EDIT:
Please note the commented within the PHP code. That does not work either.

You are calling the function:
<script type='text/javascript'>stopUpload(1);</script>
But before you call it you need to load your JS:
<script src='./pathto/something.js'></script>; <!-- something.js declares stopUpload -->
<script type='text/javascript'>stopUpload(1);</script>

Related

How to use drag and drop with knockoutJs and php?

I'm trying for several hours, to understand the js file of knockout-binding.
Can you please help me using php to upload it to my sql server?
The following picture shows the layout of drag and drop.
This one shows the php code when the submit button is pressed to upload photos:
<?php
function resizeImage($resourceType,$image_width,$image_height,$resizeWidth,$resizeHeight) {
// $resizeWidth = 100;
// $resizeHeight = 100;
$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);
imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);
return $imageLayer;
}
session_start();
// *** Include the class
if (isset($_POST['submit'])) {
$newFileName = $_POST['filename'];
if (empty($_POST['filename'])) {
$newFileName = "gallery";
}else {
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$imageTitle = $_POST['filetitle'];
$imageDesc = $_POST['filedesc'];
$file = $_FILES['file'];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
if (in_array($fileActualExt, $allowed)){
if ($fileError === 0) {
if ($fileSize < 2000000) {
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../img/gallery/" . $imageFullName;
include_once "db_connection.php";
$sql = "SELECT * FROM users;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount + 1;
$sql = "UPDATE users SET imgFullName =?, orderGallery=? WHERE userId =?;";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed";
} else{
// Image editing
$new_width = 800;
$new_height = 600;
$sourceProperties = getimagesize($fileTempName);
$uploadImageType = $sourceProperties[2];
$sourceImageWidth = $sourceProperties[0];
$sourceImageHeight = $sourceProperties[1];
$session_id = $_SESSION['userId'];
echo $fileDestination;
mysqli_stmt_bind_param($stmt, 'sii', $imageFullName, $setImageOrder, $session_id);
mysqli_stmt_execute($stmt);
echo $fileDestination . "file destination";
echo $fileTempName . "file temp name";
switch ($uploadImageType) {
case IMAGETYPE_JPEG:
$resourceType = imagecreatefromjpeg($fileTempName);
$imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight,$new_width,$new_height);
imagejpeg($imageLayer,$fileDestination);
break;
case IMAGETYPE_GIF:
$resourceType = imagecreatefromgif($fileTempName);
$imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight,$new_width,$new_height);
imagegif($imageLayer,$fileDestination);
break;
case IMAGETYPE_PNG:
$resourceType = imagecreatefrompng($fileTempName);
$imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight,$new_width,$new_height);
imagepng($imageLayer,$fileDestination);
break;
default:
$imageProcess = 0;
break;
}
if ($stmt->error) {
echo "Failure!!! " . $stmt->error;
} else {
// move_uploaded_file($fileTempName, $fileDestination);
}
header("Location: ../putaria.php?upload=success");
}
}
}else {
echo "File size is too big!";
exit();
}
}else {
echo "You had an error!";
exit();
}
}else {
echo "You need to upload a proper file type!";
exit();
}
}
For that code, only works when I press the submit button to upload the pictures.
But in this case, I drop and drag them to the web site, and I want to know how to do it.

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!

My database won't connect

I'm not sure why my db isn't connecting. I'm basically trying to produce a website in javascript, and I'm using an AJAX to call a method in a php file. This method is a query so I can get results of this query into some of my js components. Can anyone help please? I've been stuck for ages! Any help is appreciated.
Part of my javascript file:
function callPHP() {
$.ajax ({
type: "GET",
datatype: "application/json",
url: "BaseClass.php",
data: { action : 'getResults()' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
}
//error, function(err){console.log(err)}
});
}
callPHP();
My BaseClass(The content in the comments wouldn't work):
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
$param=$_REQUEST['action'];
/*
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= 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";
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($raw_post_data, true);
$recieved = $body["data"];
//Gets the result of a query
//$result = $dao->MySQLDaoMethodName(parameters);
//Return the result of the query
echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
My conn.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
class Conn
{
public static $dbhost = "***";
public static $dbname = "***";
public static $dbuser = "***";
public static $dbpass = "***";
}
?>
MySQLDao.php(this file holds the methods I wish to call from my js file):
<?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($data)
{
$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 json_encode($result);
echo($result);
}
}
?>

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.

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