Failed to save information in JSON format

I'm currently facing an issue with JSON while trying to implement a register and login feature. The data fails to be stored as intended.

Here is the JSON response I am receiving in the log:

02-24 08:24:47.878: E/JSON(2017): {"tag":"register","success":0,"error":1,"error_msg":"Error occured in Registartion"}

This snippet shows my PHP code for storing the data:

<?php
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];

// include db handler
require_once 'DB_Function.php';
$db = new DB_Functions();

// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);

// check for tag type
if ($tag == 'login') {
    ...
} else if ($tag == 'register') {
    ...
} else {
    echo "Invalid Request";
}
} else {
echo "Access Denied";
}
?>

The userfunction class is shared between the login and registration functions:

public class UserFunctions {

private JSONParser jsonParser;
...
}

Answer №1

If you're encountering issues, it might be because you are passing parameters through the GET method but attempting to parse POST content in your PHP script when it's empty. Consider using

jsonParser.makeHttpRequest(registerURL, "POST", params);
instead of
jsonParser.makeHttpRequest(registerURL, "GET", params);

Answer №2

<?php

class UserDatabase {

private $database;

//put your code here
// constructor
function __construct() {
    require_once 'DB_Connection.php';
    // connecting to database
    $this->database = new DB_Connection();
    $this->database->connect();
}

// destructor
function __destruct() {

}

/**
 * Storing new user
 * returns user details
 */
public function createUser($username, $email, $password) {
    $userid = uniqid('', true);
    $hash = $this->hashPassword($password);
    $encrypted_password = $hash["encrypted"]; // encrypted password
    $salt = $hash["salt"]; // salt
    $result = mysql_query("INSERT INTO users(user_id, username, email, encrypted_password, salt, created_at) VALUES('$userid', '$username', '$email', '$encrypted_password', '$salt', NOW())");
    // check for successful store
    if ($result) {
        // get user details 
        $uid = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
        // return user details
        return mysql_fetch_array($result);
    } else {
        return false;
    }
}

/**
 * Get user by email and password
 */
public function getUserByEmailAndPassword($email, $password) {
    $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
    // check for result 
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        $result = mysql_fetch_array($result);
        $salt = $result['salt'];
        $encrypted_password = $result['encrypted_password'];
        $hash = $this->checkPasswordHash($salt, $password);
        // check for password equality
        if ($encrypted_password == $hash) {
            // user authentication details are correct
            return $result;
        }
    } else {
        // user not found
        return false;
    }
}

/**
 * Check user is existed or not
 */
public function isUserRegistered($email) {
    $result = mysql_query("SELECT email from users WHERE email = '$email'");
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        // user existed 
        return true;
    } else {
        // user not existed
        return false;
    }
}

/**
 * Encrypting password
 * @param password
 * returns salt and encrypted password
 */
public function hashPassword($password) {

    $salt = sha1(rand());
    $salt = substr($salt, 0, 10);
    $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
    $hash = array("salt" => $salt, "encrypted" => $encrypted);
    return $hash;
}

/**
 * Decrypting password
 * @param salt, password
 * returns hash string
 */
public function checkPasswordHash($salt, $password) {

    $hash = base64_encode(sha1($password . $salt, true) . $salt);

    return $hash;
}

}

?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to extract tweet text from a json file for advanced analysis?

I have implemented a code snippet that utilizes the Twitter API to retrieve tweets based on a user-input search term and save them in a JSON file. My main focus is solely on extracting the actual tweet text and discarding any other information. Could you ...

Leveraging Bash to modify VS Code Configuration

I have been attempting to utilize the npm package.json in order to modify VS Code settings through a bash script. I came across a helpful resource on How to change VS Code settings from terminal (bash), which has guided me towards achieving my desired outc ...

What is the recommended strategy for handling and retrieving std::chrono::duration::milliseconds in cpprest?

Here is a simplified code example: //... std::chrono::milliseconds _delay; //field to be handled unsigned long getDelay() const { return _delay.count(); } void setDelay(unsigned long delay) { _delay = std::chrono::milliseconds(delay); } json:: ...

Is AJAX malfunctioning while the success function is functioning properly?

the function for success is operational, however the data isn't being saved in the database $(document).ready(function() { $("#ChatText").keyup(function(e){ if(e.keyCode == 13) { var ChatText = $("#ChatText").val(); ...

Tips for choosing a random date and time within a specified range using PHP

I am attempting to randomly select a date between two specified dates. One of the dates is random, while the other is fixed. Additionally, there is a starting date that serves as the basis for generating the random date. To clarify my objective, here is an ...

unable to locate the log generated by a test php elastic beanstalk web application

Recently, I delved into the world of Amazon AWS and decided to experiment with creating a PHP application on Elastic Beanstalk. Opting for the sample application that is automatically generated, I launched my instance successfully and was able to view the ...

Issue with loading TopoJSON data into React's simple maps library

I've been following the tutorial for react-simple-maps npm documentation in order to set up a map and experiment with it. The code snippet I'm using is from the usage section at the provided link: https://www.npmjs.com/package/react-simple-ma ...

Detect if the user is using Internet Explorer and redirect them to a different

My web application is having trouble rendering in Internet Explorer. In the meantime, I would like to detect if the user is using IE and redirect them to a different page specifically for IE visitors. What is the best way to accomplish this? Should I use ...

CSS background image referencing in React to the public folder's path

I am currently working on a project using Create-React-App and I am trying to set a background image for my header section. Here is how I'm attempting to do it: background-image: url('~/Screenshot_11.png'); However, I encountered an error w ...

Using PDO Prepared Statements to Update Column Value

Can you explain the process of using prepared statements and bound parameters to update a value in a column? Here is an example: $stmt = "UPDATE users SET name = :name WHERE name = :name"; $stmt->bindParam(:name, $oldName); $stmt->bindParam(: ...

using PHP, learn how to calculate the difference between two dates

I am working on a PHP project where I need to subtract one date from another and display the result in days, hours, minutes, and seconds format. However, the code I tried using timestamps is not giving me accurate values. Can someone please suggest a bette ...

Transferring information from ReactJs via the fetch API to a nodeJs server

I've encountered an issue where I am sending JSON data from my React application using the Fetch API, but on the server side, the req.body is showing up as empty. I'm not sure what the problem could be. Here is a snippet of my React code: impor ...

Is there a way to determine if a specific JSONArray is contained within my existing JSONArray?

I am faced with the challenge of parsing a JSONArray that may or may not include an "attachmentPoint" element. Here is an example of the JSONArray structure: [{"entityClass":"DefaultEntityClass","mac":["86:2b:a2:f1:2b:9c"],"ipv4":["10.0.0.1"],"ipv6":[], ...

Attempting to input data into elements that have been generated automatically

Trying to set values to elements with automatically generated id's: This code is functional: <input type="tekst" id="<?php echo $item->getId();?>"> <script> document.getElementById("<?php echo $item->getId();?>").v ...

I am encountering an issue while attempting to retrieve JSON data from an API as I encounter an error every time I attempt to concatenate within a while

I am attempting to retrieve data from a specific table () on the official Centers for Medicare & Medicaid Services website using their API. Due to the limitation of the API providing only 500 rows per request, I have implemented a while loop in my code. ...

Composer is unable to locate the Class with the error message: "Fatal error: Uncaught Error: Class Not Found"

I've been trying to utilize this PHP wrapper from larislackers/php-binance. I've already installed it, but for some reason, the class BinanceApiContainer is not being found. This is my code: <?php require 'C:\Users\Francisco ...

Tips for using a JavaScript variable in a PHP file on WordPress

As a newcomer to Wordpress, I am trying to navigate the Theme Editor. Within it, I found a javascript file that looks like this: const isMenuOpen = false; function toggleMenu() { alert("toggle"); isMobileMenuOpen = !isMobileMenuOpen; } ...

An AJAX response encountered a JSON parsing error along with an HTML comment

Reviewing the attached image reveals data returned from an ajax call to a PHP script. The array displayed is formed by the script, but for unknown reasons, it includes an HTML comment before the array. <!-- translation function --> The origin and ...

Export a list from R to Julia using JSON format

Imagine you have a list in R like this: x = list(a=1:3,b=8:20) You then save this to a JSON file on disk using the following code: library(jsonlite) cat(toJSON(x),file="f.json") Now, how can you read this JSON file using the Julia JSON package? Is it p ...

Unable to locate the appropriate constructor for com.eviware.soapui.support.XmlHolder using java.io.StringWriter as an argument

I am attempting to compare database values with API values using soapui in the same testcase but different steps. The first step involves retrieving a list from the database, while the second step involves comparing these values to the API. Database resp ...