Multiple XMLHttpRequest in one page - javascript

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.

Related

AJAX request displaying content to user but not on the source of the page

On the body of the document, lets call it "form.php" we have the following:
On the head we have a JavaScript code:
<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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getchauffeur.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
We query to database and populate a dropdown. We switch content using (showUser):
<div>
<?
$result = $mysqli -> query("select id, nomchauffeur from chauffeurs");
echo "<select name='id' onchange='showUser(this.value)'>";
while ($row = $result -> fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['nomchauffeur'];
echo '<option value="'.$id.
'">'.$name.
'</option>';
}
?>
Here we are still in body. We put the content of AJAX into div.
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
</div>
Here is our script that populate form fields with the content of AJAX request:
<script>
var table = document.getElementById('table');
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
//rIndex = this.rowIndex;
document.getElementById("nomchauffeur").value = this.cells[0].innerHTML;
document.getElementById("prenomchauffeur").value = this.cells[1].innerHTML;
document.getElementById("agechauffeur").value = this.cells[2].innerHTML;
document.getElementById("cinchauffeur").value = this.cells[3].innerHTML;
};
}
</script>
Now here is our getchauffeur.php:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','nouveau');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax");
$sql="SELECT * FROM chauffeurs WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>nom</th>
<th>prenom</th>
<th>age</th>
<th>adresse</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['nomchauffeur'] . "</td>";
echo "<td>" . $row['prenomchauffeur'] . "</td>";
echo "<td>" . $row['agechauffeur'] . "</td>";
echo "<td>" . $row['adressechauffeur'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The Problem: Everything works fine if the table is on the same page. But here the AJAX request constraints us to put the table in other php page(chauffeur.php).
What we need is populating the form fields automatically by clicking on the row displayed from dropdown Change actions. It appears that the row inserted into table inside 'chauffeur.php' is not printed on the html DOM. When we click on page view source, it displays only:
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
And not the content of the following fields:
nomchauffeur prenomchauffeur agechauffeur adressechauffeur
How could we grab the content of row and fill automatically the form and where is it?
This whole javascript AJAX should be after your HTML div #txtHint.
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
Also you can return only row instead of whole table. On main page create table as id 'txtHint' and insert that row in response.

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!

PHP not Sending JSON Object to JavaScript

<?php
header("Content-Type: application/json");
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
require_once("connect_db.php");
$i = 0;
$jsonData = '{';
$sqlString = "SELECT * FROM tablename ORDER BY RAND() LIMIT $limit";
$query = mysqli_query($con, $sqlString) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$i++;
$id = $row["id"];
$title = $row["title"];
$cd = $row["creationdate"];
$cd = strftime("%B %d, %Y", strtotime($cd));
$jsonData .= '"article'.$i.'":{ "id":"'.$id.'","title":"'.$title.'", "cd":"'.$cd.'" },';
}
$now = getdate();
$timestamp = $now[0];
$jsonData .= '"arbitrary":{"itemcount":'.$i.', "returntime":"'.$timestamp.'"}';
$jsonData .= '}';
echo $jsonData;
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var myTimer;
function ajax_json_data(){
var databox = document.getElementById("databox");
var arbitrarybox = document.getElementById("arbitrarybox");
var hr = new XMLHttpRequest();
hr.open("POST", "json_mysql_data.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
arbitrarybox.innerHTML = d.arbitrary.returntime;
databox.innerHTML = "";
for(var o in d){
if(d[o].title){
databox.innerHTML += '<p>'+d[o].title+'<br>';
databox.innerHTML += ''+d[o].cd+'</p>';
}
}
}
}
hr.send("limit=4");
databox.innerHTML = "requesting...";
myTimer = setTimeout('ajax_json_data()',6000);
}
</script>
</head>
<body>
<h2>Timed JSON Data Request Random Items Script</h2>
<div id="databox"></div>
<div id="arbitrarybox"></div>
<script type="text/javascript">ajax_json_data();</script>
</body>
</html>
PHP code goes on a separate file called "json_mysql_data.php". I'm just following this tutorial from https://www.youtube.com/watch?v=-Bv8P5oQnFw and it runs fine for him but not for me. I tested "connect_db.php" with mysql alone and it works fine. It seems to me like php doesn't go pass if (isset ($_POST['limit'])) but why...On the html file I get the "requesting..." message from the javascript code which means is waiting for PHP. Thanks for your help guys.
You check for the ready state and change the content of databox with the response JSON inside the onreadystatechange function:
hr.onreadystatechange = function(aEvt) {
if(hr.readyState == 4 && hr.status == 200) {
…
databox.innerHTML += …;
…
}
…
databox.innerHTML = "requesting...";
…
}
But you change the HTML of the databox:
databox.innerHTML = "requesting...";
Still inside the block of the onreadystatechange function and after you receive the response, so the databox will always say "requesting..." no matter what you receive. You have to move the part that prints "requesting..." outside of it:
hr.onreadystatechange = function(aEvt) {
if(hr.readyState == 4 && hr.status == 200) {
…
databox.innerHTML += …;
…
}
…
}
…
databox.innerHTML = "requesting...";
…
Update:
Also, it seems that your function ins't defined correctly, as you can see, the one on the MDN reference pages example receives a parameter:
req.onreadystatechange = function(aEvt) {
…
}
But yours doesn't have such parameter:
hr.onreadystatechange = function() {
…
}
Ans that's it.
Thank you for your help #arielnmz. I found the problem. PHP was having issues with the getDate() function because the date.timezone field was not configured in the PHP.ini file. Adding the following line to the file fixed the problem:
date.timezone = "UTC"

Ajax is not working on my customize component in joomla

I'm having problem on my joomla article which i customize the code with Sourcerer.
Here is some of my example code for the ajax javascript:
<script type="text/javascript">
function showBox1(element) {
document.getElementById('hideBox1').style.display = "";
if (element == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
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", "home/matedis/public_html/joomla/Add_Edit_Intake/getuser.php?q=" + element, true);
xmlhttp.send();
}
</script>
The code for passing the value to the function is here:
<?php
// Get default database object
$db = JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
// Build the query
$query->select($db->quoteName('campusid'));
$query->from($db->quoteName('campus'));
$query->where($db->quoteName('collegeid') . '=' . $db->quote('1'));
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if ($results) {
foreach ($results as $result) {
echo "<label class='option block spacer-t10'>";
echo "<input type='radio' id ='campusID' name='campusID' value='$result->campusid' onChange='showBox1(this.value)'><span class='radio'></span>";
echo $result->campusid;
echo '</label>';
}
} else {
echo 'Error';
}
?>
Here is my getuser.php code:
<?php
$q = intval($_GET['q']);
define( 'JPATH_BASE', $_SERVER[ 'DOCUMENT_ROOT' ] ); // define JPATH_BASE on the external file
require_once( JPATH_BASE . DS . 'libraries' . DS . 'import.php' ); // framework
require_once( JPATH_BASE . DS . 'configuration.php' ); // config file
$db = JFactory::getDBO();
$sql="SELECT courseid FROM course WHERE campusid = '".$q."'";
// Build the query
$query->select($db->quoteName('courseid'));
$query->from($db->quoteName('course'));
$query->where($db->quoteName('campusid').'='. $db->quote($q)); //This later must change to retrieve id from current user
// Set the query for the DB oject to execute
$db->setQuery($query);// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($results){
foreach($results as $result)
{
echo $result->courseid;
}
}
else{ echo 'Error';}
?>
Is there any mistake i had made? Because it does not show up the output i want which i refer the code from here http://www.w3schools.com/php/php_ajax_database.asp. Sorry if any inconvenience cause because i still new to joomla and php ajax.
xmlhttp.open("GET","home/matedis/public_html/joomla/Add_Edit_Intake/getuser.php?q="+element,true);
This is real path of public_html? No..

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