JSON_encode not outputting anything - javascript

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!

Related

My AJAX not outputting properly for chart

Does anyone have any idea why my AJAX function is returning each character individually. E.g.
testNew.html:150 i
testNew.html:150 t
testNew.html:150 e
testNew.html:150 m
It should be returning full words on a chart. But its printing individual letters on the console and is printing undefined on the chart.
AJAX code in javascript
$(document).ready(function(){
$.ajax({
url: "BaseClass.php",
data: { action : 'getResults' },
datatype: "application/json",
method: "GET",
success: function(data) {
console.log(data); // Produces the whole array of data from the php query fine.
var item = [];
var freq = [];
for(var i in data) {
console.log(data[i]); //produces each letter individually
item.push("Item " + data[i].item_description);
freq.push(data[i].item_id);
}
console.log(data[0].item_description); //Outputs undefined
var chartdata = {
labels: item,
datasets : [
{
label: '...',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: freq
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
MySQLDao.php - holds all the queries, gets result of the queries and sends to javascript:
<?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 * FROM item";
$result = $this->mysqli->query($sql);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
return $data;
}
}
?>
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);
echo "Your message : ", json_encode($result);
exit();
}
?>

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, 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?

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

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>

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