Ajax not working on IE - javascript

Got this website --> http://www.secureshop.gr/POOL/acrosshotels/website/
If you check on the left sidebar there is the "find a hotel" sidebar where when you choose location from the drop down menu, the Hotel menu changes the options. This works with ajax. The problem is that it's not working with all versions of IE. When you choose a destination, the hotel drop down menu is empty/blank.
The javascript code is this. Pretty simple and works onclick of the destinations options
<script type="text/javascript">
function selecthotel(str) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("hotelselection").innerHTML=xmlhttp.responseText;
}
}
if(str == 0) {
str = 0;
}
xmlhttp.open("GET","includes/ajaxlocationsearch.php?location="+str+"&language=<?php echo $language; ?>",true);
xmlhttp.send();
}
</script>
The ajax file is this
$language = $_GET["language"];
$location = $_GET['location'];
if($location == "0") {
$result = mysql_query("Select * from eshop_articles where
category='/WEBSITE/SEARCHENGINE/HOTELS' order by
appearance",$link_id);
}else {
$result = mysql_query("Select * from eshop_articles where
category='/WEBSITE/SEARCHENGINE/HOTELS' and
short_description='$location' order by appearance",$link_id);
} ?>
<option value="0"><?php $a = $language."_choose_hotel"; echo ${$a};
?></option>
<?php while($row = mysql_fetch_assoc($result)) { ?>
<option value="<?php echo $row['appearance']; ?>"><?php echo
$row['title']; ?></option>
<?php } ?>
Thank you in advance :)

I made some testing and I found out that your code had some issues with the structure. You should always have the code properly formatted in order to find errors and problems faster. I formatted your code and found some problems with nesting and your query.
I would also like to warn you that you had a pretty serious SQL injection problem, which I fixed in this code by using prepared statements and a small extra preg_replace to strip all unwanted characters from the query and table in general. You should totally go and learn a little bit more about preventing SQL injections. There are great topics here that are dedicated to the subject and I made a list of these articles to you:
stackoverflow.com - How can I prevent SQL injection in PHP
php.net - SQL Injection
Here is the code I formatted and fixed. I have tested it by using no parameter, an empty parameter, a value that does not exist in the database, and a value that does exist in the database. Each one returned the value accordingly: three first ones return null, while the real query returns true; in this case it returns "No hotels available" if none found, or a list of these hotels if found. If the database query fails, it will by default return null, and then return "No hotels found".
I am sorry for changing the code layout a little bit, feel free to edit it back as you like, that's up to you. I highly recommend proper formatting however (might have been because of your code editor as well).
index.php
<?php
$language = "en";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hotel Selection</title>
</head>
<body>
<select id="hotelselection">
<option value="null">No hotels available</option>
</select>
<script>
function selecthotel(str) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("hotelselection").innerHTML = xmlhttp.responseText;
}
}
if (typeof(str) == "undefined" || str == null) {
str = "";
}
xmlhttp.open("GET", "run.php?location=" + str + "&language=<?php echo($language); ?>", true);
xmlhttp.send();
}
selecthotel();
</script>
</body>
</html>
run.php
<?php
$phrases = array(
"en_error_db" => "No hotels available...",
"en_choose_hotel" => "Choose a hotel..."
);
$link_id = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno($link_id)) {
die("Error occurred when attempting to connect to database (" . mysqli_connect_errno() . ": " . mysqli_connect_error() . ").");
error_log("Error occurred when attempting to connect to database (" . mysqli_connect_errno() . ": " . mysqli_connect_error() . ").");
exit(1);
}
$language_raw = isset($_GET["language"]) ? $_GET["language"] : "en";
$location_raw = isset($_GET['location']) ? $_GET["location"] : "";
$language = preg_replace("/[^\w.-]/", "", $language_raw);
$location = preg_replace("/[^\w.-]/", "", $location_raw);
if (empty($location)) {
$query = "SELECT * FROM `eshop_articles` WHERE `category` = '/WEBSITE/SEARCHENGINE/HOTELS' ORDER BY `appearance` ASC";
}else{
$query = "SELECT * FROM `eshop_articles` WHERE `category` = '/WEBSITE/SEARCHENGINE/HOTELS' AND `short_description` = ? ORDER BY `appearance` ASC";
}
if ($stmt = mysqli_prepare($link_id, $query)) {
if (!empty($location)) {
mysqli_stmt_bind_param($stmt, "s", $location);
}
mysqli_stmt_execute($stmt);
// Thanks to Bruce Martin on php.net for the SELECT * via _fetch (http://www.php.net/manual/en/mysqli-stmt.fetch.php#107034)
$metaResults = mysqli_stmt_result_metadata($stmt);
$fields = mysqli_fetch_fields($metaResults);
$statementParams = "";
foreach ($fields as $field) {
$statementParams .= (empty($statementParams) ? "\$column['" . $field->name . "']" : ", \$column['" . $field->name . "']");
}
$statment = "\$stmt->bind_result($statementParams);";
eval($statment);
print('<option value="0">' . $phrases[(isset($phrases[$language . "_choose_hotel"]) ? $language : "en") . "_choose_hotel"] . '</option>');
while (mysqli_stmt_fetch($stmt)) {
print('<option value="' . $column['appearance'] . '">' . $column['title'] . '</option>');
}
exit(1);
}else{
print('<option value="0">' . $phrases[(isset($phrases[$language . "_choose_hotel"]) ? $language : "en") . "_error_db"] . '</option>');
error_log("The script was unable to prepare a MySQLi statement (" . $query . ").");
exit(1);
}
?>
I switched over to MySQLi database extension instead of your deprecated MySQL extension. It should no longer return PHP errors over PHP error logs. I highly recommend switching to MySQL PDO if just possible. It's very simple, easy and works a lot better in my opinion!
Also, a note on your XMLHttpRequest/ActiveXObject usage: if you want to be able to support IE 5, create a class for that and load the script if the client is using that browser, otherwise use jQuery Ajax, which is very easy to use and you will not need to worry about query strings or so. The reason for having the ActiveXObject script out there, is because jQuery is not supported on IE 5, which is a common browser despite the known security issues. IE 5 is used by old computers, some banks, offices and other businesses that have not looked into the security details.
Hopefully this helped you.

Ajax-requests are cached in Internet Explorer. Try to delete the cache and then add a random parameter to the request-URL:
var url = "http://example.com/ajax.php?random="+new Date().getTime();

You shouldn't reinvent the wheel, there are some mature cross-browsers solutions out there already.
You should try using jQuery library and it's ajax method.
https://api.jquery.com/jQuery.ajax/
If you don't want to use a library you can find some solutions to your problem already, it involves creating different types of objects for IE:
http://www.quirksmode.org/js/xmlhttp.html
Internet Explorer caches content a lot, so you might need to force it to grab new data instead of taking it from the cache. You can add a GET parameter with a timestamp which is generated client side to the URL to which you're pointing.
In jQuery you can simply do it like this:
jQuery.ajax({
type: "GET",
url: "http://example.com/",
cache: false,
success: function (data) {
// do something here
}
});
Without jQuery you would need to add it manually to the url:
var url = "http://example.com" + "?_=" + (newDate()).getTime();

Related

How to execute JavaScript in PHP file executed from Ajax

I posted this earlier but it incorrectly got marked as a duplicate of Can scripts be inserted with innerHTML?, which isn't my problem. I'm not trying to run any JavaScript through using innerHTML, I'm trying to run JavaScript that is located in a PHP file called through Ajax/XmlHttp. I am using innerHTML in that JS, but I'm not writing more JS within that. So it's not a duplicate of that question and I'm trying it again now.
Not sure what's going on here. I'll explain the organization of my files first and then get into the code.
The application- Allows the user to select different attributes (i.e. year or name) and view pictures of matching results from a database.
Files- I have a gallery.php file that has a series of HTML form elements acting as selectors to get filtered results from a database. Whenever a selector is set or changed, the file sends a new request to a get.php file that uses Ajax to refresh the results without loading a new page. All that works great. My next task is to implement a modal section where I can click on an image and view a bigger version which I plan to do with JavaScript and CSS, but my intermediate goal is to just change some text at the bottom of the results from get.php again using JavaScript, just as a first step. But I can't seem to get any JavaScript written in get.php to fire.
Code-
This is gallery.php:
<?php
include_once("./../php/navbar.php");
?>
<html>
<head>
<link href="/css/siteTheme.css" rel="stylesheet">
<style>
.attributes span {
margin-right: 1rem;
}
</style>
<script>
function changeParams() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
}
};
year = document.getElementById("years_select").value;
nameFirst= document.getElementById("nameFirst_select").value;
/* Ton of other getElementById statements here that I'm excluding to keep things shorter */
url = "get.php?year="+year+......;
xmlhttp.open("GET", url, true);
xmlhttp.send();
} /* End function */
</script>
</head>
<body>
<div class="content">
<h1>Gallery</h1>
<form>Details:
<!-- -------------------- Year -------------------- -->
<select onchange="changeParams()" name="years" id="years_select">
<option value="All">Year</option>
<?php
include("/var/www/admin.php");
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$sql = "select year from db group by year order by year desc";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value=" . $row['year'] . ">" . $row['year'] . "</option>";
}
mysqli_close($conn);
?>
</select>
<!-- A bunch of other selectors are created here following the same pattern as above of getting results from a DB -->
<!-- -------------------- Searchbar -------------------- -->
<input type="text" size="50" onkeyup="changeParams()" name="search" id="search" placeholder="Search"></input>
</form>
<div id="test">Choose some filters to see some results!</div>
</form>
</div> <!-- Ends content div -->
</body>
</html>
This is get.php:
<html>
<head>
<style>
/* Bunch of CSS that's not relevant here */
</style>
<script type="text/javascript">
console.log(".....");
var parts = document.querySelectorAll("div.imgContainer");
console.log("Found something:", parts);
parts.addEventListener("click", function(){
document.getElementById("anID").innerHTML = "Test...";
});
</script>
</head>
<body>
<?php
include("/var/www/admin.php");
$year = $_GET['year'];
//Bunch of other variables set here following the same logic, getting data from gallery.php
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
echo '$conn';
}
$sql = 'select * db';
/* ---------- Creating SQL statement ---------- */
$clauses = 0;
if ($year != "All") {
if ($clauses == 0) {
$sql = $sql . ' where year = "' . $year . '" and';
$clauses = $clauses + 1;
} else {
$sql = $sql . ' year = "' . $year . '" and';
}
} /* Bunch of other if statements to get set information and add to sql statement as such */
// Need to chop of the last ' and' from the sql statement
$sql = substr($sql, 0, -4);
$sql = $sql . ' order by year desc';
$result = mysqli_query($conn, $sql);
$num_results = mysqli_num_rows($result);
if ($num_results == 0 or $clauses == 0) {
echo "<p>No matches to your query. Try refining your search terms to get some results.</p>";
} else {
echo "<p>" . $num_results . " results matched your query.</p>";
echo "<div class=results>";
//echo "<div>";
echo '<script type="text/javascript">
function modalFunction() {
document.getElementById("anID").innerHTML = "test";
}
</script>';
while ($row = mysqli_fetch_array($result)) {
$pic = $row['pathToPic'];
$wwwImg = substr($pic, 13);
//echo "<span id=aCard><img src=" . $wwwImg . " height ='250px'>";
//echo "<span class=text>" . $row['fullCardInfo'] . "</span></span>";
echo "<div class=fullContainer><div class='imgContainer'><img class=image src=" . $wwwImg ."></div><p class=text>" . $row['fullInfo'] . "</p></div>";
} // End while of results
echo "</div>";// End results div//</div>";
//echo '<div class="modal"><p id="anID"></p></div>';
} // End else of "if results"
mysqli_close($conn);
?>
<script>
</script>
<div>
<p id="anID">This in a div</p>
</div>
<!--<span>
<p id="anID">This in a span</p>
</span>-->
</body>
</html>
Sorry if that was messy, I chopped out a bunch of stuff that just gets/selects/filters some data. All that works and all variables that are left in there are set in my full code.
But the issue I'm having is writing JavaScript in get.php to change the text in the <p id="anID"> tags. I've tried JS in a few different areas of get.php, from in the <head> tags, to echoing it in <script> tags in the PHP, to pure <script> tags after the PHP statements are done (I think I left them in a few different places).
Problem is that nothing I do works to change the text in the <p> tags I references. Additionally, the console.log statements in the header of get.php don't seem to get called either. They don't fire no matter where I place them in get.php. Console.log works fine in gallery.php so it's not some issue with my browser or anything.
Long term, I will be adding JS query selectors to bring up a bigger image when an image is clicked on, but for now I'm just trying to make ANY JavaScript work in get.php and I'm struggling to do so. I don't see how this is a duplicate of the suggested repeat as I'm not trying to run JavaScript through innerHTML here.
Scratch that, it actually is trying to pass JavaScript through innerHTML as the information from get.php comes from this section of gallery.php:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
console.log("Response: ", this.responseText);
}
So it appears this is a duplicate of the question I linked after all. Apologies. However, there are not great answers to that question, so any tips would be appreciated.
This line:
document.getElementById("test").innerHTML = this.responseText;
Is simply going to add the contents of this.responseText to the element test. I'm sure you understand that much, but what you want to do is completely wrong. The scripts within the output of get.php will NOT be executed at all and you have corrupted your HTML as well by including a second <html><head> and more.
A better approach would be if get.php returned the data from you DB query as a JSON string like so:
$data;
while ($row = mysqli_fetch_array($result)) {
$data[]['pic'] = $row['pathToPic'];
$data[]['wwwImg'] = substr($row['pathToPic'], 13);
}
echo json_encode($data);
exit;
And then back on gallery.php you do something like:
if (this.readyState == 4 && this.status == 200) {
formatResult(this.responseText);
}
// ... snip ...
function confirmJson(str) {
var j = null;
if (str) {
try { j = JSON.parse(str); }
catch (e) { j = null; }
}
return j;
}
function formatResult(str) {
var data = confirmJson(str);
if (! data) {
console.log("result is not JSON");
return;
}
// do stuff with the data
var i, max = data.length;
var h = document.createElement("div");
var img;
for(i=0;i<max;i++) {
img = document.createElement("src");
img.src = data[i].wwwImg;
img.addEventListener("click",function(){ alert("pic:["+ data[i].pic +"]"); },true);
h.appendChild(img);
}
document.getElementById("test").innerHTML = h;
}

Is it possible to access the Prestashop's Web service by client (customer) login instead the key?

I'm studying Prestashop's development. And I trying to create a "third part" side application with react.js (React Native for more precision) and catch Json data in the prestashop's webservice. But I want to let the "customer" make login with his own account and only his account. With CRUD also.
in advance; Very thank you for your patience and attention.
Best Regards.
Michel Diz
Prestashop backoffice login give no access to webservices. Webservices must be enabled and a key generated. So, I recommend you that change your "login" way. Customers accounts are not related with webservices and webservices are only used to access stored data un Prestashop (more like Backoffice than Frontoffice).
What exactly do you need to do?
I hope it helps you.
I don't know if you're still searching for a solution but there is a way actually.
DO MAKE SURE IT IS A SECURE LOGIN.
Since you're giving access to all prestashop data do make sure the login is very secure. I've been able to recreate it with PHP I think that with some additions you're able to recreate it the way you want it. See it as a guideline.
To create a login system by using the prestashop webservice you'll need three things
Access through webservice to the customers table
The COOKIE_KEY, defined in app/config -> parameters.php:: 'cookie_key' => '12321test';
Some expierence with PHP
The first thing is to get the customers table from the webservice.
// code placeholder
require_once('./../PSWebServiceLibrary.php');
/**
* get information from PrestaShop
*/
$webService = new PrestaShopWebservice($url, $key, $debug);
$COOKIE_KEY = 'CookieKey';
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
$optUser = array(
'resource' => 'customers',
'filter[email]' => '[' . $email . ']',
'display' => '[id,email,lastname,firstname,passwd]'
);
$resultUser = ($webService->get($optUser));
$json = json_encode($resultUser);
The second and most important thing is to Check the user input
// code placeholder
foreach ($resultUser->customers->customer as $info) {
// Prestashop uses the cookie_key in combination with a salt key. To check the password use the php function: password_verify();
$salt = substr($info->passwd, strrpos($info->passwd, ':') + 1, 2);
$ZCpassword = md5($COOKIE_KEY . $password) . ':' . $salt;
// Check if password comparison is true or false
if (password_verify($password, $info->passwd) == true) {
session_start();
$response = array();
$response['status'] = 'succes';
$response['message'] = "You did it!";
setcookie("userId", $info->id);
header('Content-type: application/json');
echo json_encode($response);
} else {
$response = array();
$response['status'] = 'error';
$response['message'] = 'Wrong password';
header('Content-type: application/json');
echo json_encode($response);
}
}
This is how to reproduce the issue to a working example.
Hope this helps!
For those who are still searching for this answer,
<?
if (isset($_GET["email"]) && isset($_GET["password"]) )
{
$email = $_GET["email"];
$password = $_GET["password"];
$COOKIE_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$jsonurl = "https://XXXXXXXXXXXXXXXXXXXX#example.com/api/customers?filter[email]=".$email."&display=[passwd]&output_format=JSON";
$json = file_get_contents($jsonurl);
$json_a = json_decode($json, true);
$loopone = $json_a['customers'];
$looptwo = $loopone[0];
$loopthree = $looptwo['passwd'];
$ZCpassword = md5($COOKIE_KEY . $password);
if (strcmp($loopthree, $ZCpassword) == 0) {
echo "sucess";
} else {
echo "fail";
}
}
else
{
echo "Send something with url dude";
}
?>

ajax sql and PHP query database and return result

I am currently trying to query a database using Ajax. My Ajax Is as follows
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Not working");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.returnhere.value = ajaxRequest.responseText;
}
}
var datepicker = document.getElementById('datepicker').value;
var datepicker1 = document.getElementById('datepicker1').value;
var queryString = "?datepicker=" + datepicker + "&datepicker1=" + datepicker1;
ajaxRequest.open("GET", "detengde.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
From: <input id='datepicker' /> <br />
To: <input id='datepicker1' />
<br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
<div id=returnhere></div>
My PHP looks like this:
include 'config.php'
$startd = ($_GET['datepicker']);
$endd = ($_GET['datepicker1']);
$sql = "SELECT * FROM delays WHERE Delaytype >= date('".$startd."') AND Delaydate < ADDATE(date('".$endd."'), INTERVAL 1 DAY)";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
do something . .. .. . .
This query works with PHP on its one and will return records that lie between two date ranges.
Im struggling to get the php output back to my page. To be honest when I click the button very little happens. I am confortable with PHP database interactions AJAX is something I just starting to learn.
Please no messages about the security I am aware this is very unsafe.
There is something very fundamental I am missing here. After many tutorials, searching through stacked overflow its just not clicking (no pun intended)
Add a field with a name "returnhere" to the HTML page.
<input type="text" name="returnhere">
If I'm reading your code right, the callback for the ajax function should fill in its value.
<?php
include 'config.php';
header('Content-Type: application/json; charset="utf-8"');
$startd = ($_GET['datepicker']);
$endd = ($_GET['datepicker1']);
$sql = "SELECT * FROM delays WHERE Delaytype >= date('".$startd."') AND Delaydate < ADDATE(date('".$endd."'), INTERVAL 1 DAY)";
$result = mysqli_query($con,$sql);
//just an empty array here
$final_array=array();
while($row = mysqli_fetch_array($result)) {
// I am not aware of what is being returned. So I am going to assume its a 'value'
// you can just store the values returned, in an array and echo the array or
// json_encode($array) and echo that
// this will just echo the value for time the loop encounters this statement
echo $row['value'];
//push the element into the array.Beware of overhead caused by array_push()
//if it is a `key-value` pair, its better just to use $final_array[$key] = $value;
array_push($final_array,$row['value']);
}
// Don't forget to set the header before echoing the json
echo json_encode($final_array);
?>
I hope this helps to some extent. Or if you need particulars feel free to comment below
In your JS
use
document.getElementById("returnhere").value=object.responseText;
or
document.getElementById("returnhere").innerHTML=object.responseText;
which ever suits your need

Populate a dropdownlist after selecting a value from a different list using Ajax

I have 2 dropdownlists. The first contains Car Brands like seat,bmw,audi etc.
The second i want to contain the models from the specific Brand the user selected in list 1.
In my current code state, when i select A brand from List 1 the second list is getting Filled with the same elements from List 1. So I Have a Duplicated List with exactly the same records.
The main file:
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
$css='css.css';
$doc = JFactory::getDocument();
$doc->addStyleSheet('modules/mod_alpha_table/assets/'.$css);
$db= JFactory::getDbo();
$ready = $db->getQuery(true);
$query="SELECT category_name,virtuemart_category_id from uhhu_virtuemart_categories_el_gr INNER JOIN uhhu_virtuemart_category_categories ON uhhu_virtuemart_categories_el_gr.virtuemart_category_id = uhhu_virtuemart_category_categories.category_child_id WHERE uhhu_virtuemart_category_categories.category_parent_id = 105";
$db->setQuery($query);
$options=$db->loadObjectList();
$model="";
?>
<script>
function showUser(str) {
var xmlhttp;
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","query.php?q="+str,true);
xmlhttp.send();
}
</script>
<div class="srchcr">
<div class="srch">
<form name="searchcar">
<form>
<select onchange="showUser(this.value)" name="cats">
<option value="none">Select Make</option>
<?php foreach ($options as $row) {
echo '<option value=' . $row->virtuemart_category_id . '>'. $row->category_name . '</option>';
}
?>
</select>
<select name="subcats" id="txtHint">
<option value="none">Select Model</option>
</select>
</form>
</div>
</div>
query.php file :
<?php
$doc = JFactory::getDocument();
$db= JFactory::getDbo();
$ready = $db->getQuery(true);
$q = htmlspecialchars($_REQUEST['q']);
$query='SELECT category_name,virtuemart_category_id from #__virtuemart_categories_el_gr INNER JOIN #__virtuemart_category_categories ON #__virtuemart_categories_el_gr.virtuemart_category_id = #__virtuemart_category_categories.category_child_id WHERE #__virtuemart_category_categories.category_parent_id = $q';
$db->setQuery($query);
$options=$db->loadObjectList();
foreach ($options as $row) {
echo '<option name='. $q .' value=' . $row->virtuemart_category_id . '>'. $row->category_name . '</option>';
}
?>
Query tested at phpmyAdmin and working fine. It seems somehow the first query is getting executed twice instead of the query inside the $query.php file. I also tried include the code from the external file inside the main but its the same story.I also renamed the second $query as $query2 and executed $query2 but nothing changed.Could someone enlight me on what is going wrong ?
EDIT:
After a break and bit more debugging i think that this is where the problem start:
xmlhttp.open("GET","query.php?q="+str,true);
It seems like the request for some reason, instead of query.php is sent at index.php and triggers the same query again.I added die(); at the start of query.php and nothing happened.So may i need to use a joomla syntax or something ?
Looks like you have a copy-paste-error here. When comparing the creation of your option-tags, I see the exact same code for both the brands and the models, meaning query and dom-creation.
So basically, your code is perfectly fine. But in your query.php you are creating this same brand-list again ;)
Some general comments on your code:
Do not create your own implementation of the XmlHttpRequest, use a library like jquery or mootools
You are vulnerable to sql-injections when using values from userland ($_REQUEST['q']) without sanitizing them. See this question on stackoverflow: Best way to prevent SQL injections in Joomla
if it is true that you gather the information for your 2 lists with the same query, try to implement your logic (user selects brand, model-list is updated) through javascript. So your main.php still creates the brand-list, but renders all model-lists as well. These are shown/hidden when the user changes the brand accordingly. This would avoid the additional roundtrip to the server each time a brand is selected.

Can not write to MySQL-DB with PHP triggered by JQuery

Hello there overflowers!
I´m new to asking on here,
but i´ve been reading a lot on here, which has helped me already.
This time though i am encountering a problem,
to which i can not seem to find a thread nor a solution.
So the following situation occured:
I have a frontend in which people can change the design to use by clicking on a button.
That does work quite well. But it should save the themename to database.
It says it does, but it does not - if that saving is triggered on the site with JS/JQuery.
It does though, if i trigger it manually with the PHP-file:
./lib/savetheme.php?user=username&theme=themename
If i trigger it via JS it goes through the php, which really echoes the needed TRUE.
But it does not save to database. It does not throw any errors (it would die - but it echoes true..).
So here comes the code...
common.php
<?php
function m($str) {
$str = mysql_escape_string($str);
return "'".$str."'";
}
?>
db-connect-data.php
<?php
$dbname = "dbname";
$dbuser = "dbuser";
$dbpw = "dbpw";
$dbhost = "localhost";
$dbport = "3306";
?>
db-connect.php
<?php
if (!mysql_connect($dbhost.":".$dbport, $dbuser, $dbpw)) {
die();
}
if (!mysql_select_db($dbname)) {
die();
}
?>
savetheme.php
require "./common.php";
require "./db-connect-data.php";
require "./db-connect.php";
if(isset($_GET)) {
$user = "";
$theme = "";
if($_GET['user'] != "") {
$user = $_GET['user'];
}
if($_GET['theme'] != "") {
$theme = $_GET['theme'];
}
$sql = "UPDATE users SET
theme = ".m($theme)."
WHERE username = ".m($user);
if(mysql_query($sql)) {
echo "TRUE";
} else {
echo mysql_error();
}
}
?>
profile.php
<?php
foreach (glob("./themes/*",GLOB_ONLYDIR) as $file) {
$output = str_replace("./themes/", "", $file);
echo '<button class="buttons themebuttons" id="'
.$output.'">'.$output.'</button>';
}
?>
<div class="ui-widget" id="savethemeok">
<br>
<div class="ui-state-green ui-corner-all">
<p>
Theme saved successfully!
</p>
</div>
</div>
<div class="ui-widget" id="savethemeerror">
<br>
<div class="ui-state-red ui-corner-all">
<p>
Error! Theme could not be saved!
</p>
</div>
</div>
main.js
$(document).ready(function() {
$(".buttons").button();
$(".themebuttons").click(function() {
var themename = $(this).attr("id");
var themepath = "./themes/" + themename + "/jquery-ui.css";
console.log("Saving new theme...");
$.get( "./lib/savetheme.php" , {
user: $("#loggeduser").attr("value"),
theme: "'" + themename + "'",
}, function(status) {
if(status == "TRUE") {
console.log("New theme: " + themename);
$("#theme").attr({href: themepath});
$("#savethemeok").show();
window.setTimeout(function() {
$("#savethemeok").fadeOut();
}, 2500);
} else {
console.log("Error: " + status);
$("#savethemeerror").show();
window.setTimeout(function() {
$("#savethemeerror").fadeOut();
}, 2500);
}
});
});
});
There is more code, i hope i got all the relevant code out,
but i do not think it will be any more overseeable
if i copy the almost 1000 lines of code not regarding this particular issue.
If needed i will do though.
I am happy and thankful with any suggestions, as i have already buried some time into that issue and seemingly i do not have any clue as to why it does not save to db when i trigger it via JS but works just fine when manually triggering it with the php...
I am sorry if there is a thread about this somewhere which i have missed out on.
If there is, please let me know. I did not find any though.
Then again, maybe I´m too stupid to look for it,
i did struggle a bit with putting my problem in words...
Thank you all in advance!
the problem is fixed.
i had changed the user variable to another user - so naturally it did not save to the user i was looking at.
im sorry to have alerted you.
thanks for viewing into it - and in the honor of Robin Williams: CARPE DIEM.
From what you've posted in the question, your columns theme and username appear to be of varchar type. Try and modify your query to the following:
$sql = "UPDATE users SET theme = '".m($theme)."' WHERE username = '".m($user)."'";

Categories

Resources