Unexpected results when passing values from PHP to Ajax using json_encode - php

Goal: Develop a registration form for a website
Problem: PHP returns unexpected results to Ajax using the json_encode function (for example, it returns DUPLICATE_USERNAME when it should return DUPLICATE_EMAIL).
Code explanation / algorithm:
User enters their details in the registration form (username, email, etc.)
When submit button is clicked, the input is acquired by a PHP script (registrationProcess.php) via POST
A database check is run so that the username and email are available (here we suppose that they aren't)
PHP returns the value back to the front-end via Ajax. It returns two strings, either DUPLICATE_USERNAME or DUPLICATE_EMAIL; the function that does this is handleRegisterError($error_type)
Depending on the returned string, the UI of the webpage is properly changed
This function is a part of a script that gets called after the submit button is clicked.
<?php
/**
* This function gets called in the PHP script if a registration error has been found. It is passed either DUPLICATE_USERNAME or DUPLICATE_EMAIL.
*/
function handleRegisterError($error_type) {
switch($error_type) {
case "DUPLICATE_USERNAME":
$data = array("error" => "DUPLICATE_USERNAME");
echo json_encode($data);
break;
case "DUPLICATE_EMAIL":
$data = array("error" => "DUPLICATE_EMAIL");
echo json_encode($data);
break;
default:
echo "Unexpected error in registrationProcess.php"
break;
}
}
/>
Now, the JavaScript code on the front-end HTML registration page that receives the code:
<script>
$.ajax({
dataType: 'json',
url: "../php/registrationProcess.php",
success: function(data) {
console.log("SUCCESS: " + data.error);
handleError(data.error);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("ERROR CALLING AJAX! textStatus = " + textStatus + " | errorThrown = " + errorThrown);
}
});
function handleError(errorType) {
console.log("errorType = " + errorType);
switch(errorType) {
case "DUPLICATE_USERNAME":
// Display duplicate username error
$("#username-error").attr("hidden", false);
$("#username-input-field").css("margin-bottom", 8);
break;
case "DUPLICATE_EMAIL":
// Display duplicate email error
$("#email-error").attr("hidden", false);
$("#email-input-field").css("margin-bottom", 8);
break;
}
}
</script>
The receiving code consists of the basic Ajax form to receive results from PHP. It passes the received variable (data.error) to the handleError function, which in turn consists of a switch statement that changes the UI for a duplicate username/email error.
Debugging:
When PHP sends values from json_encode, it echoes the JSON code it is transmitting to the website, so I can easily see what the PHP transmits as JSON. For JavaScript debugging, I used the console.log function to print "SUCCESS", followed by the data.error (which should be similar to the value transmitted by PHP). The error that is used in JavaScript is then repeatedly printed to console from the handleError function just to be safe.
You can see an example of both sources of debugging I used to analyse the errors in these two images, where the JSON that is transmitted from PHP is seen on the top left and the console is seen on the right side of the image:
Problem analysis
I have placed the following user into the database:
username: Mike
email: mikey#gmail.com
To test the code, I've then run two separate tests: In the first test, I tried to create another username with the name Mike and a different email (which is expected to return a DUPLICATE_USERNAME error). In the second test, I tried to create another username with the name Jenna and the email mikey#gmail.com, which is expected to cause a DUPLICATE_EMAIL error.
My code successfully dealt with the first case, when the username was duplicated:
However, in the second case, PHP correctly recognised a DUPLICATE_EMAIL error, but the JavaScript / Ajax somehow interpreted that as DUPLICATE_USERNAME when it was being sent over.
What am I doing wrong in my code that is causing this bug? Is it maybe some state on the webpage that is being saved from previous data transmissions?
Thank you for the time taken to deal with this problem!
The script for registrationProcess.php:
<?php
include 'secureFunctions.php';
$username = "";
$birthday = "";
$gender = "";
$email = "";
$password = "";
$username = getVariable('username');
$birthday = getVariable('birthday');
$gender = getVariable('gender');
$email = getVariable('email');
$password = getVariable('password');
$db_host = "sql7.freesqldatabase.com";
$db_username = "sql7369409";
$db_password = "*******";
$db_name = "sql7369409";
$conn = new mysqli($db_host, $db_username, $db_password, $db_name);
if(mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error);
}
if($gender != "") {
// Edit gender for the database
switch ("gender") {
case "male":
$gender = "m";
break;
case "female":
$gender = "f";
break;
case "other":
$gender = "o";
break;
}
}
if($birthday != "") {
// Edit birthday for the database
$arr = explode('/', $birthday);
$birthday = $arr[2] . '-' . $arr[1] . '-' . $arr[0];
}
$sql = "INSERT INTO users (id, username, birthday, gender, email, password)
VALUES (NULL, '$username', '$birthday', '$gender', '$email', '$password')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully!";
header("Location: ../pages/index.html");
exit();
}
else {
handleRegisterError(registrationGetErrorType(mysqli_error($conn)), "TRUE");
}
function handleRegisterError($error_type, $devValue) {
//echo "errorType = $error_type ";
if($devValue == "TRUE") {
/*
switch ($error_type) {
case "DUPLICATE_USERNAME":
//echo "test2";
$data = array("error" => "DUPLICATE_USERNAME");
echo json_encode($data);
break;
case "DUPLICATE_EMAIL":
//echo "test1";
$data = array("error" => "DUPLICATE_EMAIL");
echo json_encode($data);
break;
case "UNKNOWN":
$data = array("error" => "UNKNOWN");
echo json_encode($data);
break;
}
*/
//$data;
if($error_type == "DUPLICATE_USERNAME") {
//echo " t1 ";
$data = array("error" => "DUPLICATE_USERNAME");
//echo json_encode($data);
} elseif($error_type == "DUPLICATE_EMAIL") {
//echo " t2 ";
$data = array("error" => "DUPLICATE_EMAIL");
//echo json_encode($data);
} else {
$data = array("error" => "UNKNOWN");
//echo json_encode($data);
}
echo json_encode($data);
}
}
?>
The above script also uses some methods from secureFunctions.php:
<?php
/**
* Retrieves a variable from HTML using the null coalesce operator (for security reasons)
* #param mixed $variableName
* #return void
*/
function getVariable($variableName) {
$result = $_POST[$variableName] ?? '';
return $result;
}
/**
* There are two types of registration errors: (1) username already in use (2) email already in use or (3) Unknown error
* First two errors look like this:
* (1): Duplicate entry 'skorjanc.survey#gmail.com' for key 'email'
* (2): Duplicate entry 'King_Fish' for key 'name'
*
* #param mixed $sqlDbText The error text from the server
* #return (1) DUPLICATE_USERNAME (2) DUPLICATE_EMAIL (3) UNKNOWN
*/
function registrationGetErrorType($sqlDbText) {
$filtered = str_replace("'", "", $sqlDbText); // Replace single quotes with air
$array = explode(" ", $filtered);
$key = $array[count($array)-1];
if($key == "email") {
return "DUPLICATE_EMAIL";
} elseif($key == "name") {
return "DUPLICATE_USERNAME";
}
return "UNKNOWN";
}
?>
As ArJay suggested, I am also attaching values of $array and $key in the registrationGetErrorType method for both cases (duplicate username and duplicate password):
(1) DUPLICATE_USERNAME
array = Array ( [0] => Duplicate [1] => entry [2] => King_Fish [3] => for [4] => key [5] => name )
key = name
(2) DUPLICATE EMAIL
array = Array ( [0] => Duplicate [1] => entry [2] => skor#gmail.com [3] => for [4] => key [5] => email )
key = email

I have found the cause of the problem.
When the submit button was clicked, all the values were actually sent to the correct PHP script from the form. The values were processed and the correct JSON object with the correct error was returned.
Then, however, the page refreshed because of the submit button functionality. Now, all of the form variables were set back to empty, such as username = "", email = "" etc. Those variables were again used by the same script and tested against existing database records, which in turn resulted in the wrong second error (DUPLICATE_USERNAME instead of DUPLICATE_EMAIL).
It seems that I have hit an algorithm error, as I have devised the code flow in such a way as to cause errors. I have, however, found a great tutorial on creating register/login pages, whose code I have tested (and it works!) - follow this link.
Thanks to everyone, specifically Peter Mortensen, for the patience on this error!

Related

No data passed using UnityWebRequest POST

I'm trying to retrieve some data from a MySQL database through php POST method to Unity.
But somehow, when I use the UnityWebrequest the post variable is always empty.
My C# script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class IDCheck : MonoBehaviour
{
int onlineID = -1;
readonly string urlCheckIdentifier = "http://www.mywebsite.php";
void Start(){
if (Application.internetReachability != NetworkReachability.NotReachable){
StartCoroutine("GetOnlineID");
}
}
void SetID(int _id){
onlineID = _id;
}
IEnumerator GetOnlineID(){
// TEST NUMBER 2
List<IMultipartFormSection> form = new List<IMultipartFormSection>();
form.Add(new MultipartFormDataSection("onlineid", "test"));
/* THIS WAS ATTEMPT NUMBER 1
WWWForm form = new WWWForm();
form.AddField("onlineid", "test");
*/
UnityWebRequest www = UnityWebRequest.Post(urlCheckIdentifier, form);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError){
Debug.Log("Error on upload");
} else {
Debug.Log(www.downloadHandler.text);
DownloadData data = JsonUtility.FromJson<DownloadData>(www.downloadHandler.text);
bool idFound = (data.succes == false)?false:true;
if (!idFound){
Debug.Log("Didnt work");
Debug.Log(data.succes);
} else {
SetID(data.id);
Debug.Log(onlineID);
}
}
}
}
My PHP script:
<?php
include_once 'dbconnect.php';
// UNIQUE DEVIDE ID IS GIVEN FROM THE APP VIA POST METHOD
$onlineid = $_POST["onlineid"];
// CHECK IF ID EXISTS IN CURRENT USERS TABLE
$query = "SELECT id, username FROM users WHERE uniqueID='$onlineid'";
$result = mysqli_query($dbconnection, $query);
$row = mysqli_fetch_row($result);
if($row){
// IF ID WAS FOUND, RETURN JSON TO THE APP
$dataArray = array('success' => true, 'error' => '', 'id' => $row[1], 'username' => $row[2], 'TESTuniqueIDPassed' => $onlineid);
} else {
// ID WAS NOT FOUND, CREATING NEW ONE.
$query2 = "INSERT INTO users(uniqueID) VALUES ('$id')";
$result2 = mysqli_query($dbconnection, $query2);
// GETTING THE NEWLY CREATED ID FROM THE DB.
$query3 = "SELECT id, username FROM users WHERE uniqueID='$id'";
$result3 = mysqli_query($dbconnection, $query3);
$row3 = mysqli_fetch_row($result3);
// RETURNING JSON WITH THE NEW ID
$dataArray = array('success' => true, 'error' => '', 'id' => $row3[1], 'username' => $row3[2], 'TESTuniqueIDPassed' => $onlineid);
}
header('Content-Type: application/json');
//echo json_encode($dataArray);
echo $onlineid;
?>
As you can see I even tried to just echo the $onlineid which should be populated with the POST method from unity, but that's always returning an empty string.
I've tried google of course but most posts about this subject are pretty old.
The solution to add
www.chunkedTransfer = false;
in front of the yield return call is now depreciated, and another suggested solution was to put
www.useHttpContinue = false;
in front of the yield return also did nothing to solve the problem.
Anybody any ideas where to go from here?
Regards,
Mark
I've tried a couple of things in the meantime while waiting for an anwser.
Stumbled upon an anwser myself so I will post it for the next person to have the same issue:
Your link should start with https instead of http, because Unity does not allow insecure links anymore.
Using MultipartFormDataSection still wont work, but WWWForm will!

How do I use HTTP:PostAsync() to submit JSON data to my server? (ROBLOX)

So I understand how GetAsync works, and I have scripts on my server that work with what I'm trying to accomplish. But in terms of getting data to the server instead of reading it from a json, how would I do that? On the server side, my PHP Script that gets all the post data from the submitted JSON and checks a database with all the information and if its not there, it inserts it. (It's a ban system. But I'm not sure if I have roblox-side set up correctly or if i have server-side set up correctly. Here's my code:
This is running within Custom Adonis Admin System
SendWebBan = function(plr,UserID,Username,Agent,Comment)
local http = game:GetService("HttpService")
local Reason = "Banned in game by AAC Admin."
local url = "URL HERE/gamebanlistener.php"
local data = {
["UserID"] = UserID,
["Username"] = Username,
["Agent"] = Agent,
["Reason"] = Reason,
["Comment"] = Comment
}
local encode = http:JSONEncode(data)
local reponse,err = pcall(function()
http:PostAsync(url,encode)
end)
print(reponse)
if reponse == "false" then
Remote.MakeGui(plr,"Notification",{
Title = "Failed";
Message = "Ban Failed";
Duration = 10;
})
elseif reponse == "true" then
Remote.MakeGui(plr,"Notification",{
Title = "Success";
Message = "Ban Successful";
Duration = 10;
})
else
Remote.MakeGui(plr,"Notification",{
Title = "Failed";
Message = "Ban Failed";
Duration = 10;
})
end
end;
<?php
$ServerKey = "key here";
$APIKey = $_POST["key"];
$Data = json_decode($_POST['data']);
$UserID = $Data.UserID;
$Username = $Data.Username;
$Agent = $Data.Agent;
$Reason = $Data.Reason;
$Comment = $Data.Comment;
$Date = date("d/m/Y");
if($APIKey == $ServerKey){
//$conn = mysqli_connect($host,$dbuser,$dbpassword,$db);
$Connection = mysqli_connect(sql credentials here);
if($Connection->connect_errno)
{
echo('{"Status":"'. $Connection->connect_errno . '"}');
}else {
$BlacklResult = $Connection->query("SELECT * FROM bans"); //Blacklist is the name of my Bans database
if($BlacklResult->num_rows > 0)
{
while($Row = $BlacklResult->fetch_assoc()){
if($Row != null){
if($Row["UserID"] == $UserID){
echo 'Status:false';
return;
}else{
$Connection->query("INSERT INTO bans(UserID, Username, Agent, BanReason, BanComment,DateOfBan) VALUES(".$UserID.",".$Username.",".$Agent.",".$Reason.",".$Comment.",".$Date.");");
echo 'Status:true';
}
};
};
};
};
}else {
echo('{"Status":"API KEY"}');
};
?>
When you pcall a function, the tuple that is returned is a bool followed by the result of the function. If the function throws an error, then result is replaced with the error string. Try making this change :
local success, result = pcall(function()
return http:PostAsync(url,encode)
end)
print(success, result)
if success then
-- request went through, parse the response from your endpoint
else
-- parse the http error
end

Checked the query, database, table names, column names, etc. Still have no idea why this error occurred

The error that I occurred:
Fatal error: Call to a member function bind_param() on boolean in C:\wamp64\www\APU\SDP\reg-list-function.php on line 82
I'm writing a php script where the Admins are able to approve the registration of the user. I've checked through the formats of my database, column names, and even query, and still I've no idea why this error pops out. Any help or suggestions will be appreciated!
<?php
// we will only start the session with session_start() IF the session isn"t started yet //
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
?>
<?php
// including the conn.php to establish connection with database //
include "conn.php";
?>
<?php
// Begin of the function: Registration List's Verification Form: Registration //
// First we check the form has submitted or not //
if (isset($_POST['submit-list-reg'])) {
// If it is, then we will retreive data from the input forms //
$regid = $_POST["regid"];
$reg_acccode = mysqli_real_escape_string($con, $_POST['reg-acccode']);
$reg_pw = mysqli_real_escape_string($con, $_POST['reg-pw']);
// Taking the current time //
date_default_timezone_set("Etc/GMT-8");
$now = date("Y-m-d H:i:s");
// Variable to store Error Message //
$error = '';
// Alphanumeric Generator //
function random_strings($length_of_string) {
// String of all alphanumeric character
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Shufle the $str_result and returns substring
// of specified length
return substr(str_shuffle($str_result), 0, $length_of_string);
}
// Sorting out the query related to the function //
// Verify the user is an admin or not //
$VERFYADMIN = "SELECT * FROM user
WHERE status = 2 AND active = 1 AND account_code = '".md5($reg_acccode)."' AND password = '".md5($reg_pw)."'";
$VERFYADMINQ = mysqli_query($con, $VERFYADMIN);
//***BEGIN OF PROCESS***//
if (mysqli_num_rows($VERFYADMINQ) < 1) {
// if the admin is not verified, then inform the user and send him back to admin panel //
echo "<script>alert('ALERT: Information unable to be verified. Please try again.');";
echo "window.location.href='admin_panel.html';</script>";
exit(0);
} else {
// begin the process of registration //
while (list($key,$val) = #each ($regid)) {
// Now to verify the user's legitimacy //
// Take the user's vercode into variable first //
$USERVERCODE = "SELECT * FROM registration_list
WHERE registration_id = $val AND verified = 0";
$USERVERCODEQ = mysqli_query($con, $USERVERCODE);
if (mysqli_num_rows($USERVERCODEQ) < 1) {
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the data. Please try again.');";
echo "</script>";
} else {
while ($row = mysqli_fetch_array($USERVERCODEQ)) {
$vercode = $row["verification_code"];
}
// since we got the value of the vercode then we start to define the query //
$VERCODE = "SELECT * FROM verification_code WHERE verification_code = $vercode AND code_active = 1";
$VERCODEQ = mysqli_query($con, $VERCODE);
if (mysqli_num_rows($VERCODEQ) < 1) {
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the info of VERCODE. Please try again.');";
echo "</script>";
} else {
while ($row = mysqli_fetch_array($VERCODEQ)) {
$status = $row["code_status"];
}
// we will first insert the user main information into the database: i.e. password, username, etc. //
$account_code = random_strings(8);
$APPROVE = "INSERT INTO user (username, password, email, account_id, account_code, active, status, registered_date, verification_code)
SELECT username, password, email, account_id, '".md5($account_code)."', 1, $status, $now, verification_code
FROM registration_list
WHERE registration_id = ?";
$stmt = $con->prepare($APPROVE);
$stmt->bind_param("i", $val); // Problem around here //
$stmt->execute();
if (($stmt->error) == FALSE) {
I expect the process will be no issue at all as I've checked everything and nothing seems wrong to me.
Reformatting your code to make it more legible and easier to understand, we now have:
<?php
// we will only start the session with session_start() IF the session isn"t started yet //
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
?>
<?php
// including the conn.php to establish connection with database //
include "conn.php";
?>
<?php
// Begin of the function: Registration List's Verification Form: Registration //
// First we check the form has submitted or not //
if (isset($_POST['submit-list-reg']))
{
// If it is, then we will retreive data from the input forms //
$regid = $_POST["regid"];
$reg_acccode = mysqli_real_escape_string($con, $_POST['reg-acccode']);
$reg_pw = mysqli_real_escape_string($con, $_POST['reg-pw']);
// Taking the current time //
date_default_timezone_set("Etc/GMT-8");
$now = date("Y-m-d H:i:s");
// Variable to store Error Message //
$error = '';
// Alphanumeric Generator //
function random_strings($length_of_string)
{
// String of all alphanumeric character
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Shufle the $str_result and returns substring
// of specified length
return substr(str_shuffle($str_result), 0, $length_of_string);
}
// Sorting out the query related to the function //
// Verify the user is an admin or not //
$VERFYADMIN = "SELECT * FROM user
WHERE status = 2 AND active = 1 AND account_code = '".md5($reg_acccode)."' AND password = '".md5($reg_pw)."'";
$VERFYADMINQ = mysqli_query($con, $VERFYADMIN);
//***BEGIN OF PROCESS***//
if (mysqli_num_rows($VERFYADMINQ) < 1)
{
// if the admin is not verified, then inform the user and send him back to admin panel //
echo "<script>alert('ALERT: Information unable to be verified. Please try again.');";
echo "window.location.href='admin_panel.html';</script>";
exit(0);
}
else
{
// begin the process of registration //
while(list($key,$val) = #each ($regid))
{
// Now to verify the user's legitimacy //
// Take the user's vercode into variable first //
$USERVERCODE = "SELECT * FROM registration_list WHERE registration_id = $val AND verified = 0";
$USERVERCODEQ = mysqli_query($con, $USERVERCODE);
if (mysqli_num_rows($USERVERCODEQ) < 1)
{
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the data. Please try again.');";
echo "</script>";
}
else
{
while ($row = mysqli_fetch_array($USERVERCODEQ))
{
$vercode = $row["verification_code"];
}
// since we got the value of the vercode then we start to define the query //
$VERCODE = "SELECT * FROM verification_code WHERE verification_code = $vercode AND code_active = 1";
$VERCODEQ = mysqli_query($con, $VERCODE);
if (mysqli_num_rows($VERCODEQ) < 1)
{
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the info of VERCODE. Please try again.');";
echo "</script>";
}
else
{
while ($row = mysqli_fetch_array($VERCODEQ))
{
$status = $row["code_status"];
}
// we will first insert the user main information into the database: i.e. password, username, etc. //
$account_code = random_strings(8);
$APPROVE = "INSERT INTO user (username, password, email, account_id, account_code, active, status, registered_date, verification_code)
SELECT username, password, email, account_id, '".md5($account_code)."', 1, $status, $now, verification_code
FROM registration_list
WHERE registration_id = ?";
$stmt = $con->prepare($APPROVE);
$stmt->bind_param("i", $val); // Problem around here //
$stmt->execute();
if (($stmt->error) == FALSE)
{
In here are several things that I wouldn't personally do. As has been mentioned, using variables supplied by user input, even MD5 ones, directly in SQL queries should be best avoided.
The line "while(list($key,$val) = #each ($regid))", which sets the $val variable has an ampersand to suppress any error messages, this in turn could be causing you issues further down. It's best not to suppress these messages, but to find out why they are occurring, this could be the cause of a non numeric value being passed to your "bind_param" function. I'd also use single quotes instead of double quotes with the function as well.
Solved after I changed the variables that contained string value with this format -> ' " . $variable . " ' .

$.ajax type post is empty in PHP $_POST

The ajax request works fine in the javascript part but when it comes to PHP the POST is erased and it is not passing only one value.
The ajax looks like this:
function goals() { //dynamically added forms with their corresponding inputs to be posted
setForms.forEach(function(formIndex) { //the forms that are added and their index
var formData = {
'email': "<?php echo $_SESSION["email"]; ?>", //session email works fine
'goalRow': formIndex,
'motivation': $("#goals"+formIndex+"-1").val(), //formIndex works fine adding the right number to get the values
'priority': $("#goals"+formIndex+"-2").val(),
'goal': $("#goals"+formIndex+"-3").val(),
'measure': $("#goals"+formIndex+"-4").val(),
'endDate': $("#goals"+formIndex+"-5").val(),
'phase1': $("#goals"+formIndex+"-6").val(),
'phase2': $("#goals"+formIndex+"-7").val(),
'phase3': $("#goals"+formIndex+"-8").val(),
'notes': $("#goals"+formIndex+"-9").val(),
'notification': $("#goals"+formIndex+"-10").val(),
'frequency': $("#goals"+formIndex+"-11").val(),
'notificationStart': $("#goals"+formIndex+"-12").val(),
};
$.ajax({ //posting the form
type: "POST",
url: "?service=goalsabroad-api", //page for the action
data: formData, //data object
success: function() { //log to make sure data is passed
console.log(formData);
}
});
});
}
Data is PASSED correctly and everything appears when logging for ALL FORMS without a problem. But when I get to the PHP page it says Undefined index:
Chrome dev tab shows status 200 and logs correctly. When opening in new tab I see the PHP errors.
PHP looks like this:
<?php
var_dump($_POST);
$email = $_POST["email"];
$goalRow = $_POST["goalRow"];
$motivation = $_POST["motivation"];
$priority = $_POST["priority"];
$goal = $_POST["goal"];
$measure = $_POST["measure"];
$endDate = $_POST["endDate"];
$phase1 = $_POST["phase1"];
$phase2 = $_POST["phase2"];
$phase3 = $_POST["phase3"];
$notes = $_POST["notes"];
$notification = $_POST["notification"];
$frequency = $_POST["frequency"];
$notificationStart = $_POST["notificationEnd"];
$query = "SELECT email FROM goalsabroad WHERE email = '$email' AND goalRow = '$goalRow'";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) === 0) {
echo "empty";
$query = "INSERT INTO goalsabroad (email, goalRow, motivation, priority, goal, measure, endDate, phase1, phase2, phase3, notes, notification, frequency, notificationStart)
VALUES ('$email', '$goalRow', '$motivation', '$priority', '$goal', '$measure', '$endDate', '$phase1', '$phase2', '$phase3', '$notes', '$notification', '$frequency', '$notificationSart')";
echo $query;
mysqli_query($connect, $query);
} else {
$query = "UPDATE goalsabroad SET motivation = '$motivation'
AND priority = '$priority'
AND goal = '$goal'
AND measure = '$measure'
AND endDate = '$endDate'
AND phase1 = '$phase1'
AND phase2 = '$phase2'
AND phase3 = '$phase3'
AND notes = '$notes'
AND notification = '$notification'
AND frequency = '$frequency'
AND notificationStart = '$notificationStart'
WHERE email = '$email' AND goalRow = '$goalRow'";
echo $query;
mysqli_query($connect, $query);
}
?>
The ajax post must be successful because query is ran and new rows are added as expected BUT only email field adds to the query everything else is empty (and the echo $query returns empty fields even email, and var_dump($_POST) also returns array(0) {}
The .htaccess file redirects .php to the 'extensionless' format that is why url has no .php (but I tried both) like every other parameter of this post.
I basically checked every stackoverflow post about this topic but I could not find anything to make it work, maybe I am the problem but I did not have someone else to click the button for me...maybe I just stressed myself so much on this I can't see the obvious. Thank you for your help.
In you PHP script you have:
$notificationStart = $_POST["notificationEnd"];
But your Ajax call is sending
'notificationStart': $("#goals"+formIndex+"-12").val(),
When looking for $_POST['notificationEnd'] it will be an undefined index.

How to pass special characters through php from a mssql database

I have this code is working fine my application gets the data with json and is all fine but when I insert special characters like ñ which I need to get I can't have been told that I should use the utf8_encode but I just don't know how to apply it here since.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
if (isset($_POST['mod']) && isset($_POST['lec']) && isset($_POST['clase']))
{
$mod = $_POST['mod'];
$lec = $_POST['lec'];
$clase = $_POST['clase'];
//Create query to retrieve all contacts
$query = 'SELECT TituloEjercicio,PreguntaEjercicio,Opcion1Ejercicio,Opcion2Ejercicio,Opcion3Ejercicio,Opcion4Ejercicio,EstaCorrectaEjercicio FROM ejercicios WHERE QueModulo = ? and QueLeccion = ? and Queclase = ?';
$params = array($mod,$lec,$clase);
$stmt = sqlsrv_query($connectionInfo->conn, $query,$params);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("lbl_variable_cuestionario_titulo" => $row['TituloEjercicio'],
"lbl_variable_pregunta" => $row['PreguntaEjercicio'],
"opcion1" => $row['Opcion1Ejercicio'],
"opcion2" => $row['Opcion2Ejercicio'],
"opcion3" => $row['Opcion3Ejercicio'],
"opcion4" => $row['Opcion4Ejercicio'],
"EstaCorrecta" => $row['EstaCorrectaEjercicio']
);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
sqlsrv_close($connectionInfo->conn);
}
}
sqlsrv_close($connectionInfo->conn);
}
sqlsrv_close($connectionInfo->conn);
?>
If your issue lies with pushing non-latin characters to MySQL then you might just have to configure your database to use UTF8. There are good tutorials online that show you how to do that.

Categories