Trying to understand jquery serialization - javascript

I'm working with PHP making a form and using regular PHP it works just fine but using jquery it doesn't work anymore. I checked if it was utf-8 but the problem occurs in this method that worked in the normal submit:
public function save_to_DAO()
{
if ($this->questions)
{
try
{
$data = json_encode($this->questions);
$prev = $this->get_from_DAO();
$form = $this->questions;
if(isset($prev)){
$arr = array_merge( $prev, $form );
$data = json_encode($arr);
}
$w = file_put_contents('questions.json', $data);
if($w && $w > 0) {
return true;
}
}
catch (exception $e)
{
die ('ERROR: ' . $e->getMessage() . $this->questions);
return false;
}
}
}
This is the request:
function postQuestion(){
$('.js-submit').click(function(event){
event.preventDefault();
$.post("create_quiz_op.php", $('#qform').serialize(), getQuestions(displayQuestions));
});
}
This is the PHP handler:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$questions = [];
$cq = new CreateQuizController();
if(isset($_POST['submit']))
{
$question = new Question();
$question->set_id($_POST['id']);
$question->set_question($_POST['question']);
for ($j = 0; $j < count($_POST['answers']); $j++)
{
$question->set_answer($_POST['answers'][$j]);
}
$question->set_right_answer($_POST['right_answer']);
$questions[] = $question;
}
$cq->set_questions($questions);
if($cq->save_to_DAO())
{
print_r(json_encode($cq->get_from_DAO()));
print_r("\n");
}
else {
echo "Problema";
}
}
?>
The call reports on the browser developer tools show that it's not successful. The call reaches PHP but it is not processed successfully.

Related

I keep getting this error in my code: Error: SyntaxError: Unexpected token 'o', "object(std"... is not valid JSON

Here is my php script for the registration page, the data is still being entered into the correct table but this problem is persistent.
Edit: I've seen comments asking for the javascript code, I've included it below the php code now.
`<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
main();
function main(){
require 'connectToDB.php';
// echo "\nreached the php file";
$response = array("code" => 0, "message" => "");
$request = file_get_contents('php://input');
$jsonRequest = json_decode($request);
var_dump($jsonRequest);
if (checkForExistingUser($conn, $jsonRequest) != 0){
$response["code"] = 2;
$response["message"] = "User already exists";
}
// else if($response["code"] == 1){
// // $userID = $conn->lastInsert();
// // header("Location: UniqueUserID.php");
// exit;
// }
else{
$response = addUser($conn, $jsonRequest);
// header("Location: UniqueUserID.php");
exit;
}
// printf(json_encode($response));
// var_dump($response);
$conn = null;
return json_encode($response);
}
function checkForExistingUser ($conn, $jsonRequest){
$stmt = $conn->prepare("
SELECT COUNT(Email) as noOfUsers
FROM user_main
WHERE Email = :confirmemailadd");
// $stmt -> bindParam(':confirmemailadd', $jsonRequest->confirmemailadd);
if (isset($jsonRequest->confirmemailadd)) {
$stmt->bindValue(':confirmemailadd', $jsonRequest->confirmemailadd);
} else {
$stmt->bindValue(':confirmemailadd', '');
}
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
$noOfResults = $results[0]["noOfUsers"];
// echo($noOfResults);
return $noOfResults;
}
function addUser($conn, $jsonRequest){
$response = array("code"=>0, "message"=>"");
// echo ("Reached addUser \n");
$firstname = sanitise($jsonRequest->firstname);
$surname = sanitise($jsonRequest->surname);
$username = sanitise($jsonRequest->username);
$confirmemailadd = sanitise($jsonRequest->confirmemailadd);
$phonenum = sanitise($jsonRequest->phonenum);
$retypepassword = sanitise($jsonRequest->retypepassword);
function encryptPassword($retypepassword) {
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($retypepassword, 'AES-256-CBC', $key, 0, $iv);
$hash = hash_hmac('sha256', $encrypted, $key);
return $hash . ':' . base64_encode($iv) . ':' . base64_encode($encrypted);
}
$stmt = $conn->prepare("
INSERT INTO user_main (Name, Surname, Username, Email, PhoneNum, PWD)
VALUES (:firstname, :surname, :username, :confirmemailadd, :phonenum, :retypepassword) ");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':confirmemailadd', $confirmemailadd);
$stmt->bindParam(':phonenum', $phonenum);
$stmt->bindParam(':retypepassword', $retypepassword);
try{
$stmt->execute();
$userID = $conn->lastInsertId();
$response["code"] = 1;
$response["message"] = "successfully added";
$response["user_id"] = $userID;
}
catch (PDOException $e){
$response["code"] = 0;
$response["message"] = $e->getMessage();
}
// echo json_encode($response);
return $response;
}
function sanitise($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
`
I'm still relatively new to the back-end development side of things but I cannot figure this one out, I've tried to google it and research other solutions on stack overflow but couldn't find anything useful
document.addEventListener('DOMContentLoaded', function () {
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
}, false)
function handleFormSubmit(event) {
event.preventDefault();
checkEmails();
checkPasses();
processForm();
// redirectToPage()
}
function checkEmails(){
var emailValue = document.getElementById("emailadd").value;
var retypeEmailValue = document.getElementById("confirmemailadd").value;
if (emailValue !== retypeEmailValue){
window.alert("Emails do not match.");
}
}
function checkPasses(){
var passValue = document.getElementById("password").value;
var retypeValue = document.getElementById("retypepassword").value;
if (passValue !== retypeValue){
window.alert("Passwords do not match.");
}
}
function processForm(){
var userDetails = gatherData()
console.log(userDetails);
postRequest(userDetails)
}
function gatherData(){
//gather the data from the form fields into JSON
var userDetails = {
firstname : document.getElementById("firstname").value,
surname : document.getElementById("surname").value,
username : document.getElementById("username").value,
confirmemailadd: document.getElementById("confirmemailadd").value,
phonenum: document.getElementById("phonenum").value,
retypepassword: document.getElementById("retypepassword").value,
}
return userDetails;
}
async function postRequest(userDetails){
// make an AJAX POST request to server
try{
const response = await fetch("../php/register.php",{
method: 'POST',
headers: {
'Origin' : 'http://localhost/',
'Content-Type': 'application/json', // sent request
'Accept': 'application/json' // expected data sent back
},
body: JSON.stringify(userDetails),
});
const data = await response.json();
console.log(data);
handleResponseCode(data);
}catch (error){
console.log('Error:',error);
}
}
function handleResponseCode(data){
console.log("response code: ", data.code);
console.log("response message: ", data.message);
if (data.code == 1){
alert ("Your account has been successfully created")
}
else if (data.code == 2 ){
alert (data.message );
}
}
You can try to catch the root cause of this error:
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
This will catch any exceptions thrown during the encoding process and allow you to handle them appropriately.
Edit:
function main(){
// ...
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
$conn = null;
return $jsonResponse;
}
you can put this catch error inside a function you wanna trace
Just remove the var_dump(...). Because that var_dump is already sending content back.

AJAX not outputting correct thing

So I'm trying to call a php method from javascript so I can query a database and get the results into my js functionality. Currently, the 'console.log(output)' that is in my ajax is just outputting:
"array (size=1)
'action' => string 'getResults' (length=10)'"
Not really sure why it's doing this, it should be returning the query result which is just one entry from the database. Anyone have any idea? Any help is welcome! Thanks.
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);
//alert(output);
}
//error, function(err){console.log(err)}
});
}
callPHP();
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
$param=$_REQUEST['action'];
echo var_dump($_GET);
/*
$handle = fopen("php://input", "rb");
$param = '';
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";
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->MySQLDaoMethodName(parameters);
//Return the result of the query
//echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
Conn.php - this is all the connection info, * out for confidential reasons:*
<?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 querys:
<?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);
}
}
?>
I think you misunderstand how to ship data between javscript and php.
Your javascript should be posting with $.post() if you want to send an object or array of data.
Your php will recieve json from the javascript. You need to use php's json_decode function on it to make it useful to php.
If you want the output of your php script to be useful to javascript, you need to encode it with php's json_encode function before returning it to the calling script.
http://php.net/manual/en/function.json-decode.php
The output is for echo var_dump($_GET); I'm sure. I can tell because of the output format is a var_dump type. and the success part of your code does not have any output. I mean in this part else { //Decodes data, dont change ... the output has been commented out.
I noticed that you are using MySqli but some methods are MySql api like this part of the code
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
I assume this code is not complete and in debugging phase as I can see many incomplete methods and function calls.
Also try to use prepared statements with place holders for security.
It is a good practice to use ob_clean() before API output as any extra character will destroy the output data and format. However, you will not see errors. There are useful tools for API testing like Browsers Rest Client extensions. The best way for debugging is always debugging tools and frameworks like x-debug.
Do following changes to your code. Hope this helps!
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
$param=$_REQUEST['action'];
// echo var_dump($_GET);
/*
$handle = fopen("php://input", "rb");
$param = '';
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 ."...";
ob_clean();
echo json_encode($returnValue);
exit();
}
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";
//Clean up before output
ob_clean();
echo json_encode($returnValue);
exit();
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
//Close connection as fast as possible
$dao->closeConnection();
//Return the result of the query
ob_clean();
echo json_encode($result);
exit();
}
}
?>
MySQLDao.php
<?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 = ?";
$stsm = $this->mysqli->prepare($sql);
$stsm->bind_param('i',1);
$result = $stmt->execute();
if (mysqli_num_rows($result) == 1) {
$obj = mysqli_fetch_object($result, 'obResults');
return $obj;
}
return false;
}
}
?>

Call data back from AJAX

I have a script which saves canvas PNGs to a directory and I need the URL to save on the server.
When I submit, the image saves but the server remains empty. I am trying to return error messages but I am receiving nothing.
JAVASCRIPT:
function doodleSave() {
var drawing = document.getElementById("doodle-canvas");
var drawingString = drawing.toDataURL("image/png");
var postData = "canvasData="+drawingString;
var ajax = new XMLHttpRequest();
ajax.open("POST", 'http://www.website.com/php/doodleSave.php', true);
ajax.onreadystatechange= function() {
if (ajax.readyState === 4) //If it ran smoothly
{$("#doodle-submit-button").html("...");}
};
ajax.send(postData);
ajax.success(function(data) {
{$("#doodle-submit-button").html(""+data+"");}
});
}
PHP:
<?php
session_start();
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
$rawImage = $GLOBALS['HTTP_RAW_POST_DATA'];
$removeHeaders = substr($rawImage, strpos($rawImage, ",")+1);
$url = md5(uniqid(rand(), true));
$decode = base64_decode($removeHeaders);
$fopen = fopen('../images/external/doodles/'.$url.'.png', 'wb');
fwrite($fopen, $decode);
fclose($fopen);
//ADD POST TO DATABASE WITH USER'S ID
/* AUTOMATED VARIABLES */
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = 'images/external/doodles/'.$url;
try
{
$stmt = $pdo->prepare("INSERT INTO `(table name)` (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUES(:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$profile_unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "uploaded";
}
else
{
echo "Could not upload";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>

ALERT ,when searched word not found in mysql database

my coding is all about
1)fetch the data from mysql thro php
2)get data from php to d3 based on input by using PHP URL
I want to set alert when the text in the input field is not found in mysql database..
now when I try with the word other than mysql data, it shows
this console
how can i alert when wrong word(other than mysql database value) is submitted
HTML FORM
<form name="editorForm">
<input type="text"name="editor" id="editor"
onchange="document.getElementById('editorForm').submit();">
<input type="submit"value="butn">
</form>
JQUERY TO FETCH THE DATA FROM PHP BASED ON URL
$(function () {
$('form').submit(function (e) {
e.preventDefault();
var t=$('form').serialize();
var u='http://localhost:8888/saff/indexi.php?'+t;
if(u==null){
alert("not found");
}
else{
funn();
}
D3 CODES
function funn(){
d3.json(u, function(treeData) {
//D3 CODES
});
}
my php code
<?php
$con=mysqli_connect("localhost","root","admin","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
$r = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
function buildtree($src_arr, $parent_id = 0, $tree = array())
{
foreach($src_arr as $idx => $row)
{
if($row['parent'] == $parent_id)
{
foreach($row as $k => $v)
$tree[$row['id']][$k] = $v;
unset($src_arr[$idx]);
$tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
}
}
ksort($tree);
return $tree;
}
function insertIntoNestedArray(&$array, $searchItem){
if($searchItem['parent'] == 0){
array_push($array, $searchItem);
return;
}
if(empty($array)){ return; }
array_walk($array, function(&$item, $key, $searchItem){
if($item['id'] == $searchItem['parent']){
array_push($item['children'], $searchItem);
return;
}
insertIntoNestedArray($item['children'], $searchItem);
}, $searchItem);
}
$nestedArray = array();
foreach($data as $itemData){
//$nestedArrayItem['value'] = $itemData['value'];
$nestedArrayItem['id'] = $itemData['id'];
$nestedArrayItem['name'] = $itemData['name'];
$nestedArrayItem['parent'] = $itemData['parent'];
$nestedArrayItem['tooltip'] = $itemData['tooltip'];
$nestedArrayItem['color'] = $itemData['color'];
$nestedArrayItem['level'] = $itemData['level'];
$nestedArrayItem['children'] = array();
//$data[]=$dat;
insertIntoNestedArray($nestedArray, $nestedArrayItem);
}
header('Content-Type: application/json');
$json= json_encode($nestedArray,JSON_UNESCAPED_UNICODE);
echo $json = substr($json, 1, -1);
?>
works as expected when the word used is exist in the database
and the page looks like this
getting correct json format in the mozilla console.but design is not shown in the page...but in chrome ,everything works fine..
You need to test if the page is empty in the json function of the d3
function funn(){
d3.json(u, function(treeData) {
if(!treeData.length){
alert("not found");
}else {
//D3 CODES
}
});
}
Make sure that you return a empty object from the page when not found

How to modify $_SESSION var dynamically using ajax

I'm developing a website which allow the user to do query on a public database and I would like to allow the user to see the query he has done during the current session and delete one of them he wants to.
here is the code creating $_SESSION['history']:
$_SESSION['history'][] = array(
'Database' => $_SESSION['db'],
'Choice' => $_SESSION['radio'],
'Query' => $_SESSION['query'],
'Résult' => ($asResults),
'Date' => date("d-m-Y"),
'Hour' => date("H:i:s")
);
here is the code displaying the array of the $_SESSION['history']:
<?php
function displayHistory($arQueryArray)
{
if (isset($_SESSION['history']))
{
echo '<table id="history" class="display">';
$iQueryNumber = 0;
echo '<thead><tr>';
echo '<th>n°</th>';
foreach (array_keys($_SESSION['history'][0]) as $field)
{
if ($field != 'Résult' and $field != 'Choice')
{
echo '<th>', $field, '</th>';
}
}
echo '<th></th><th></th>';
echo '</tr></thead>';
echo '<tbody>';
foreach ($_SESSION['history'] as $query)
{
echo '<tr>';
echo '<td>', ($iQueryNumber + 1), '</td>';
foreach ($query as $field => $value)
{
if ($field != 'Résult' and $field != 'Choice' and $field != 'Requête')
{
echo '<td>', $value, '</td>';
}
else if ($field == 'Query')
{
echo '<td>' . $arQueryArray[$query['Choice']] . " " . $query['Query'] . '</td>';
}
}
?>
<td>
<input type="button" class="del_btn" value="X" title="Delete this query" onclick="delQueryInHistory(<?php echo $iQueryNumber; ?>, this);"/>
</td>
<?php
echo '</tr>';
$iQueryNumber += 1;
}
echo '</tbody></table>';
}
else
{
echo "<p>No query</p>";
}
}
?>
Here is the javascript:
var XHR = null;
function getXMLHTTP()
{
var xhr = null;
if(window.XMLHttpRequest)
{ // Firefox
xhr = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{ // Internet Explorer
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{
xhr = null;
}
}
}
else
{ // XMLHttpRequest not supported
alert("YOur browser doesn't support XMLHTTPRequest...");
}
return xhr;
}
//Query suppression function
function delQueryInHistory(queryId, self)
{
XHR = getXMLHTTP();
XHR.open("GET", "controleur/delQueryInHistory.php?queryId=" + queryId, true);
XHR.onreadystatechange = function()
{
if (XHR.readyState == 4)
{
self.parentNode.parentNode.parentNode.removeChild(self.parentNode.parentNode);
}
}
XHR.send();
}
Here is the php called
<?php
session_start();
if(empty($_GET['queryId']) or !is_numeric($_GET['queryId']) or !isset($_GET['queryId']))
{
exit;
}
else
{
unset($_SESSION['history'][intval($_GET['queryId'])]);
}
?>
The problem is that it simply doesn't run and i don't understand why since i have not any error raised! Even if i use a corrupted php file... I have already verified that the path to the php file is OK!
Sorry for my English, and thanks..
** Last UPDATE:** Sorry, I've forgotten to say what specially didn't run: The row is correctly removed but the $_SESSION['history'][queryId] is not removed! But the XmlHttp object has been created! Thanks.
I've found how to fix the issue, maybe it could help
<?php
session_start();
if(empty($_GET['queryId']) or !is_numeric($_GET['queryId']) or !isset($_GET['queryId']))
{
exit;
}
else
{
unset($_SESSION['history'][$_GET['queryId']]);
$_SESSION['history'] = array_values($_SESSION['history']);
}
?>
the unset() function doesn't normalize integer indexes and it broke my code during the display!

Categories

Resources