I have created a registration page in admin section in OpenCart, in which we are asking details such as name, email, telephone, country, state/zone, password and many other things. Everything is working fine except country and zone form field. whenever I open the form I find one country always selected and nothing is displayed in zone field. This is first problem. When i choose another country then it loads state/zone, and if everything goes well, then the user gets registered. But if there is any error in form, then when it shows error on the page, state/zone value gets lost again. I have to reselect country and then zone is displayed. I have checked through "echo" that value of zone is transferred to this page but not shown selected in the drop down.this is my main problem.
this is the link to first image--
now this is the second image in which error messages are displayed---
Now someone please tell me what should i do?
I'm not an expert of opencart. i have just created this for the first time. I also don't have knowledge of jquery or javascript.
please tell me which part of code should I put here for getting solution.
thanks !!
this is customer.tpl template file
<tr>
<td><span class="required">*</span> <?php echo $entry_country; ?></td>
<td><select name="country_id" onchange="country(this);">
<option value=""><?php echo $text_select; ?></option>
<?php foreach ($countries as $country) { ?>
<?php if ($country['country_id'] == $country_id) { ?>
<option value="<?php echo $country['country_id']; ?>" selected="selected"><?php echo $country['name']; ?></option>
<?php } else { ?>
<option value="<?php echo $country['country_id']; ?>"><?php echo $country['name']; ?></option>
<?php } ?>
<?php } ?>
</select><?php if ($error_country) { ?>
<span class="error"><?php echo $error_country; ?></span>
<?php } ?></td>
</tr>
<tr>
<td><span class="required">*</span> <?php echo $entry_zone; ?></td>
<td><select name="zone_id">
</select><?php if ($error_zone) { ?>
<span class="error"><?php echo $error_zone; ?></span>
<?php } ?></td>
</tr>
<!-- ... -->
<script type="text/javascript">
function country(element) {
if (element.value != '') {
$.ajax({
url: 'index.php?route=seller/customer/country&token=<?php echo $token; ?>&country_id=' + element.value,
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after('<span class="wait"> <img src="catalog/view/theme/default/image/loading.gif" alt="" /></span>');
},
complete: function() {
$('.wait').remove();
},
success: function(json) {
html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == '<?php echo $zone_id; ?>') {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
}
$('select[name$=\'[country_id]\']').trigger('change');
</script>
and this is customer.php controller file
<?php
class ControllerSellerCustomer extends Controller {
private $error = array();
public function index() {
$this->language->load('seller/customer');
$this->document->setTitle($this->language->get('heading_title'));
//$this->load->model('sale/customer');
$this->getForm();
}
public function insert() {
$this->language->load('seller/customer');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('seller/customer');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
$this->model_seller_customer->addCustomer($this->request->post);
$this->session->data['success'] = $this->language->get('text_success');
$this->redirect($this->url->link('seller/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
}
$this->getForm();
}
protected function getForm() {
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['text_enabled'] = $this->language->get('text_enabled');
$this->data['text_disabled'] = $this->language->get('text_disabled');
$this->data['text_select'] = $this->language->get('text_select');
$this->data['text_none'] = $this->language->get('text_none');
$this->data['text_wait'] = $this->language->get('text_wait');
$this->data['text_no_results'] = $this->language->get('text_no_results');
$this->data['entry_description'] = $this->language->get('entry_description');
$this->data['entry_firstname'] = $this->language->get('entry_firstname');
$this->data['entry_email'] = $this->language->get('entry_email');
$this->data['entry_telephone'] = $this->language->get('entry_telephone');
$this->data['entry_business'] = $this->language->get('entry_business');
$this->data['entry_password'] = $this->language->get('entry_password');
$this->data['entry_confirm'] = $this->language->get('entry_confirm');
$this->data['entry_status'] = $this->language->get('entry_status');
$this->data['entry_company'] = $this->language->get('entry_company');
$this->data['entry_company_id'] = $this->language->get('entry_company_id');
$this->data['entry_address'] = $this->language->get('entry_address');
$this->data['entry_city'] = $this->language->get('entry_city');
$this->data['entry_zone'] = $this->language->get('entry_zone');
$this->data['entry_country'] = $this->language->get('entry_country');
$this->data['button_save'] = $this->language->get('button_save');
$this->data['button_cancel'] = $this->language->get('button_cancel');
$this->data['tab_general'] = $this->language->get('tab_general');
$this->data['token'] = $this->session->data['token'];
if (isset($this->error['warning'])) {
$this->data['error_warning'] = $this->error['warning'];
} else {
$this->data['error_warning'] = '';
}
if (isset($this->session->data['success'])) {
$this->data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$this->data['success'] = '';
}
if (isset($this->error['firstname'])) {
$this->data['error_firstname'] = $this->error['firstname'];
} else {
$this->data['error_firstname'] = '';
}
if (isset($this->error['email'])) {
$this->data['error_email'] = $this->error['email'];
} else {
$this->data['error_email'] = '';
}
if (isset($this->error['telephone'])) {
$this->data['error_telephone'] = $this->error['telephone'];
} else {
$this->data['error_telephone'] = '';
}
if (isset($this->error['company'])) {
$this->data['error_company'] = $this->error['company'];
} else {
$this->data['error_company'] = '';
}
if (isset($this->error['business'])) {
$this->data['error_business'] = $this->error['business'];
} else {
$this->data['error_business'] = '';
}
if (isset($this->error['description'])) {
$this->data['error_description'] = $this->error['description'];
} else {
$this->data['error_description'] = '';
}
if (isset($this->error['password'])) {
$this->data['error_password'] = $this->error['password'];
} else {
$this->data['error_password'] = '';
}
if (isset($this->error['confirm'])) {
$this->data['error_confirm'] = $this->error['confirm'];
} else {
$this->data['error_confirm'] = '';
}
if (isset($this->error['address'])) {
$this->data['error_address'] = $this->error['address'];
} else {
$this->data['error_address'] = '';
}
if (isset($this->error['city'])) {
$this->data['error_city'] = $this->error['city'];
} else {
$this->data['error_city'] = '';
}
if (isset($this->error['country'])) {
$this->data['error_country'] = $this->error['country'];
} else {
$this->data['error_country'] = '';
}
if (isset($this->error['zone'])) {
$this->data['error_zone'] = $this->error['zone'];
} else {
$this->data['error_zone'] = '';
}
$url = '';
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('seller/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'),
'separator' => ' :: '
);
//SAVE and CANCEL Button
$this->data['action'] = $this->url->link('seller/customer/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
$this->data['cancel'] = $this->url->link('seller/customer', 'token=' . $this->session->data['token'] . $url, 'SSL');
//SAVE and CANCEL Button
//BUSINESS TYPE
//Calling the model for displaying business type
$this->load->model('seller/customer');
$this->data['businesses'] = $this->model_seller_customer->getBusiness();
//BUSINESS TYPE
//print_r($this->data['businesses']);die;
// For displaying values in form fields if an error occurs
if (isset($this->request->post['firstname'])) {
$this->data['firstname'] = $this->request->post['firstname'];
} else {
$this->data['firstname'] = '';
}
if (isset($this->request->post['email'])) {
$this->data['email'] = $this->request->post['email'];
} else {
$this->data['email'] = '';
}
if (isset($this->request->post['telephone'])) {
$this->data['telephone'] = $this->request->post['telephone'];
} else {
$this->data['telephone'] = '';
}
if (isset($this->request->post['company'])) {
$this->data['company'] = $this->request->post['company'];
} else {
$this->data['company'] = '';
}
if (isset($this->request->post['business_id'])) {
$this->data['business_id'] = $this->request->post['business_id'];
} elseif (isset($this->session->data['business_id'])) {
$this->data['business_id'] = $this->session->data['business_id'];
} else {
$this->data['business_id'] = $this->config->get('business_id');
}
if (isset($this->request->post['description'])) {
$this->data['description'] = $this->request->post['description'];
} else {
$this->data['description'] = '';
}
if (isset($this->request->post['address'])) {
$this->data['address'] = $this->request->post['address'];
} else {
$this->data['address'] = '';
}
if (isset($this->request->post['city'])) {
$this->data['city'] = $this->request->post['city'];
} else {
$this->data['city'] = '';
}
if (isset($this->request->post['country_id'])) {
$this->data['country_id'] = $this->request->post['country_id'];
} elseif (isset($this->session->data['country_id'])) {
$this->data['country_id'] = $this->session->data['country_id'];
} else {
$this->data['country_id'] = '';
}
if (isset($this->request->post['zone_id'])) {
$this->data['zone_id'] = $this->request->post['zone_id'];
} elseif (isset($this->session->data['zone_id'])) {
$this->data['zone_id'] = $this->session->data['zone_id'];
} else {
$this->data['zone_id'] = '';
}
if (isset($this->request->post['password'])) {
$this->data['password'] = $this->request->post['password'];
} else {
$this->data['password'] = '';
}
if (isset($this->request->post['confirm'])) {
$this->data['confirm'] = $this->request->post['confirm'];
} else {
$this->data['confirm'] = '';
}
if (isset($this->request->post['status'])) {
$this->data['status'] = $this->request->post['status'];
} else {
$this->data['status'] = 1;
}
$this->load->model('localisation/country');
$this->data['countries'] = $this->model_localisation_country->getCountries();
$this->template = 'seller/customer_form.tpl';
$this->children = array(
'common/header',
'common/footer'
);
$this->response->setOutput($this->render());
}
protected function validateForm() { //echo "validating"; die;
if (!$this->user->hasPermission('modify', 'seller/customer')) {
$this->error['warning'] = $this->language->get('error_permission');
}
if ((utf8_strlen($this->request->post['firstname']) < 1) || (utf8_strlen($this->request->post['firstname']) > 32) || (!preg_match('/^[A-Za-z ]+$/', $this->request->post['firstname']))) {
$this->error['firstname'] = $this->language->get('error_firstname');
}
if ((utf8_strlen($this->request->post['description']) < 100) || (utf8_strlen($this->request->post['description']) > 1000)) {
$this->error['description'] = $this->language->get('error_description');
}
if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\#]+#.*\.[a-z]{2,6}$/i', $this->request->post['email'])) {
$this->error['email'] = $this->language->get('error_email');
}
//For displaying error message if same email-id exist in database.
$rv = mysql_query("SELECT email FROM " . DB_PREFIX . "seller_details WHERE email = '" . $this->request->post['email']."'");
$row = mysql_fetch_array($rv);
if ( !empty($row['email']) )
{
$this->error['email'] = $this->language->get('error_email_exist');
}
//For displaying error message if same telephone number exist in database.
$rv = mysql_query("SELECT phone FROM " . DB_PREFIX . "seller_details WHERE phone = '" . $this->request->post['telephone']."'");
$row = mysql_fetch_array($rv);
if ( !empty($row['phone']) )
{
$this->error['telephone'] = $this->language->get('error_telephone_exist');
}
//For displaying error message if same store name exist in database.
$rv = mysql_query("SELECT store_name FROM " . DB_PREFIX . "seller_details WHERE store_name = '" . $this->request->post['company']."'");
$row = mysql_fetch_array($rv);
if ( !empty($row['store_name']) )
{
$this->error['company'] = $this->language->get('error_store_exist');
}
//$customer_info = $this->model_sale_customer->getCustomerByEmail($this->request->post['email']);
if ((utf8_strlen($this->request->post['telephone']) < 10) || !preg_match('/[0-9]+/', $this->request->post['telephone'])) {
$this->error['telephone'] = $this->language->get('error_telephone');
}
if ((utf8_strlen($this->request->post['company']) < 3) || (utf8_strlen($this->request->post['company']) > 32)) {
$this->error['company'] = $this->language->get('error_company');
}
//If no business_type is selected then error message is displayed.
if ($this->request->post['business_id'] == '') {
$this->error['business'] = $this->language->get('error_business');
}
if (!isset($this->request->post['zone_id']) || $this->request->post['zone_id'] == '') {
$this->error['zone'] = $this->language->get('error_zone');
}
if ($this->request->post['password'] || (!isset($this->request->get['customer_id']))) {
if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
$this->error['password'] = $this->language->get('error_password');
}
if ($this->request->post['password'] != $this->request->post['confirm']) {
$this->error['confirm'] = $this->language->get('error_confirm');
}
}
if ($this->error && !isset($this->error['warning'])) {
$this->error['warning'] = $this->language->get('error_warning');
}
if (!$this->error) {
return true;
} else {
return false;
}
}
public function country() {//echo "country"; die;
$json = array();
$this->load->model('localisation/country');
$country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']);
if ($country_info) {
$this->load->model('localisation/zone');
$json = array(
'country_id' => $country_info['country_id'],
'name' => $country_info['name'],
'iso_code_2' => $country_info['iso_code_2'],
'iso_code_3' => $country_info['iso_code_3'],
'address_format' => $country_info['address_format'],
'zone' => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']),
'status' => $country_info['status']
);
}
//print_r($json['zone'][0]['name']);die;
$this->response->setOutput(json_encode($json));
}
}
?>
I just made changes two changes in the template file --
1. HTML part
2. Ajax Script
HTML part is --
<tr>
<td><span class="required">*</span> <?php echo $entry_country; ?></td>
<td><select name="country_id">
<option value=""><?php echo $text_select; ?></option>
<?php foreach ($countries as $country) { ?>
<?php if ($country['country_id'] == $country_id) { ?>
<option value="<?php echo $country['country_id']; ?>" selected="selected"><?php echo $country['name']; ?></option>
<?php } else { ?>
<option value="<?php echo $country['country_id']; ?>"><?php echo $country['name']; ?></option>
<?php } ?>
<?php } ?>
</select>
<?php if ($error_country) { ?>
<span class="error"><?php echo $error_country; ?></span>
<?php } ?>
</td>
</tr>
<tr>
<td><span class="required">*</span> <?php echo $entry_zone; ?></td>
<td><select name="zone_id">
<option value=""><?php echo $text_select; ?></option>
</select>
<?php if ($error_zone) { ?>
<span class="error"><?php echo $error_zone; ?></span>
<?php } ?></td>
</tr>
Ajax part is --
<script type="text/javascript">
$('select[name=\'country_id\']').bind('change', function() {
$.ajax({
url: 'index.php?route=seller/customer/country&token=<?php echo $token; ?>&country_id=' + this.value,
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after('<span class="wait"> <img src="catalog/view/theme/default/image/loading.gif" alt="" /></span>');
},
complete: function() {
$('.wait').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').show();
} else {
$('#postcode-required').hide();
}
html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == '<?php echo $zone_id; ?>') {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
$('select[name=\'country_id\']').trigger('change');
</script>
In Your getForm() function find these lines:
if (isset($this->request->post['business_id'])) {
$this->data['business_id'] = $this->request->post['business_id'];
} elseif (isset($this->session->data['business_id'])) {
$this->data['business_id'] = $this->session->data['business_id'];
} else {
$this->data['business_id'] = $this->config->get('business_id');
}
// few lines later
if (isset($this->request->post['country_id'])) {
$this->data['country_id'] = $this->request->post['country_id'];
} elseif (isset($this->session->data['country_id'])) {
$this->data['country_id'] = $this->session->data['country_id'];
} else {
$this->data['country_id'] = '';
}
if (isset($this->request->post['zone_id'])) {
$this->data['zone_id'] = $this->request->post['zone_id'];
} elseif (isset($this->session->data['zone_id'])) {
$this->data['zone_id'] = $this->session->data['zone_id'];
} else {
$this->data['zone_id'] = '';
}
and change them to
if (isset($this->request->post['business_id'])) {
$this->data['business_id'] = $this->request->post['business_id'];
} else {
$this->data['business_id'] = $this->config->get('business_id');
}
if (isset($this->request->post['country_id'])) {
$this->data['country_id'] = $this->request->post['country_id'];
} else {
$this->data['country_id'] = '';
}
if (isset($this->request->post['zone_id'])) {
$this->data['zone_id'] = $this->request->post['zone_id'];
} else {
$this->data['zone_id'] = '';
}
You are not working with session here but it may happen that the concrete values could be in session from some other form and this could mess things up.
Related
$("b_xml").onclick=function(){
new Ajax.Request("books.php", {
method:"GET",
parameters: {category:getCheckedRadio(document.getElementsByName("category"))},
onSuccess: showBooks_JSON,
onFailure: ajaxFailed
})
}
When click button, new Ajax Request is created and call data from books.php.
so I use getElementByName to collect all named="category" radio button
here is my html code
<label><input type="radio" name="category" value="children" checked="checked"/> Children</label>
<label><input type="radio" name="category" value="computers" /> Computers</label>
<label><input type="radio" name="category" value="cooking" /> Cooking</label>
<label><input type="radio" name="category" value="finance" /> Finance</label>
and books.php
<?php
$BOOKS_FILE = "books.txt";
function filter_chars($str) {
return preg_replace("/[^A-Za-z0-9_]*/", "", $str);
}
if (!isset($_SERVER["REQUEST_METHOD"]) || $_SERVER["REQUEST_METHOD"] != "GET") {
header("HTTP/1.1 400 Invalid Request");
die("ERROR 400: Invalid request - This service accepts only GET requests.");
}
$category = "";
$delay = 0;
if (isset($_REQUEST["category"])) {
$category = filter_chars($_REQUEST["category"]);
}
if (isset($_REQUEST["delay"])) {
$delay = max(0, min(60, (int) filter_chars($_REQUEST["delay"])));
}
if ($delay > 0) {
sleep($delay);
}
if (!file_exists($BOOKS_FILE)) {
header("HTTP/1.1 500 Server Error");
die("ERROR 500: Server error - Unable to read input file: $BOOKS_FILE");
}
header("Content-type: application/xml");
print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
print "<books>\n";
$lines = file($BOOKS_FILE);
for ($i = 0; $i < count($lines); $i++) {
list($title, $author, $book_category, $year, $price) = explode("|", trim($lines[$i]));
if ($book_category == $category) {
print "\t<book category=\"$category\">\n";
print "\t\t<title>$title</title>\n";
print "\t\t<author>$author</author>\n";
print "\t\t<year>$year</year>\n";
print "\t\t<price>$price</price>\n";
print "\t</book>\n";
}
}
print "</books>";
?>
I checked books.txt is not empty
and when I click button, alert is work but It returns empty box.
What is problem?
To return JSON from your books.php
<?
$BOOKS_FILE = "books.txt"; $BOOKS_XML = "";
function filter_chars($str) {
return preg_replace("/[^A-Za-z0-9_]*/", "", $str);
}
if (!isset($_SERVER["REQUEST_METHOD"]) || $_SERVER["REQUEST_METHOD"] != "GET") {
header("HTTP/1.1 400 Invalid Request");
die("ERROR 400: Invalid request - This service accepts only GET requests.");
}
$category = "";
$delay = 0;
if (isset($_REQUEST["category"])) {
$category = filter_chars($_REQUEST["category"]);
}
if (isset($_REQUEST["delay"])) {
$delay = max(0, min(60, (int) filter_chars($_REQUEST["delay"])));
}
if ($delay > 0) {
sleep($delay);
}
if (!file_exists($BOOKS_FILE)) {
header("HTTP/1.1 500 Server Error");
die("ERROR 500: Server error - Unable to read input file: $BOOKS_FILE");
}
header("Content-type: application/xml");
$BOOKS_XML += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$BOOKS_XML += "<books>\n";
$lines = file($BOOKS_FILE);
for ($i = 0; $i < count($lines); $i++) {
list($title, $author, $book_category, $year, $price) = explode("|", trim($lines[$i]));
if ($book_category == $category) {
$BOOKS_XML += "\t<book category=\"$category\">\n";
$BOOKS_XML += "\t\t<title>$title</title>\n";
$BOOKS_XML += "\t\t<author>$author</author>\n";
$BOOKS_XML += "\t\t<year>$year</year>\n";
$BOOKS_XML += "\t\t<price>$price</price>\n";
$BOOKS_XML += "\t</book>\n";
}
}
$BOOKS_XML += "</books>";
$JSON = json_encode(simplexml_load_string($BOOKS_XML));
echo $JSON;
?>
I have a notifications system on my site, that utilizes AJAX to update in real-time. The problem is that it works on every browser except IE 11. After looking around I noticed some people advising to use cache:false in the call. However, this makes the code non-functional across all browsers. Anyone know what the solution is?
JAVASCRIPT:
<script>
$(document).ready(function(){
$('.notif_count').html('0');
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif_follow.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.notif_follow').html(data.notification);
if(data.notif_count > 0)
{
$('.notif_count').html(data.notif_count);
}
}
});
}
load_unseen_notification();
$(document).on('click', '.notif', function(){
$('.notif_count').html('0');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
</script>
PHP:
<?php
session_start();
require_once 'class.channel.php';
$user_notif = new USER();
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
if($_POST["view"] != '')
{
$stmt = $user_notif->runQuery("UPDATE notif_follow SET status = 1 WHERE receive_id = ?");
$stmt->bindValue(1,$user_id);
$stmt->execute();
}
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if(count($notifs) > 0)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT * FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetchAll(PDO::FETCH_ASSOC);
if(count($query2result) > 0){
$follow = '<button class="button" style="margin:2px;">Remove Channel</button>';
}
else{
$follow = '<button class="button" style="margin:2px;">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
<button class="button" style="margin:2px;">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
$count = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? AND status= 0");
$count->bindValue(1,$user_id);
$count->execute();
$countresult = $count->fetchAll(PDO::FETCH_NUM);
if(count($countresult) > 0){
$notif_count = count($countresult);
}
else{
$notif_count = 0;
}
header('Content-type: application/json');
$notif_array = array('notification'=>$notification,'notif_count'=>$notif_count);
echo json_encode($notif_array);
}
?>
I mixed an "ajax select" and "while scrolling load data" script, and this is working, but I don't know how to print "not found data" in div.status when the output variable (on animals.php) is empty.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Animals</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="search">
<div class="filter category">
<select name="category" id="category">
<option value="">All</option>
<option value="free">Free</option>
<option value="lost">Lost</option>
<option value="found">Found</option>
</select>
</div>
<div class="filter chipnumber">
<input type="text" name="chipnumber" id="chipnumber"></div>
</div>
<div class="send">
<button type="submit" id="submit">Search</button>
</div>
</div>
<script>
$(document).ready(function() {
var animal_limit = 6;
var animal_start = 0;
var animal_action = 'inactive';
function load_animal_data() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
$.ajax({
url: "animals.php",
method: "POST",
data: {animal_limit:animal_limit, animal_start:animal_start, animal_action:animal_action, category:category, chipnumber:chipnumber},
success:function(data) {
$('div.animals').append(data);
if (data == '') {
animal_action = 'active';
} else {
animal_action = 'inactive';
}
}
});
}
load_animal_data();
function search() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
animal_start = 0;
load_animal_data();
}
$('#search').on('click', function() {
search();
});
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $('div.animals').height() && animal_action == 'inactive') {
animal_action = 'active';
animal_start = animal_start + animal_limit;
setTimeout(function() {
load_animal_data();
}, 1000);
}
});
});
</script>
<div class="animals"></div>
<div class="status"></div>
</body>
</html>
animals.php
<?php
$connect = mysqli_connect("localhost", "root", "", "petsdata");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($connect,"utf8");
$output = '';
$animal_start = $connect->real_escape_string($_POST["animal_start"]);
$animal_limit = $connect->real_escape_string($_POST["animal_limit"]);
$category = $connect->real_escape_string($_POST["category"]);
$chipnumber = $connect->real_escape_string($_POST["chipnumber"]);
if (isset($animal_start, $animal_limit, $category, $chipnumber)) {
if (!empty($category) && !empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($category)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND status = '1' ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
else {
$query = mysqli_query($connect, "SELECT * FROM animals ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
while ($row = mysqli_fetch_array($query)) {
$output .= '<div class="animal">';
$output .= '<span>Category: ' . $row["category"] . '</span>';
$output .= '<span>Chipnumber: ' . $row["chipnumber"] . '</span>';
$output .= '</div>';
}
}
echo $output;
?>
if($query->num_rows > 0){
//Proceed as normally
}else{
$output = 'No data Found';
}
I have some php and html code and a small bit of JavaScript. Its a like system. Click the like button or dislike button and when you exit/leave the page the JavaScript and ajax runs a php file to update the database with the changes.(+1 to likes or +1 to dislikes or -1 to dislikes etc.) There is one problem. I click like/dislike and then i leave/ refresh page and the likes have not changed in value. If i dont click anything, which means im not updating the database and i refresh/leave a second time the likes are updated on the screen to what they should be. The database gets updated when its suppose to, its the code that dosnt use the new value for whatever reason. Here's my code:
<?php
session_start();
error_reporting(0);
$GOTID = $_GET['id'];
$GOTtitle = $_GET['title'];
include_once "mysql_connect.php";
include_once "like.php";
//include_once "dislike.php";
$email ='';
$log = null;
$log1 = null;
if(isset($_SESSION["ID"])){
$log1 = $_SESSION["ID"];
}else{
$log1=null;
}
if(isset($_SESSION["EMAIL"])){
$log = $_SESSION["EMAIL"];
$email = $_SESSION["EMAIL"];
// echo $email;
}else{
$log=null;
}
$_SESSION["EMAIL"] = $log;
$title = "";
$text="";
$tags = "";
$views = "";
$likes = "";
$dislikes = "";
$id = "";
$userid = "";
$date = "";
$thumbnail = "";
$imageext = "";
$texttype = "";
$data = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row = mysql_fetch_array($data)) {
$title = $row[0];
$descrip = $row[1];
$id = $row[2];
$userid = $row[3];
$date = $row[4];
$views = $row[5];
$likes = $row[6];
$dislikes = $row[7];
$thumbnail = $row[8];
$imagext = $row[10];
$videourl = $row[11];
}
if($likes != '0' || $dislikes !='0'){
$total = $likes + $dislikes;
$likebar = round(($likes / $total) * 100);
$finlikes = (($likebar * 150)/100);
}else{
$finlikes = 150;
}
$query5 = mysql_query("UPDATE `videos` SET `views` = `views`+1 WHERE `videos`.`id` = $GOTID;");
$stop = false;
$fetchlast = mysql_query("SELECT `id` FROM videos WHERE id=(SELECT MAX(id) FROM videos)");
$lastrow = mysql_fetch_row($fetchlast);
$lastid = $lastrow[0];
for ($i=1; $i <= $lastid; $i++) {
if($GOTID == $id){
$stop = true;
break;
}else{
if($i >=$lastid && $GOTID != $id){
$stop = false;
header('HTTP/1.0 404 Not Found');
$_GET['e'] = 404;
die();
exit;
}
}
}
$username = '';
$userrep = '';
$rank = '';
$imageData = '';
$currentname = mysql_query("SELECT * FROM allaccounts WHERE id=$userid");
while ($row = mysql_fetch_array($currentname)) {
$username = $row[0];
$rank = $row[3];
$userrep = $row[7];
$data = $row["image"];
$ext = $row["filetype"];
// $img1 = Img_Resize($data);
// $imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
}
$liked = false;
$disliked = false;
$done = false;
$thing = mysql_query("SELECT `id` FROM likes WHERE id=(SELECT MAX(id) FROM likes)");
$lastrow = mysql_fetch_row($thing);
$lastid = $lastrow[0];
if($lastid == null || $lastid == '0'){
$lastid = '1';
}
$state1 = '';
for ($i=1; $i <= $lastid+1; $i++) {
$current = mysql_query("SELECT * FROM likes WHERE id=$i");
while ($row = mysql_fetch_array($current)) {
$id1 = $row[0];
$userid1 = $row[1];
$state1 = $row[2];
$articleid1 = $row[3];
if($done == false){
if($email == $userid1 && $articleid1 == $id && $state1 == '1'){
$liked = true;
$disliked = false;
$done = true;
break;
}else{
$liked = false;
}
if($email == $userid1 && $articleid1 == $id && $state1 == '0'){
$disliked = false;
$liked = false;
$done = true;
break;
}
if($email == $userid1 && $articleid1 == $id && $state1 == '2'){
$disliked = true;
$liked = false;
$done = true;
break;
}else{
$disliked = false;
}
}
}
}
$donetitle = str_replace(" ", "-", $title);
$_SESSION["prevpage"] = "video/".$id."/".$donetitle."";
$lik = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row22 = mysql_fetch_array($lik)) {
$Olikes = $row22[6];
}
$dis = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row22 = mysql_fetch_array($dis)) {
$Odislikes = $row22[7];
}
?>
<html>
<head>
<title><?php echo $title;?></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"language="javascript" type="text/javascript"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript">
var likes = <?php echo $likes;?>;
var dislikes = <?php echo $dislikes;?>;
</script>
<div class = "container_24">
<header>
</header>
<div class = "main clearfix">
<div class ="grid_24 ">
<div id = "rectarticletop">
<a onclick='like()' id="likebtn"><img id="alike"src="img/icons/like.png" alt = "like"/></a>
<div id="dislikes"><div style="width:<?php echo($finlikes);?>;" id="likes"></div></div>
<a onclick="dislike()" id="dislikebtn"><img id="adislike" src="img/icons/dislike.png" alt = "dislike" /></a>
<p id= "likesnum"><?php echo $likes; ?></p>
<p id= "dislikesnum"><?php echo $dislikes; ?></p>
<script type="text/javascript">
var Liked = "<?php echo $liked;?>";
var Disliked = "<?php echo $disliked;?>";
var Art = "<?php echo $id;?>";
var User = "<?php echo $email;?>";
var olikes = "<?php echo $Olikes;?>";
var odislikes = "<?php echo $Odislikes;?>";
var state = "<?php echo $state1; ?>";
if(Liked == null){
Liked = false;
}
if(Disliked == null){
Disliked == false;
}
if(!Liked){
console.log("not liked!");
}
if(!Disliked){
console.log("not disliked!");
}
var loged = "<?php echo($log);?>";
window.onbeforeunload = function() {
$.ajax({
type: "GET",
url: 'dealLikes.php?article='+Art+'&user='+User+'&state=1&likes='+likes+'&dislikes='+dislikes+'&Olikes='+olikes+'&Odislikes='+odislikes+'&prev='+state+'',
success: function(data){
console.log("Its done!");
}
});
};
setInterval(function changetext(){
document.getElementById('likesnum').innerHTML = likes;
document.getElementById('dislikesnum').innerHTML = dislikes;
if(Liked){
document.getElementById('alike').src = "img/icons/like1.png";
}else{
document.getElementById('alike').src = "img/icons/like.png";
}
if(Disliked){
document.getElementById('adislike').src = "img/icons/dislike1.png";
}else{
document.getElementById('adislike').src = "img/icons/dislike.png";
}
},20);
function like(){
if(loged){
if(Liked){
likes-=1;
Liked = false;
// document.getElementById('alike').src = "img/icons/like.png";
}else if(Disliked){
dislikes-=1;
Disliked = false;
likes+=1;
Liked = true;
// document.getElementById('alike').src = "img/icons/like1.png";
// document.getElementById('adislike').src = "img/icons/dislike.png";
}else{
likes+=1;
Liked = true;
// document.getElementById('alike').src = "img/icons/like1.png";
}
}else{
window.location = "login";
}
}
function dislike(){
if(loged){
if(Disliked){
dislikes-=1;
Disliked = false;
// document.getElementById('adislike').src = "img/icons/dislike.png";
}else if(Liked){
likes-=1;
Liked = false;
dislikes+=1;
Disliked = true;
// document.getElementById('adislike').src = "img/icons/dislike1.png";
//document.getElementById('alike').src = "img/icons/like.png";
}else{
dislikes+=1;
Disliked = true;
// document.getElementById('adislike').src = "img/icons/dislike1.png";
}
}else{
window.location = "login";
}
}
</script>
</div>
</div>
</div>
</div>
</body>
</html>
What is wrong with the code that makes it not update the amount of likes on the first refresh but does update on the second refresh?
Hi Guys I have this search from that takes a search term matches it with a table.field and in php it searches all matching data.
I want to add autocomplete to it, can anyone PLEASE assist?
Here is the HTML FORM
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<input type="text" id="searchThis" name="searchThis" placeholder="search" value="" size="14" />
<select name="searchItems" id="searchItems">
<optgroup value="Vehicles" label="Vehicles">Vehicles
<option value="vehicles.Make">Make</option>
<option value="vehicles.model">Model</option>
<option value="vehicles.RegNumber">Registration Number</option>
<option value="vehicles.licenseExpireDate">License Expire Date</option>
</optgroup>
<optgroup value="Owners" label="Owners">Clients
<option value="owners.OwnerName" label="" >Name</option>
<option value="owners.mobile">Mobile Number</option>
</optgroup>
</select>
<input type="submit" id="doSearch" name="Search" value="Search" />
</form>
<ul id="result">
</ul>
There is the JS
<script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function (){
$j("#searchThis").keyup(function()
{
var searchThis = $j('#searchThis').val();
var searchItems = $j('#searchItems').val();
var dataString = {'searchThis': searchThis,'searchItems':searchItems};
if(searchThis!='')
{
$j.ajax({
type: "POST",
url: "doAutocomplete_search.php",
data: dataString,
dataType: "html",
cache: false,
success: function(data)
{
$j("#result").html(data).show();
}
});
}return false;
});
$j("#result").live("click",function(e){
var clicked = $j(e.target);
var name = clicked.find('.name').html();
var decoded = $j("<div/>").html(name).text();
$j('#searchThis').val(decoded);
});
$j(document).live("click", function(e) {
var clicked = $j(e.target);
if (! clicked.hasClass("search")){
$j("#result").fadeOut();
}
});
$j('#searchid').click(function(){
$j("#result").fadeIn();
});
});
})($j);
And the PHP
function implement($cxn,$searchThis, $field) {
$show = "";
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
$srchData = array();
$rows = mysqli_fetch_row($selectc);
echo $rows;
//if() {, MYSQL_ASSOC
//echo var_dump($srchData);
$show .= '
<table style="border:2px solid #0000">';
//foreach($srchData as $fields=>$data) {
for($s=0; $s < $rows && $srchData = mysqli_fetch_assoc($selectc);$s++) {
if($srchStack[0] == 'vehicles' && $fields == 'RegNumber') {
$dataItem = $data;
$editTbl = 'Vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
} elseif($srchStack[0] == 'vehicles' && $fields == 'Make') {
$dataItem = $data;
$editTbl = 'vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
}
$show .= '<tr><td><a '.$link.'>'.$data.'</a></td></tr>
';
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
//}
}
echo implement($cxn, $_POST['searchThis'], $_POST['searchItems']);
$cxn->close();
Hi Guys so i had to do some refactoring, realized it was more the PHP MySQL code.
Here is the refactored PHP code
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
//$srchData = array();
$rows = mysqli_num_rows(#$selectc) or die(mysqli_error($cxn).'<br>No Rows returned...');
if($rows > 0) {//, MYSQL_ASSOC
//$link = ''; $l_c = 0;
$show .= '<table style="border:2px solid #0000">';
for($c = NULL;$c != $rows && $srchData = mysqli_fetch_assoc($selectc); $c++) {
foreach($srchData as $fields=>$data) {
if($fields == $srchStack[1]) {
$dataItem = $data;
$editTbl = $srchStack[0];
$show .= '<tr><td>'.$dataItem.'</td></tr>';//$a_json_row($dataItem);
//$show .= $link[$c];$link[$c]
}
}
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
Of-course the JS code still needs some more work but this greatly improved the results...
Hope this help someone...