Cannot get the dependent dropdown value from region dropdown - javascript

I would like to show the geozone in the registration account step as dropdown menu, just like the zone (region). But the value of the geozone is dependent to what customer choose in the zone (region).
The Picture
In the process, I already did some modifications to the controller, view, including controller. Just like in the pic below :
The geozone field is Kotamadya/Kabupaten.
But when I choose the region Aceh, the geozone field is not refreshed.
Error Message
I got error message like below :
SyntaxError: Unexpected token <
OK
<br />
<b>Fatal error</b>: Call to a member function
getGeozonesByZoneId() on a non-object in <b>
/home/........../catalog/controller/account/register.php
</b> on line <b>513</b><br />
The Code
In ../controller/account/register.php, I added some modifications as below :
public function zone() {
$json = array();
$this->load->model('localisation/zone');
$geozone_info = $this->model_localisation_zone->getZone($this->request->get['zone_id']);
if($geozone_info)
{
$this->load->model('localisation/geo_zone');
$json = array(
'country_id' => $geozone_info['country_id'],
'name' => $geozone_info['name'],
'code' => $geozone_info['code'],
'zone' => $geozone_info['zone_id'],
'geozone' => $this->model_localisation_geozone->getGeozonesByZoneId($this->request->get['zone_id']),
'status' => $geozone_info['status']
);
}
$this->response->setOutput(json_encode($json));
}
line 513 is :
'geozone' => $this->model_localisation_geozone->getGeozonesByZoneId($this->request->get['zone_id'])
I don't know what's wrong with the getGeozonesByZoneId function, because I think I already write the function correctly in ../model/localisation/geo_zone.php as below :
<?php
class ModelLocalisationGeozone extends Model {
public function getGeozone($zone_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "geo_zone WHERE geo_zone_id = '" . (int)$geo_zone_id . "'");
return $query->row;
}
public function getGeozonesByZoneId($zone_id) {
$geozone_data = $this->cache->get('geozone.' . (int)$zone_id);
if (!$geozone_data) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE zone_id = '" . (int)$zone_id . "'");
$geozone_data = $query->rows;
$this->cache->set('geozone.' . (int)$zone_id, $geozone_data);
}
return $geozone_data;
}
}
?>
and I already added javascript to register.tpl in view as below :
$('select[name=\'zone_id\']').bind('change', function(event, first_time) {
$.ajax({
url: 'index.php?route=account/register/zone&zone_id=' + this.value,
dataType: 'json',
beforeSend: function() {
$('select[name=\'zone_id\']').after('<span class="wait"> <img src="catalog/view/theme/default/image/loading.gif" alt="" /></span>');
},
complete: function() {
$('.wait').remove();
},
success: function(json) {
var html = '<option value=""><?php echo $text_select; ?></option>';
var selected = false;
if (json['geozone'] && json['geozone'] != '') {
for (i = 0; i < json['geozone'].length; i++) {
html += '<option value="' + json['geozone'][i]['geo_zone_id'] + '"';
if (json['geozone'][i]['geo_zone_id'] == '<?php echo $geo_zone_id; ?>') {
html += ' selected="selected"';
selected = true;
}
html += '>' + json['geozone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'geo_zone_id\']').html(html);
if(typeof first_time === "undefined" && selected) {
$("#register_details_form").validate().element('#register_details_form select[name="geo_zone_id"]');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
$('select[name=\'zone_id\']').trigger('change', ['first_time']);
anyone can help me to resolve this issue? or maybe have same experiences with me and willing to share your solutions to me?
thanks before in advance.

Use model_localisation_zone (defined variable) instead of model_localisation_geozone (not defined), or make sure the latter is defined.

if i am not wrong you are forgetting to load model Geozone in your register.php controller file add this line
$this->load->model('localisation/geozone');
to register.php
before calling function
$this->model_localisation_geozone->getGeozonesByZoneId($this->request->get['zone_id'])

Related

Condition in each function is outputting same set of results for all records

I am performing a foreach loop and then sending that data. Then in my AJAX function I am outputting the information in the success function. This all works fine.
However, I just tweaked the code to include a new data-attribute. This data-attribute holds the $creator variable. It can be seen here:
$html .= '<div class="projectCont" data-current="'.$category.'" data-creator="'.$project_creator.'">';
The correct data is outputting.
What I am having issues with is adding the active class to the container - .projectCont when the data-attribute - data-creator is customer.
Right now it seems like only the last looped object is being checked and then whatever this is, the rest of the data is taking on.
For example: I have around 10 looped object being outputted. For testing purposes, I changed the creator to "Customer" for only one of these - the last one in the database. Now when all of these loop and output, every single record has the class that was added based on my condition in the success.
Does anyone know why this is happening? I nested this condition in the each function thinking that it would check and modify each individual record.
Condition in question (see JS for more code):
var projectCreator = $('.projectCont').data('creator');
if (projectCreator == 'Customer') {
$('.creatorIcon').addClass('active');
console.log("It should be showing");
} else {
$('.creatorIcon').removeClass('active');
}
JS:
success: function (data) {
//console.log(data);
if (data == null) {
alert("Unable to retrieve projects!");
alert(data);
} else {
var displayProjects = JSON.parse(data);
$wrapper.empty();
$(displayProjects).each(function() {
$wrapper.append(this.html);
//console.log(this.html);
var projectCreator = $('.projectCont').data('creator');
if (projectCreator == 'Customer') {
$('.creatorIcon').addClass('active');
console.log("It should be showing");
} else {
$('.creatorIcon').removeClass('active');
}
});
$wrapper.append(startBuilding);
}
PHP:
if ($projects_stmt = $con->prepare($projects_sql)) {
$projects_stmt->execute();
$project_rows = $projects_stmt->fetchAll(PDO::FETCH_ASSOC);
$proj_arr = array();
foreach ($project_rows as $project_row) {
$project_creator = $project_row['creator'];
$html = '';
$html .= '<div class="projectCont" data-current="'.$category.'" data-creator="'.$project_creator.'">';
$html .= '<div class="creatorIcon"><img src="/Projects/expand.png" alt="Customer Photo"></div>';
$html .= '</div>';
$data = array('id' => $project_row['id'], 'date' => $project_row['date_added'], 'html' => $html);
$proj_arr[] = $data;
}
}
echo json_encode($proj_arr);
More JS:
$('.categoryList').on('click', function (event) {
$('#projectsWrap').addClass('active'); //Once a category is selected the project wrap section will show
$wrapper = $('#projectGallery');
category = $(this).data('category');
//console.log(category);
$.ajax({
url: '/php/projectLoadTest.php',
type: 'POST',
data: {
'category': category
},
success: function (data) {
//console.log(data);
if (data == null) {
alert("Unable to retrieve projects!");
alert(data);
} else {
var displayProjects = JSON.parse(data);
$wrapper.empty();
$(displayProjects).each(function() {
$wrapper.append(this.html);
//console.log(this.html);
var projectCreator = $('.projectCont').data('creator');
if (projectCreator == 'Customer') {
$('.creatorIcon').addClass('active');
console.log("It should be showing");
} else {
$('.creatorIcon').removeClass('active');
}
});
$wrapper.append(startBuilding);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
alert('There are currently no project images for this selection');
}
});
//was here
});
I think you shouldn't mess with the JS in this case - you can do this class manipulation in your PHP:
if ( $projects_stmt = $con->prepare( $projects_sql ) ) {
$projects_stmt->execute();
$project_rows = $projects_stmt->fetchAll( PDO::FETCH_ASSOC );
$proj_arr = array();
foreach ( $project_rows as $project_row ) {
$project_creator = $project_row[ 'creator' ];
$html = '';
$html .= '<div class="projectCont" data-current="' . $category . '" data-creator="' . $project_creator . '">';
// setting the active string - if Customer -> ' active'
$is_active = ( $project_creator == 'Customer' ) ? ' active' : '';
$html .= '<div class="creatorIcon' . $is_active . '"><img src="/Projects/expand.png" alt="Customer Photo"></div>';
$html .= '</div>';
$data = array( 'id' => $project_row[ 'id' ], 'date' => $project_row[ 'date_added' ], 'html' => $html );
$proj_arr[] = $data;
} // foreach
} // if
echo json_encode( $proj_arr );

How to properly concatenate values coming from Javascript and PHP?

I have been struggling with this for the last two hours and I can't get it to work. Take a look to the following piece of code:
$js = '$.extend($.fn.fmatter , {
userActions : function(cellvalue, options, rowData, addOrEdit) {
var data = cellvalue.split("|");
var id = options.rowId;
var actions = "";';
foreach ($editorActions as $linkType => $value) {
switch ($linkType) {
case 'view':
$js .= "if(data[1] == 1) {
actions += \"<a class='actionimage' href='" . $value . " + options.rowId' title='" . $this->translate->_e('View') . "' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>\";
}";
}
break;
}
As you can see id is a value coming from Javascript and $value is coming from PHP. The idea is to get an hyperlink as for example:
$value = "/route/to/function/";
id = 19009; // I've omitted the $ sign since this var is coming from JS
var href = "' . $value . '" + id;'
Then I need to use the href var as part of the <a> element shown right after the definition.
With my code above I am getting this error:
Uncaught SyntaxError: Invalid or unexpected token
Can I get some help to get this right?
UPDATE:
This is how the code looks like after I render the page:
$(function () {
$.extend($.fn.fmatter, {
userActions: function (cellvalue, options, rowdata) {
var data = cellvalue.split('|');
var id = options.rowId;
var actions = '';
console.log(id);
if (data[1] == 1) {
actions += "<a class='actionimage' href='/sf/distributor/show/ + options.rowId' title='View' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>";
}
return actions;
}
});
});
Notice how the function $.extend close properly. console.log(id) did print the value of options.rowId however this value doesn't have any effect on the hyperlink as you may notice this is the value /sf/distributor/show/ + options.rowId.
What is coming in $value is a plain string in the case above /sf/distributor/show/.
You're missing double quotes and to end and reopen the string around options.rowId and a + in:
actions += \"<a class='actionimage' href='" . $value . " + options.rowId'
It should be:
actions += \"<a class='actionimage' href='" . $value . "\" + options.rowId + \"'
Here you are missing "" and that way you are adding options.rowId as a string text.
href='/sf/distributor/show/" + options.rowId + "'

Unable to update div text from ajax response sent via php

Apologies for this question if something out there covers this. I searched and found many relevant posts which has allowed me to get to this point.
I have a form snippet with 1 input box and a button and a div for a status message:
<div>
<div>
<div>
<input id="discount_code"name="discount_code" placeholder=" Enter discount code."></input>
</div>
<div>
<a class="btn btn-xs btn-primary" id="btn-validate">Validate</a>
</div>
</div>
<div id="status_msg" style="border: 1px solid black"></div>
</div>
Then I have the following bits of javascript:
The bit that triggers based on the click:
$('#btn-validate').on('click', function(e) {
e.preventDefault();
validateCode(11); // "11" is a php-provided ID variable
});
The javscript with the ajax call:
function validateCode(eventID) {
var codeValue = $("#discount_code").val();
if (FieldIsEmpty(codeValue)) { // outside function that exists/works fine
$('#status_msg').html('Enter a discount code.').fadeIn(500);
$('#status_msg').fadeOut(2500);
//bootbox.alert("Please enter discount code to validate.");
} else {
$.ajax({
type: 'POST',
cache: false,
async: true,
url: '/include/discount_validation.php',
dataType: 'json',
data: {
event_id: eventID,
discount_code: codeValue
},
beforeSend: function() {
$('#status_msg').html('');
$('#status_msg').fadeIn(0);
},
success: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
});
}};
And I have a PHP file that, suffice it to say, is working and producing the following json outputs based on the input:
// do php database things...
header('Content-Type: application/json');
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => "$message"));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => "$message"));
}
In the above, I have bootbox.alert lines commented out but when they are active, the box appears and the message is as I would expect it to be.
And lastly, the first condition that triggers if the input box is empty, both fires the alert (when not commented) AND changes the text of #status_msg.
I put the border in to verify visibility and #status_msg is visible but just is not set when either success or error fires.
First check if you getting an object in the response
in the success add
alert(JSON.stringify(data));
If it shows the object then you are good to go else check the php file where you creating the object.
If object is recieved in the success of ajax then you need to parse the json object using jQuery.parseJSON
For Eg:
response = jQuery.parseJSON(data);
Now you have a javascript object with name response.
Now use it
response['status'] or response['message'] in the success of the ajax.
check the code
first discard : " from php code $message variable
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}
then use the response on font end success function :
success: function(data) {
$('#status_msg').html(data.message);
$('#status_msg').fadeIn(0);
},
Set your data like this inside ajax().
success: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
AND
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}

Unwanted JSON Response

I'm using this small JSON function with a database.
<script>
$(document).ready(function () {
var url = "Database.php";
$("#jsondata tbody").html("");
$.getJSON(url, function (data) {
$.each(data.users, function (i, user) {
var songdetails = "<p>"
+ "<p>" + user.Title + "</p>"
+ "<p>" + user.ArtistNumber + "</p>"
+ "<p>" + user.TrackTime + "</p>"
+ "<p>" + user.Composer + "</p>"
+ "<p>" + user.Lyricist + "</p>"
+ "</p>";
$(songdetails).appendTo("songlist");
});
});
});
</script>
This produces this in the browser, which I don't want/need.
{"users":[{"Title":"Anyway","ArtistNumber":"2","TrackTime":"167","Composer":"John
Glaze","Lyricist":"Kellee
Maize","FileLocation":"public/Anyway.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"One
Way Heartbeats","ArtistNumber":"4","TrackTime":"187","Composer":"Bill
Bobs","Lyricist":"Michael
McEachern","FileLocation":"public/OneWayHeartbeats.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Parallel
Me","ArtistNumber":"3","TrackTime":"192","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"private/ParallelMe.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"1"},{"Title":"Poisoned
Oxygen","ArtistNumber":"3","TrackTime":"177","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"public/PoisonedOxygen.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Xmas
Prison Blues","ArtistNumber":"1","TrackTime":"192","Composer":"Steve
Perry","Lyricist":"Steve
Perry","FileLocation":"private/XmasPrisonBlues.wma","rated":"0","scores":"[0,0,0,0,0]","free":"1"}]}
Any ideas on how to hide it or remove it from coming up?
Thanks
This is the Database.php:
<?php
$Hostserver = "localhost";
$databUser = "ee2800";
$databPass = "secret";
$databDatabase = "ee2800";
$database = new mysqli ($Hostserver, $databUser, $databPass, $databDatabase);
if ($database) {
mysqli_select_db($database, "ee2800");
//echo ("Successfully connected to database!");
} else {
die ("<strong>Error:</strong> Failed to connect to the database.");
}
$var = array();
$sql = "SELECT * FROM songs";
$result = mysqli_query($database, $sql);
while ($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":' . json_encode($var) . '}';
?>
Using jQuery 1.10.2
The songlist element is found here
<?php
// The system queries the database to obtain a result set containing no more than 10 artists //
if ($result = $database->query( "SELECT * FROM `artist` ORDER BY `artist`.`ArtistNumber` ASC LIMIT 10")) {
while ($row = $result->fetch_row()) {
echo "<div id='artist{$row[2]}'>";
echo "<p>Artist: {$row[0]} {$row[1]}</p>";
echo '<p><div id= songlist> </div> </p>';
//div tag 'songlist' adds all data from json and pastes into this div id //
// echo '<p>Songs</p>';
//onlick function echo'd anchor tag//
echo "</div>";
// Songs dont display onclick however retrieved data using jSON can't seem to target where to put the information //
}
}
$database->close();
?>
And basically whenever I run these files, I get that long string I stated at the beginning as a response in my browser everytime.
Well your PHP appears to be returning a valid json string, but it is not being coverted automatically to a json object so that it can be processed by javascript as an object.
You could try forcing the parse to a json object like this
$.getJSON(url, function (data) {
data = $.parseJSON(data);
$.each(data.users, function (i, user) {

Rewrite code from javascript to PHP

I have code in javascript:
if (imageData[imageCount].comments.data != null)
{
text = 'Comments Data:<br />';
imageData[imageCount].comments.data.forEach(function(comment){
text += comment.from.username + ': ' + comment.text + '<br />';
});
}
Which imageData[imageCount] refers to $data in PHP.
i've trying to rewrite self in PHP but it doesn't worked.
foreach ($contents->data as $data) {
if ($data->comments->data != null)
{
foreach($data->comments->data as $comment)
{
$text = comment->from->username + ': ' + comment->text + '<br />';
});
}
I'm sure to have problem with the code structure. It returns Invalid argument supplied for foreach()
-- Edit --
I've successed to convert the snippet to PHP. But i faced a new problem since i'm trying to create XML File from API (in this case Instagram API).
Look at productName and productPrice attribute from product section:
http://pastebin.com/ubGGyp9b
Value productName="Sushi Homemade " and productPrice="50.000 " is just for productID="002". But why the value also filled to next productID >= 002.
Is there mistake from this code:
<products>
<category categoryName="Instagram">
<?php
foreach ($contents->data as $data) {
foreach($data->comments->data as $comment){
if(preg_match('/#title/', $comment->text)){
$komen = preg_replace('/#title/', '', $comment->text);
break;
} else { $komen = 'No Title'; }
}
foreach($data->comments->data as $comment){
if(preg_match('/#price/', $comment->text)){
$harga = preg_replace('/#price/', '', $comment->text);
break;
} else { $harga = '0'; }
}
echo '<product productName="'. $komen .'" productID="' . $data->id . '" thumbPath="' . $data->images->thumbnail->url . '" productPrice="'. $harga .'">
<details>
<![CDATA[
<img src="' . $data->images->low_resolution->url . '" width="100%"/>
' . $data->caption->text . '
]]>
</details>
</product>
You forgot an $ in the last line and some brackets were not correctly set. To concat strings in PHP use "." instead of "+"
foreach ($contents->data as $data) {
if ($data->comments->data != null) {
foreach ($data->comments->data as $comment) {
$text = $comment->from->username . ': ' . $comment->text . '<br />';
}
}
}

Categories