Why this Ajax ResponseText is empty? - javascript

$("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;
?>

Related

how to add characters to the end of the value if it already exists?

Here when I click post button it inserts a random value on database.
If a value already exists on database then show error. It works fine.
But I want to add 2/3 characters at the end of value if it already exists on database. If $check == 1 then I want to add some characters at the end of the value instead of showing alert. How to do this?
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
// if $check==1 then i want to add 2 characters at the end of $slug .
if($check == 1)
{
// instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database
echo "<script> alert('something is wrong') </script> ";
exit ();
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
<form method="POST" >
<?php
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chararray = str_split($chars);
for($i = 0; $i < 7 ; $i++)
{
$randitem = array_rand($chararray);
$result .= "".$chararray[$randitem];
}
echo $result ;
?>
<input type="hidden" value="<?php echo $result;?>" name="rand" />
<span class="input-group-btn">
<button class="btn btn-info" type="submit" name="submit">POST</button>
</span>
</form>
just run update query if $check == 1
if($check == 1){
$newSlug = $slug."xy";
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
$run = mysqli_query($con,$update );
echo "<script> alert('Updated Successfully') </script> ";
exit ();
}
This is helpful for you
<?php
$con = mysqli_connect("localhost","root","","post" ) or die
( "unable to connect to internet");
if(isset($_POST['submit'])){
$tmp_slug = $_POST['rand'];
$slug = $_POST['rand'];
while(check_exiest($tmp_slug))
{
$tmp_rand = rand(11,99);
$tmp_slug = $slug.$tmp_rand;
}
$insert ="insert into slug (post_slug) values ('$tmp_slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
public function check_exiest($slug)
{
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check >= 1)
{
return true;
}
else
{
return false;
}
}
?>
Just few modification in your code to insert new value.
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check == 1)
{
$slug_new = $slug.'ab'; // Add 2 characters at the end
$update ="UPDATE slug SET post_slug = '$slug_new' WHERE post_slug = '$slug'";
$run = mysqli_query($con,$update);
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>

php and ajax JavaScript pagination comment system

Trying to build a commenting system. Were comments are posted with AJAX. With comment count with Pagination. I have success achieving both, but putting them together is another story. I have tried doing 2 ajax calls. One for getting records from the database and showing pagination. The other call for recording records to the database.
// this is the first ajax call to to get the results and show pagination buttons
<script>
function request_page(pn){
var two = <?php echo $img_id; ?>;
var showmax = <?php echo SHOWMAX; ?>; // results per page
var totalpages = <?php echo $totalpages; ?>;
//controls for pigmintation
var pagination_controls = document.getElementById("pagination_controls");
var results_box = document.getElementsByClassName(two)[0];
params = 'showmax=' + showmax + '&totalpages=' + totalpages + '&pn=' + pn + '&img_id=' + two;
request = new ajaxRequest()
request.open("POST", "response5.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
results_box.innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(totalpages != 1)
{
if( pn > 1){
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+totalpages+'</b> ';
if (pn != totalpages) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
<script> request_page(<?php echo $totalpages; ?>); </script>
/// the response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$curPage = (int) sanitizeString($_POST['pn']);
$showmax = (int) sanitizeString($_POST['showmax']);
$totalpages = (int) sanitizeString($_POST['totalpages']);
$z = (int) sanitizeString($_POST['img_id']);
if ($curPage < 1) {
$curPage = 1;
} else if ($curPage > $totalpages) {
$curPage = $totalpages;
}
$offset = ($curPage-1) * $showmax;
// var_dump($showmax);
$one = $showmax;
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
//fetch resuls
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
////ajax call # 2 is triggered when ever the comment form is submitted
<div>
<form method='post' id="form<?php echo $img_id; ?>" name="<?php echo $img_id; ?>">
<textarea class='lake' name='one' placeholder="Comment" id='<?php echo $img_id; ?>'></textarea>
<input id="submit" onclick="showUser(document.getElementById(<?php echo $img_id; ?>).value, <?php echo $img_id; ?>);" type="button" value="Submit">
</form>
</div>
//// the ajax call function
function showUser(a, b){
name = a;
two = b;
yes = "form" + two;
params = 'name1=' + name + '&two1=' + two;
request = new ajaxRequest()
request.open("POST", "response10.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementsByClassName(two)[0].innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
document.getElementById(yes).reset();
return false;
}
The response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
define('SHOWMAX', 5);
$q = sanitizeString($_POST['name1']);
$z = sanitizeString($_POST['two1']);
$b = sanitizeString($_SESSION['user_id']);
$sql = 'INSERT INTO img_comment (img_id, comment, user_id)
VALUES(:img_id, :comment, :user_id)';
// prepare the statement
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':img_id', $z, PDO::PARAM_INT);
$stmt->bindParam(':comment', $q, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $b, PDO::PARAM_INT);
$stmt->execute();
$OK = $stmt->rowCount();
$getCount = 'SELECT COUNT(*) FROM img_comment WHERE img_id ='. $z;
// submit query and store result as $totalPix
$total = $pdo->query($getCount);
$totalCount = $total->fetchColumn();
// var_dump($totalCount);
$total = (int)$totalCount;
$totalpages = (int) ceil($total/ SHOWMAX);
$offset = ($totalpages-1) * SHOWMAX;
$one = SHOWMAX;
if($totalCount > 0){
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
}

Uncaught SyntaxError: Unexpected token < - Wordpress

I am using the Penny auction theme and I am getting the following error message:
Uncaught SyntaxError: Unexpected token < penny_scripts.js:126
When I expand the error it shows:
(anonymous function) penny_scripts.js:126
$.ajax.success smart-updater.js:146
j jquery.js?ver=1.11.0:2
k.fireWith jquery.js?ver=1.11.0:2
x jquery.js?ver=1.11.0:4
b jquery.js?ver=1.11.0:4
Line 126 of penny_scripts.js is
var myObj = eval("(" + data + ")");
for (var i = 0; i < myObj.length; i++) <---This line
{
pid = myObj[i].pid;
rnd = myObj[i].rnd;
remaining_time = myObj[i].remaining_time;
current_bid = myObj[i].current_bid;
If I do alert(data); then I get the following message
Line 1092 of functions.php is:
$info = array(); global $wpdb;
$my_arr = $_POST['my_values'];
$OKOK = $_POST['OKOK'];
foreach($my_arr as $id_plus_rand)
{
$exp = explode("_",$id_plus_rand);
$pid = $exp[0];
$rnd = $exp[1];
//----------------------
$newpid = array();
$highest_bidder_id = PennyTheme_get_highest_bid_owner_obj($pid);
if($highest_bidder_id == false) $highest_bidder = "0";
else {
$s = "select user_login from ".$wpdb->users." where ID='{$highest_bidder_id->uid}'";
$r = $wpdb->get_results($s); $r = $r[0];
$highest_bidder = $r->user_login;
}
$newpid['highest_bidder'] = $highest_bidder;
$newpid['highest_bidder_id'] = $highest_bidder_id->id;
$newpid['pid'] = $pid;
$newpid['rnd'] = $rnd;
$newpid['remaining_time'] = get_post_meta($pid, 'ending', true) - current_time('timestamp',0);
$newpid['current_bid'] = PennyTheme_get_show_price(get_post_meta($pid, 'current_bid', true));
if($OKOK == "1"):
//$closed = get_post_meta($pid, 'closed', true);
//$post = get_post($pid);
$bids = "select * from ".$wpdb->prefix."penny_bids where pid='$pid' order by id DESC limit 13";
$res = $wpdb->get_results($bids);
$all_bids = '';
if(count($res) > 0)
{
$all_bids .= '<table width="100%">';
$all_bids .= '<thead><tr>';
$all_bids .= '<th>'.__('Username','PennyTheme').'</th>';
$all_bids .= '<th>'.__('Bid Amount','PennyTheme').'</th>';
// echo '<th>'.__('Date Made','PennyTheme').'</th>';
$all_bids .= '</tr></thead><tbody>';
//-------------
foreach($res as $row)
{
$user = get_userdata($row->uid);
$s = "select user_login from ".$wpdb->users." where ID='{$row->uid}'";
$r = $wpdb->get_results($s);
$all_bids .= '<tr>';
$all_bids .= '<th>'.$r[0]->user_login.'</th>';
$all_bids .= '<th>'.PennyTheme_get_show_price($row->bid).'</th>';
// echo '<th>'.date("d-M-Y H:i:s", $row->date_made).'</th>';
$all_bids .= '</tr>';
}
$all_bids .= '</tbody></table>';
}
else $all_bids .= __("No bids placed yet.", 'PennyTheme');
$newpid['bidders'] = $all_bids;
endif;
array_push($info,$newpid);
}
header('Content-type: application/json'); <---Line 1092
Line 146 of smart-update.js is:
if(es.rCallback && rCallback && es.rCallback.search(rCallback) != -1) {
window[rCallback](data);
} else {
es.callback(data); <---This line
}
Line 1395 of plugin.php:
function remove_menu_page( $menu_slug ) {
global $menu;
foreach ( $menu as $i => $item ) { <-- This line
if ( $menu_slug == $item[2] ) {
unset( $menu[$i] );
return $item;
}
}
return false;
}
I only get this error message when I am not logged into the site or logged in with an account that the user level is below Contributor.
I am unsure why that is happening or how to fix this. Any help is appreciated.
The above problem was caused by a plugin that I had enabled on my site. When I updated it, the error stopped. The error doesn't happen with version 2.19.5 or above. Changelog for 2.19.5
Remove Testimonials menu for authors removal code <--This was the change that fixed the error for me.
Require Aihrus Framework 1.1.4
Revise premium introduction
Update premium links

Update data through checkbox using jquery

I can't get this to work. I need to update the value of a column of the checked checkboxes in mysql. When I click the button it is supposed to update the value of the checked checkboxes. Here is my code for editLayout.php:
<form action="updateLayout.php" method="POST">
<input name="update" type="SUBMIT" value="Update" id="update">
<?php
$x = 'seats';
$linkID = # mysql_connect("localhost", "root", "Newpass123#") or die("Could not connect to MySQL server");
# mysql_select_db("seatmapping") or die("Could not select database");
/* Create and execute query. */
$query = "SELECT * from $x order by rowId, columnId desc";
$result = mysql_query($query);
$prevRowId = null;
$seatColor = null;
$tableRow = false;
//echo $result;
echo "<table class='map'>";
while (list($rowId, $columnId, $status, $name, $seatid) = mysql_fetch_row($result))
{
if ($prevRowId != $rowId) {
if ($rowId != 'A') {
echo "</tr></table></td>";
echo "\n</tr>";
}
$prevRowId = $rowId;
echo "\n<tr><td align='center'><table><tr>";
} else {
$tableRow = false;
}
if ($status == 0) {
$seatColor = "#A6E22E";
}
else if ($status == 1){
$seatColor = "#D34836";
}
else if ($status == 2){
$seatColor = "#00A0D1";
}
echo "\n<td bgcolor='$seatColor'>";
echo $seatid;
echo "<input type='checkbox' name='seats[]' id='seats' value=".$seatid."> </checkbox>";
echo "</td>";
}
echo "</tr></table></td>";
echo "</tr>";
echo "</form>";
echo "</table>";
/* Close connection to database server. */
mysql_close();
?>
And here is my code for the jquery residing on different page (functions.js). I already included this in the header:
jQuery(function($) {
$("form input[id='update']").click(function() {
var count_checked = $("[name='seats[]']:checked").length;
if(count_checked == 0) {
alert("Please select product(s) to update.");
return false;
}
if(count_checked == 1) {
return confirm("Are you sure you want to update these product?");
} else {
return confirm("Are you sure you want to update these products?");
}
});
});
And here is my updateLayout.php.:
<?php
$db = mysql_connect("localhost", "root", "Newpass123#");
if(!$db) { echo mysql_error(); }
$select_db = mysql_select_db("seatmapping");
if(!$select_db) { echo mysql_error(); }
if(isset($_POST['update'])) {
$id_array = $_POST['seats'];
$id_count = count($_POST['seats']);
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$seatid'");
if(!$query) { die(mysql_error()); }
}
header("Location: editLayout.php");
}
?>
I'm using jquery 1.11.0. I know there's a lot of sql injection in here and im still using mysql but I plan to change it all once I get this to work. Any kind of help is appreciated.
Thanks in advance.
Your update query doesn't use the correct update value. You use '$seatid', which isn't declared anywhere. You should use '$id'.
Change
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$seatid'");
if(!$query) { die(mysql_error()); }
}
into
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$id'");
if(!$query) { die(mysql_error()); }
}

how to display country and zone in opencart?

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.

Categories