How to modify $_SESSION var dynamically using ajax - javascript

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!

Related

Multiple XMLHttpRequest in one page

I have a situation where I am making the following requests and for some reason only one of them is working?
The expected result is that the second div which is populated by filter2 will bring in the necessary information, however this is not working even though this is following the same logic as filter 1?
The code for the actual requests is here:
Request 1:
function show1(str) {
if (str == "") {
document.getElementById("id1").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("id1").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "filter1.php?q=" + str, true);
xmlhttp.send();
}
Request 2:
function show2(str) {
if (str == "") {
document.getElementById("id2").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("id2").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "filter2.php?p=" + str, true);
xmlhttp.send();
}
The php code is as follows for both of the requests is as follows:
Filter1:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include('db.php');
$q = strval($_GET['q']);
mysqli_select_db($mysqli,"database");
$search="SELECT * FROM column WHERE type = '".$q."'";
$result = mysqli_query($mysqli,$search);
echo "<ul id=\"list\">";
while($row = mysqli_fetch_array($result)) {
echo "<li>";
echo "<a class=\"class\">" . $row['column'] . "</a>";
echo "<a class=\"class\"><strong>" . $row['column'] . "</strong></a>";
echo "<button><img src=\"icons/image.png\" style=\"height:42px;width:42px;\" onclick=\"show2(this.value)\" value=\"" . $row['column'] . "\" class=\"class\"></button>";
echo "</li>";
}
echo "</ul>";
mysqli_close($mysqli);
?>
</body>
</html>
Filter2:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include('db.php');
$p = strval($_GET['p']);
mysqli_select_db($mysqli,"database");
$search="SELECT * FROM column WHERE name = '".$p."'";
$result = mysqli_query($mysqli,$search);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "<tr id=\"id\"><td><strong>" . $row['column'] . "</strong></td></tr>";
echo "<tr id=\"id\"><td>TestContact</td></tr>";
echo "<tr id=\"id\"><td>" . $row['column'] . "</td></tr>";
echo "<tr id=\"id\"><td>Website ></td></tr>";
}
echo "</ul>";
mysqli_close($mysqli);
?>
</body>
</html>
I am not sure if this is a common mistake or I have some kind of clash/stupid syntax error, but this is driving me crazy and I would be forever grateful for anyone to help?
Like I said in a comment ( and was also stated in the 1st comment by #jcubic ) an img element doesn't have a value attribute which is, I suspect, the reason your function is passing undefined
Instead you can use a dataset attribute and alter the parameter passed to the inline function / event handler:
echo "<button><img src=\"icons/image.png\" style=\"height:42px;width:42px;\" onclick=\"show2(event)\" data-value=\"" . $row['column'] . "\" class=\"class\"></button>";
and the javascript function
/* passing event allows access to event.target amongst other things - this is useful */
function show2( e ){
var el=e.target;
var str=el.dataset.value;
if( str )/* etc */
}
that said you'd be much better creating a generic ajax function ( or better yet look into the fetch api ) and write wrapper functions for each use case.

Trying to understand jquery serialization

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.

Delete data with checkbox in a table

I display a table on the website after a select option (I use ajax) and get the datas from the database. What I want to do is to insert a checkbox in my table and when it is checked delete the row in the database. I don't want to use a submit button but only the checkbox to delete it.
I'm not really good with ajax and JavaScript. This is the code:
The select :
<p>
<label for="client">Veuillez choisir le fournisseur :</label><br />
<select name="client" id="client" onchange="showUser(this.value)">
<?php
// echo '<option value=""/></option>';
while ($donnees = $reponse->fetch())
{
echo '<option value='.$donnees['refCustomer'].'>'.$donnees['legalCompanyName'].' </option>';
//$value = $donnees['refCustomer'];
}
$reponse->closeCursor();
?>
</select>
</p>
The script :
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getTableBuffer.php?q="+str,true);
xmlhttp.send();
}
}
</script>
getTableBuffer.php :
<?php
$q = intval($_GET['q']);
try
{
$bdd = new PDO());
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$reponse = $bdd->query('select * from vendor_'.$q.'_offers_ncli_amendments_buffer');
echo '<table class="imagetable">';
echo '<tr>';
echo '<th>code</th>';
echo '<th>dateAdded</th>';
echo '<th>effectiveDate</th>';
echo '<th>price</th>';
echo '<th>type</th>';
echo '<th>destination</th>';
echo '</tr>';
while ($donnees = $reponse->fetch())
{
echo '<tr>';
echo '<td><input type="checkbox" name="code" id="code" value="'.$donnees['code'].'"/>'.$donnees['code'].'</td>';
echo '<td>'.$donnees['dateAdded'].'</td>';
echo '<td>'.$donnees['effectiveDate'].'</td>';
echo '<td>'.$donnees['price'].'</td>';
echo '<td>'.$donnees['type'].'</td>';
echo '<td>'.$donnees['destination'].'</td>';
echo "</tr>";
}
echo "</table>";
echo "</br>";
echo "</br>";
$reponse->closeCursor();
?>
Add event onclick to your checkbox :
echo '<td><input onclick="remove(this);" type="checkbox" name="code" id="code" ....';
create function remove() in you javascript, that send the $donnees['code'] to a remove.php to delete it from DB :
function remove(e)
{
if (e.target.checked)
{
....
xmlhttp.open("GET","remove.php?code="+e.target.value,true);
xmlhttp.send();
}
}
Create remove.php that get the code and delete from DB :
<?php
if(isset($_GET['code'])){
//Query to remove from DB where code = $_GET['code']
}
?>
Hope this will help.

Dynamic drop down with PHP MySQL and Java

Complete Dynamic drop down in PHP MySQL & AJAX with mysql Insert query works perfectly.
Code to insert date to MySQL table
<?php
require('../conn/include.php');
require('quick.php');
$query="SELECT * FROM category";
$result=mysql_query($query);
$project=$_POST['project'];
$alttext=$_POST['alttext'];
$relation=$_POST['state'];;
if(isset($_FILES['image'])) {
$errors=array();
$allowed_ext=array('jpg','png','jpeg','JPG');
$filename=$_FILES['image']['name'];
$name=stripslashes($filename);
$type=strtolower(end(explode('.',$filename)));
$size=$_FILES['image']['size'];
$file_tmp=$_FILES['image']['tmp_name'];
if(in_array($type,$allowed_ext) ===false) {
$errors[]= "<span class=\"notification n-error\">Extenstion Not Allowed</span>";
}
if($size > 1048576) {
$errors[]= "<span class=\"notification n-error\">File must be less then 2mb</span>";
}if(file_exists('../../images/a/gallery/'.$filename)) {
$errors[]= "<span class=\"notification n-error\">File $filname Already Exists in directory</span>";
}if(empty($errors)) {
if(move_uploaded_file($file_tmp, '../../images/a/gallery/'.$filename)) {
$insert="Insert into `my`.gallery(name,alttext,project,relation)VALUE('$name','$alttext','$project','$relation')";
//echo $insert;
$que=mysql_query($insert);
echo "<span class=\"notification n-success\">File $filname Uploaded Sucessfully</span>";
header('Refresh:3; url:gallery.php');
}
}else {
foreach($errors as $error) {
echo $error,'<br/>';
}
}
}
?>
AJAX Code
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getState(cate_id) {
var strURL="findsect.php?country="+cate_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Code for Second Drop Down or findsec.php
<?php
$country=$_GET['country'];
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my');
$query="SELECT * FROM gallery_section WHERE related='$country'";
$result=mysql_query($query);
?>
<select name="state" onchange="getCity(<?php echo $country?>,this.value)">
<option>Select State</option>
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
Thanks to Nick Wilde who helped me.
I'm presuming you mean when the value of the option for the second drop down is multiple words. If that is the case the problem is you are missing quotes; use this instead:
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
as the last three lines of your findsec.php

Ajax POST / XML not working

I have two buttons I press. one calls function with argument of "1" the other calls with argument of "2"
function getOptions(scheme){
var url = "http://localhost/AV/data2.php";
var XMLHttpRequestObject = new XMLHttpRequest();
XMLHttpRequestObject.onreadystatechange = function(){
if (this.readyState != 4) return;
if (this.status == 200){
var xmlDocument = this.responseXML;
options = xmlDocument.getElementsByTagName("option");
listOptions();
}
}
XMLHttpRequestObject.open("POST", url, true);
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.send("scheme="+scheme);
//XMLHttpRequestObject.send(null);
}
and the data2.php file:
<?php
header("Content-type: text/xml");
if ($_POST["scheme"=="1"]) $options = array('black','pink','orange');
if ($_POST["scheme"=="2"]) $options = array('red','blue','green');
//$options = array('red','blue','green');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo '<options>';
foreach ($options as $value)
{
echo '<option>';
echo $value;
echo '</option>';
}
echo '</options>';
?>
this does not work.. it returns something about "junk after document element".. I have other parts in there i commented out and those work when i change it to GET but why doesn't this work?
It should be
if ($_POST["scheme"]=="1") // and
if ($_POST["scheme"]=="2")

Categories

Resources