Opencart ajax post query to database not working - php

I am testing opencart in XAMPP. I added this extension which checks zip code and enables to give zip code based shipping. Demo is here. It may not be compatible with the latest version.
The code was not working initially and after some modifications the admin side works. I can insert/modify zip code, etc., which means there is no issues in database.
In the catalog side however I am helpless. There is this ajax button which is not working.
<div class="pincode">
<span><strong>Enter pincode to check serviceability:</strong></span><br><br>
<input type="text" name="zip_code" value="" id="zip_code" size="8">
<a id="button_zipcode" class="button" title="Check"><span>Check</span></a><br><br>
<div id="temp_zipcode" style="width:94%;"></div>
which gets enabled with this script
$('#button_zipcode').bind('click', function() {
$.ajax({
url: 'index.php?route=product/product/zipcode',
type: 'post',
data: 'zip_code='+$('#zip_code').val(),
dataType: 'json',
success: function(json) {
$('.success, .warning, .attention, information, .error').remove();
if (json['warning']) {
$('#temp_zipcode').html('<div class="warning" style="display: none;">' + json['warning'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.warning').fadeIn('slow');
}
if (json['success']) {
$('#temp_zipcode').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
}
}
});
});
url: 'index.php?route=product/product/zipcode', what this means? if it is controller/product/product.php what should I add to make it work? The code should check zip code with DB and give output.
And there is another page as catalog/model/localisation/zip_code.php which has
<?php
class ModelLocalisationZipCode extends Model {
public function getZipCode($zip_code_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zip_code WHERE zip_code_id = '" . (int)$zip_code_id . "' AND status = '1'");
return $query->row;
}
public function getCodeByZip($zip_code) {
$query1 = $this->db->query("SELECT * FROM " . DB_PREFIX . "zip_code WHERE zip_code LIKE '" . $zip_code . "' AND status = '1'");
return $query1;
}
}
?>
Is there anyway to make it work?
Thanks in advance...

In your catalog/controller/product/product.php
add the fallowing code :
public function zipcode() {
$this->language->load('product/zipcode');
$this->load->model('localisation/zip_code');
$json = array();
if (isset($this->request->post['zip_code'])) {
$zip_code = $this->request->post['zip_code'];
} else {
$zip_code = 0;
}
$zone_data = $this->model_localisation_zip_code->getCodeByZip($zip_code);
if($zone_data->num_rows == 0)
{
$json['warning'] = sprintf($this->language->get('text_warning'));
}
else
{
$city_name = $zone_data->row['city_name'];
$state_name = $zone_data->row['state_name'];
$zone_name = $zone_data->row['zone_name'];
$json['success'] = sprintf($this->language->get('text_success'), $city_name, $state_name, $zone_name);
}
$this->response->setOutput(json_encode($json));
}

Related

unable $_GET data in PDO using AJAX for product filtering

Unable to filter product using PDOamd AJAX,
Below code loads data form sql using PDO and AJAX but when i try to filter based on Brand it doesn't work. tried debug var_dump method but nothing helps.
Can someone help me to solve, how do i filter product, is there anything missing in code?
HTML
<div class="md-radio my-1">
<input type="radio" class="filter_all cate" name="cate" id="<?php echo str_replace(' ', '', $row['sca']); ?>" value="<?php echo $row['sca'] ?>">
<label for="<?php echo str_replace(' ', '', $row['sca']); ?>">
<?php echo $row['sca']; ?>
</label>
</div>
SCRIPT
$(document).ready(function () {
var flag = 0;
var fetching = false;
var done = false;
function filter_data() {
// prevent concurrent requests
if (fetching === true) {
return;
}
fetching = true;
var data = {
action: 'fetch_data',
cate: get_filter('cate'),
brand: get_filter('brand'),
model: get_filter('model'),
sort: get_filter('sort'),
date: get_filter('date'),
offset: flag,
limit: 4
};
console.log($.param(data));
$.ajax({
url: "fetch.php?" + $.param(data),
type: 'POST'
})
.done(function (data) {
console.log('data received');
$('.filter_data').append(data); // append
// we reached the end, no more data
if (data === '<h3>No Data Found</h3>') {
done = true;
}
flag += 4;
fetching = false; // allow further requests again
})
.fail(function (error) {
console.log('An error occurred while fetching', error)
// TODO: some error handling
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name + ':checked').each(function () {
filter.push($(this).val());
});
return filter;
}
$('.filter_all').click(function () {
filter_data();
});
filter_data(); // commented out for debugging purpose
var $window = $(window);
var $document = $(document);
$window.scroll(function () {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 300 && fetching === false && done === false) {
console.log('infinite scroll');
filter_data();
}
});
});
PHP
<?php
include("$_SERVER[DOCUMENT_ROOT]/include/config.php");
include("$_SERVER[DOCUMENT_ROOT]/include/function.php");
$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle'";
if (!empty($_GET['cate'])) {
$query .= " AND sca IN (" . str_repeat("?,", count($_GET['cate']) - 1) . "?)";
} else {
$_GET['cate'] = []; // in case it is not set
}
if (!empty($_GET['brand'])) {
$query .= " AND product_brand IN (" . str_repeat("?,", count($_GET['brand']) - 1) . "?)";
} else {
$_GET['brand'] = []; // in case it is not set
}
if (!empty($_GET['model'])) {
$query .= " AND mdl IN (" . str_repeat("?,", count($_GET['model']) - 1) . "?)";
} else {
$_GET['model'] = []; // in case it is not set
}
if (empty($_GET['sort']) || $_GET['sort'][0] == "date") {
$query .= " ORDER BY pdt DESC";
} elseif ($_GET["sort"][0] == "ASC" || $_GET["sort"][0] == "DESC") {
$query .= " ORDER BY prs " . $_GET['sort'][0];
}
if (isset($_GET['limit'])) {
if (!empty($_GET['offset'])) {
$query .= " LIMIT " . $_GET['limit'] . " OFFSET " . $_GET['offset'];
} else {
$query .= " LIMIT " . $_GET['limit'];
}
}
$stmt = $conn->prepare($query);
$params = array_merge($_GET['cate'], $_GET['brand'], $_GET['model']);
$stmt->execute($params);
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
if ($total_row > 0) {
foreach ($result as $row) {
$parameter = $row['pid'];
$hashed = md5($salt . $parameter);
$output .= '<a href="/single_view.php?p=' . $row['id'] . '" class="w-xl-20 w-lg-20 col-md-3 col-6 p-1 p-lg-2">
<div class="card border-0 small">
<img class="card-img-top rounded-0" src="/upload/thumb/' . $row["im1"] . '" alt="Card image cap">
<div class="card-body pb-0 pt-2 px-0">
<h6 class="card-title text-dark text-truncate">' . ucfirst(strtolower($row['tit'])) . '</h6>
<h6 class="card-subtitle mb-1 text-muted text-truncate small">' . $row['product_brand'] . ' / ' . $row['mdl'] . '</h6>
<p class="card-text"><strong class="card-text text-dark text-truncate">₹ ' . $row['prs'] . '</strong></p>' . timeAgo($row['pdt']) . '
</div>
</div>
</a>';
}
} else {
$output = '<h3>No Data Found</h3>';
}
echo $output;
?>
You are sending data via GET query parameters despite defining the ajax call as a post. That's a security risk. Try changing your AJAX call to something like this, and replace youyr $_GET stuff to $_POST.
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: data,
mimeType: 'multipart/form-data',
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});

Send php variables to jquery function

Ok, I need to send data from PHP to jquery and use jquery function to update that data into HTML.
But the problem is jquery want update HTML elements with PHP data...
This is php code.Php is called from ajax.
$product_image = "";
$product_name = "";
$product_description = "";
$product_size = "";
if(mysqli_num_rows($r) > 0) {
while($row = mysqli_fetch_assoc($r)) {
$product_image = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["image"];
$product_name = $row["name"];
$product_description = $row["description"];
$product_size = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["img_size"];
echo '<script type="text/JavaScript">';
echo 'var product_image = ' . json_encode($product_image) . ';';
echo 'var product_name = ' . json_encode($product_name) . ';';
echo 'var product_description = ' . json_encode($product_description) . ';';
echo 'var product_size = ' . json_encode($product_size) . ';';
echo 'showProduct();';
echo '</script>';
}
}
//echo $product_num_id;
mysqli_close($dbc);
exit();
}
This is jquery function for updating html elemtns:
function showProduct()
{
alert("dbg");
$("#product_name_put").html(product_name);
$("#product_desc_put").html(product_description);
$("#product_image_put").attr("src", product_image);
$("#product_size_put").attr("src", product_size);
}
And this is html elements:
<div class="product_view_info">
<ul class="product">
<li><img id="product_image_put" src="" alt=" Product Photo"></li>
<li class="informations">
<div class="product_name"><h4 id="product_name_put"></h4></div>
<div class="desc_info"><p id="product_desc_put"></p></div>
<img id="product_size_put" src="" alt="Size Photo">
</li>
</ul>
</div>
This is a problem: https://ibb.co/HGyJkwB
UPDATE: AJAX CODE: When user click on product ajax sending id of clicked product to php.
$(document).on("click touchend", ".product_stake_stapovi, .product_invalidska_kolica, .product_antidekubitni_program, .product_ortoze, .product_mideri, .product_pojas, .product_toaletni_program, .product_bolnicki_kreveti_i_oprema", function (event) {
var product_num_id = $(this).children(".num_id").attr("id"); //Getting id from image element (that is location of real stored id in database)
var product_id = $(this).attr("class");
var product_real_id = product_id.replace("col-3 col ", "");
$.ajax({
method: "POST",
url: "index.php?proizvodi",
data: ({product_num_id:product_num_id}),
success: function() {
$(".big_categoryes").fadeOut("fast");
$(".all_products").fadeOut("fast");
$(".product_view_info").fadeIn("smooth");
}
});
});
U can get data from PHP as json like so:
if(mysqli_num_rows($r) > 0) {
while($row = mysqli_fetch_assoc($r)) {
$product = (object)[];
$product->image = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["image"];
$product->name = $row["name"];
$product->description = $row["description"];
$product->size = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["img_size"];
echo json_encode($product);
}
}
mysqli_close($dbc);
exit();
and get data from json with jquery:
$(document).on("click touchend", ".product_stake_stapovi, .product_invalidska_kolica, .product_antidekubitni_program, .product_ortoze, .product_mideri, .product_pojas, .product_toaletni_program, .product_bolnicki_kreveti_i_oprema", function (event) {
var product_num_id = $(this).children(".num_id").attr("id"); //Getting id from image element (that is location of real stored id in database)
var product_id = $(this).attr("class");
var product_real_id = product_id.replace("col-3 col ", "");
$.ajax({
method: "POST",
url: "index.php?proizvodi",
data: ({product_num_id:product_num_id}),
success: function(response) {
var product = JSON.parse(response);
console.log(product.image);// example
showProduct(product);
$(".big_categoryes").fadeOut("fast");
$(".all_products").fadeOut("fast");
$(".product_view_info").fadeIn("smooth");
}
});
});
function showProduct(product){
$("#product_name_put").html(product.name);
$("#product_desc_put").html(product.description);
$("#product_image_put").attr("src", product.image);
$("#product_size_put").attr("src", product.size);
}
I hope this could help you.

Livesearch using php and ajax not working

I have a Ajax PHP MySQL live search that basically pulls out manufacturing items from a MySQL database and presents them in a drop-down list, as users enter they search term, one item per line, just like searching in Google.
What I need is a way to allow users to click on a particular link item, and for that to display data on the same page, just below the item(link) clicked.
Any help would be appreciated.
1.HTML form
<form class="navbar-form navbar-left" action="javascript:">
<div class="input-group">
<input type="text" class="form-control" id="searchbox1" name="q" token="<?=$csrf->token()?>" action='search1' placeholder="Search for Templates" autocomplete="off">
<div class="input-group-btn">
<button class="btn btn-default " id="searchbtn1" type="submit">
<i class="fa fa-search"></i></button>
</div>
</div>
<div id="livesearch1"></div>
</form>
2. AJAX Call seperate .js file
$('#searchbox1').on('keyup focus', function(e) {
var b = $(this).attr();
delete b.class, delete b.placeholder, delete b.id, delete b.name, delete b.type, delete b.autocomplete;
b.q = $(this).val();
if (b.q != '' && b.q.length > 0) {
$.ajax({
type: "POST",
url: api,
data: b,
cache: false,
success: function(a) {
$("#livesearch1").html(a);
$("#livesearch1").fadeIn();
}
});
} else {
$("#livesearch1").fadeOut();
}
});
$('#searchbox1').on('blur', function(e) {
$('#livesearch1').fadeOut();
});
3. api call
case 'search':
if($app->isAdmin() || $app->isEditor() || $app->isUser())
{
$app->escape('q');
ob_start();
ajaxsearch($q);
echo $result = ob_get_clean();
// json('success','true','results',$result);
}
break;
4. .php file
function ajaxsearch1($q){
$db = MysqliDb::getInstance();
$csrf = new Csrf_Protect();
$q = removeWhiteSpace($q);
$q = htmlspecialchars_decode($q,ENT_QUOTES);
$q = preg_replace('/[^a-zA-Z0-9.-. .).(]/', '', $q);
if(strlen($q) >0 )
{
$term = $q;
$searchterm = explode(' ',$term);
$searchColumns = array("name","slug");
$searchCondition = '';
for($i = 0; $i < count($searchColumns); $i++)
{
$searchFieldName = $searchColumns[$i];
$searchCondition .= "($searchFieldName LIKE '%" . implode("%' AND $searchFieldName LIKE '%", $searchterm) . "%')";
if($i+1 < count($searchColumns)) $searchCondition .= " OR ";
}
$res = $db->rawQuery("SELECT * FROM tbl_templates WHERE ($searchCondition) AND (version='1') order by id desc Limit 10 ");
foreach($res as $sr)
{ ?><li><?=ucfirst($sr['name'])?></li><?php
}
}
}
?>
This was a parameter issue.
data was not in the $q it was in the $name code should be something like this.
case 'search':
if($app->isAdmin() || $app->isEditor() || $app->isUser())
{
$app->escape('name');
ob_start();
ajaxsearch($name);
echo $result = ob_get_clean();
}
break;

Live Update Table entries to database SQL PDO AJAX

i try to make an editable-table on a homepage which automatically save the new entries after you leave the "field" or press enter but something doesnt work.
Everthing is fine until i want to save the new entrie to database.
I fired the PDO-SQL-Statment and it works.
For me it seems to be the table_edit_ajax.php wasnt work but i dont know why!
Hope some of you guys can help me?
Im using a normal mysql database
Homepagecode:
<Table>
$getIDBusinessRessources = $dbPDO->geteditableSingleBusinessRessoure();
foreach($getIDBusinessRessources as $getidBusiness){
$id = $getidBusiness['checkid'] ;
echo '<tr id="'
. $getidBusiness['checkid']
. '" '
. 'class="edit_tr"'
. '>';
// Spalte Ressourcenname
echo '<td class="edit_td">'
.'<span id="RessourceName_'
.$getidBusiness['checkid']
. '" '
. 'class="text">'
.$getidBusiness['Rn']
.'</span>'
.'<input type="text" value="'
.$getidBusiness['Rn']
. '" class="editbox" id="Ressourcname_Input_'
. $getidBusiness['checkid']
.'">'
.'</td>';
// Spalte Amount
echo '<td class="edit_td">'
.'<span id="Amount_'
.$getidBusiness['checkid']
. '" '
. 'class="text">'
.$getidBusiness['AM']
.'</span>'
.'<input type="text" value="'
.$getidBusiness['AM']
. '" class="editbox" id="Amount_Input_'
. $getidBusiness['checkid']
.'" '
.'</td>';
</tr>
</table>
JS:
$( document ).ready(function() {
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#RessourceName_"+ID).hide();
$("#Amount_"+ID).hide();
$("#Ressourcname_Input_"+ID).show();
$("#Amount_Input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var first=$("#Ressourcname_Input_"+ID).val();
var last=$("#Amount_Input_"+ID).val();
var dataString = 'id='+ ID +'&RessourceName='+first+'&Amount='+last;
$("#RessourceName_"+ID).html('<img src="img/bearbeiten.png" />'); // Loading image
if(first.length>0&& last.length>0)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#RessourceName_"+ID).html(first);
$("#Amount_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
Ajax Code:
<?php
include "DBconnection.php";
if($_POST['id']){
$id = $_POST['checkid'];
$RessourceName = $_POST['Rn'];
$Amount = $_POST['AM'];
$dbPDO->UpdateLiveTableEntries($id,$RessourceName, $Amount );
}
?>
and at least the DB-Update code
function UpdateLiveTableEntries($id ,$Ressourcename, $Amount ){
// echo '<script type="text/javascript"> alert("inside");</script>';
$stmt = self::$_db->prepare("UPDATE BalancesheetInput SET RessourceName =:ressname , Amount =:menge WHERE ID =:id");
$stmt->bindParam(":id", $id);
$stmt->bindParam(":ressname", $Ressourcename);
$stmt->bindParam(":menge", $Amount);
$stmt->execute();
}
If you're sending this:
var dataString = 'id='+ ID +'&RessourceName='+first+'&Amount='+last;
^^ ^^^^^^^^^^^^^ ^^^^^^
why are you looking for these?
$id = $_POST['checkid'];
^^^^^---you aren't sending a 'checkid'
$RessourceName = $_POST['Rn'];
^-- you aren't sending an 'Rn'
$Amount = $_POST['AM'];
^^-- you aren't sending an 'AM'

AJAX request causes change function unbind

I want to implement simple functionality to allow users to save their message text as template to be used in the future.
php:
echo '<div id="container">';
$sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates
WHERE member_id = {$member_id}");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$confName = get_conference_name($confID);
$confName = formatText_safe($confName);
echo "<label>" . $lang['my_template'] . "</label><select id='tempchoose' name='templates'>";
if ($num_rows == 0) {
echo '<option value=""> ' . $lang['no_saved'] . '</option>';
} else {
for ($i = 0; $i < $num_rows; $i++) {
//$template_id = mysql_result($result, $i, 0);
$temp_text = mysql_result($result, $i, 1);
$temp_name = mysql_result($result, $i, 2);
echo '<option value="' . $temp_text . '">' . $temp_name . '</option>';
}
}
echo "</select></div>";
echo '<input id="send" name="Message" value="send" disabled="disabled" type="submit" />
<input id="temp" name="temp" type="button" value="save as template" />"
<textarea style="width: 99%;" id="textarea" name="TextBox" rows="8" disabled="disabled" type="text" value=""/></textarea>';
javascript:
$("#temp").bind("click", function(){
name=prompt("template name?");
temp_text = $("#textarea").val();
if (name!=null && name!="" && name!="null") {
$.ajax ({
data: {temp_text:temp_text, name:name},
type: 'POST',
url: 'save_template.php',
success: function(response) {
if(response == "1") {
alert("template saved successfully");
} else {
alert(response);
}
}
});
} else {
alert("invalid template name");
}
$.ajax ({
url: 'update_templates.php',
success: function(response) {
$("#container").html(response);
}
});
});
$("select").change(function () {
$("select option:selected").each(function () {
$("#textarea").removeAttr("disabled");
$("#send").removeAttr("disabled");
});
$("#textarea").val($(this).val());
})
.trigger('change');
update_temp.php
$sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates
WHERE member_id = {$member_id}");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$confName = get_conference_name($confID);
$confName = formatText_safe($confName);
echo "<label>".$lang['my_template']."</label><select id='tempchoose' name='templates'>";
if ($num_rows == 0) {
echo '<option value=""> '.$lang['no_saved'].'</option>';
} else {
for ($i = 0; $i < $num_rows; $i++) {
//$template_id = mysql_result($result, $i, 0);
$temp_text = mysql_result($result, $i, 1);
$temp_name = mysql_result($result, $i, 2);
echo '<option value="' . $temp_text . '">' . $temp_name . '</option>';
}
}
echo "</select>";
the last ajax request in #temp click function is used to updated the droplist with the newly created template, the problem is that when i click save template; ajax request is performed successfully and droplist is updated, however something wired happen which is that the change function of select is not working anymore! anyone knows where's the problem?
Because ajax will inject new elements to your DOM and those elements don't know about the binding you already defined.
Solution : use jQuery on
Change
$("select").change(function () {
to
$(document).on("change","select", function(){
jQuery on is available from 1.7+ version onwards, if you are using a previous version of jQuery, consider using delegate.
If you are rewriting the select with Ajax you should use .delegate() rather than simply .change, like:
$("someSelector").delegate("select", "change", function() {
// do stuff...
});
where someSelector is an element that contains your select.
Yes, because you have replaced the drop down inside of container, which will unhook all of the events on the drop down. The solution would be to modify the code as below:
$.ajax ({
url: 'update_templates.php',
success: function(response) {
$("#container").html(response);
$("#container select").change(
// your drop down change functionality here //
);
}
});
What this is doing is saying, "After the drop down has been refreshed, also refresh the event."
I hope this helps.

Categories