How to load checked checkbox in ajax edit modal? - javascript

can you help me how to load checked checkbox in edit modal? I'm using checkbox to input multiple roles in my system. Everything was fine but I have problem in my edit modal. The checkbox was blank and not checked.
this is my ajax edit function:
function edit_function(task, id) {
$('#editModal').modal();
$.ajax({
method: 'POST',
url: '<?php echo base_url() . 'user/edit/' ?>' + id,
dataType: 'json',
success: function(x) {
if (resp.length > 0) {
for (var i = 0; i < resp.length; i++) {
id= x[i]['id'];
$("#editModalForm input[name=email]").val(x[i]['email']);
$('#editModalForm input[name=role_id]').prop('checked', true);
}
}
}
});
}
this is my checkbox in html form
<?php foreach ($roles as $row) : ?>
<div class="form-check-inline">
<label class="form-check-label">
<input type="checkbox" name="role_id[]" id="role_id[]"
value="<?php echo $row->role_id; ?>"><?php echo $row->role_id; ?>
</label>
</div>
<?php endforeach; ?>
this is my json result:
[{"id":288,"role_id":["2","3"],"email":"me#gmail.com"}]

function edit_function(task, id) {
$('#editModal').modal();
$.ajax({
method: 'POST',
url: '<?php echo base_url() . 'user/edit/' ?>' + id,
dataType: 'json',
success: function(x) {
if (resp.length > 0) {
for (var i = 0; i < resp.length; i++) {
id= x[i]['id'];
$("#editModalForm input[name=email]").val(x[i]['email']);
for (var r = 0; r < x[i]['role_id'].length; r++) {
var role=x[i]['role_id'][r];
$('#role_id_'+role).prop('checked', true);
}
}
}
}
});
}
<?php foreach ($roles as $row) : ?>
<div class="form-check-inline">
<label class="form-check-label">
<input type="checkbox" name="role_id[]" id="role_id_<?php echo $row->role_id ?" />
value="<?php echo $row->role_id; ?>"><?php echo $row->role_id; ?>
</label>
</div>
<?php endforeach; ?>

Related

How to call Ajax in tpl(template) file OpenCart version 2.3

How to call ajax call in tpl template opencart version 2.3
I have api controller with data and that data I need to post in template(tpl) file. Template file is tpl extension , I need open script tag but I don't know how do it in tpl file and how to target endpoint with function? I provide my code. In controller I have api folder and file reifenmontage and function get_marka_data()...How I target this data in tpl file? I know tpl is only for show data but I must do on this way :/
public function get_marka_data() {
$query = $this->db->query("
SELECT mo.marka
FROM " . DB_PREFIX . "model mo
GROUP BY mo.marka
")->rows;
$data = array_map(function($row){
return array('value'=>$row['marka'],'label'=>$row['marka']);
}, $query);
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($data));
var_dump($data);
}
<script type="text/javascript"><!--
$('#button-getdata').on('click', function() {
$.ajax({
url: 'index.php?route=extension/module/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select, #reifenmontage-input input'),
dataType: 'json',
beforeSend: function() {
$('#reifenmontage-input').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" /> <?php echo $text_wait; ?></div>');
},
success: function(json) {
$('.success, .warning, .attention, information, .error').remove();
if (json['success']) {
html = "<!-- Retrieved data -->\n";
for (i in json['success']) {
var element = json['success'][i];
console.log(element);
html += "\t<tr><td>" + element['label'] + "</td><td align=\"right\">" + element['value'] + "</td></tr>\n";
}
$('#reifenmontage-output').html(html);
}
}
});
});
//--></script>
<?php if($heading_title) { ?>
<h2><?php echo $heading_title; ?></h2>
<?php } ?>
<h2><?php echo $description_title; ?></h2>
<?php echo $description; ?>
<div id="reifenmontage-input" class="reifenmontage-input">
<form id="reifenmontage-input" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label" for="datum"><?php echo $entry_begin_period; ?></label>
<div class="input-group date">
<input type="text" name="datum" value="<?php echo $current_day . '-' . $current_month . '-' . $current_year; ?>" data-date-format="DD-MM-YYYY" id="datum" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-calendar"></i></button>
</span></div>
</div>
<div class="form-group">
<label class="control-label" for="entry-cyclus"><?php echo $entry_cyclus; ?></label>
<select name="cyclus" id="entry-cyclus" class="form-control">
<option value=""><?php echo $text_select; ?></option>
<?php
for ($i=20;$i<43;$i++) {
if ($i == 28) {
?>
<option value="<?php echo $i; ?>" selected="selected"><?php echo $i; ?></option>
<?php
} else {
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
?>
</select>
</div>
<div class="buttons">
<div class="pull-right">
<input type="button" value="<?php echo $button_create; ?>" id="button-getdata" class="btn btn-default" />
</div>
</div>
</fieldset>
</form>
</div>
<div id="reifenmontage-output"></div>
And for de php-function, change te last part into:
$json = array();
if ($data) {
$json['succes'] = $data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
Example for form, output id and script to retrieve data from controller in extension/module
In controller/api/reifenmontage.php:
<?php
class ControllerApiReifenmontage extends Controller {
private $error = array();
public function get_marka_data() {
$json = array();
if (isset($this->request->post['marka'])) {
$marka_data_query = $this->db->query("SELECT mo.model FROM " . DB_PREFIX . "model mo WHERE mo.marka='" . $this->request->post['marka'] . "'");
$marka_data = $marka_data_query->rows;
$json['succes'] = $marka_data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
Form with script:
<div id="reifenmontage-input" class="reifenmontage-input">
<form id="reifenmontage-input" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group required">
<label class="col-sm-4 control-label" for="input-marka">Marka</label>
<div class="input-group col-sm-8">
<select name="marka" id="input-marka" class="form-control">
<option value="0">Select ...</option>
<option value="AJP">AJP</option>
<option value="APOLO">APOLO</option>
<option value="APRILIA">APRILIA</option>
<!-- All stored marka's -->
</select>
</div>
</div>
</fieldset>
<div class="buttons">
<div class="pull-right">
<button type="button" class="btn btn-primary" id="button-getdata" data-loading-text="Loading ...">Get Data</button>
</div>
</div>
</form>
</div>
<div class="col-xs-12 col-sm-3" style="margin-right:30px;">
<div class="row">
<select class="form-control" id="result">
</select>
</div>
</div>
<script type="text/javascript"><!--
$('#button-getdata').on('click', function() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select'),
dataType: 'json',
beforeSend: function() {
$('.success, .warning, .attention, information, .error').remove();
$('#result').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" />Please wait ...</div>');
},
success: function(json) {
if (json['error']) {
$('#result').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" />' + json['error'] + '</div>');
}
if (json['success']) {
for (i in json['success']) {
var element = json['success'][i];
//console.log(element);
html = "\t<option value=\""+ element['model'] + "\">" + element['model'] + "</option>\n";
$('#result').append(html);
}
}
}
});
});
//--></script>
New controller/api/reifenmontage.php
<?php
class ControllerApiReifenmontage extends Controller {
private $error = array();
public function get_markas() {
$json = array();
$markas_query = $this->db->query("SELECT marka FROM " . DB_PREFIX . "model GROUP BY marka");
$markas_data = $markas_query->rows;
if ($markas_data) {
$json['success'] = $markas_data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function get_marka_data() {
$json = array();
if (isset($this->request->post['marka'])) {
$marka_data_query = $this->db->query("SELECT mo.model FROM " . DB_PREFIX . "model mo WHERE mo.marka='" . $this->request->post['marka'] . "'");
$marka_data = $marka_data_query->rows;
$json['success'] = $marka_data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
And new script on template / form:
<script type="text/javascript"><!--
function getMarkaData() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select'),
dataType: 'json',
beforeSend: function() {
$('.success, .warning, .attention, information, .error').remove();
},
success: function(json) {
if (json['error']) {
$('#result').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" />' + json['error'] + '</div>');
}
if (json['success']) {
$('#result2').html('');
for (i in json['success']) {
var element = json['success'][i];
//console.log(element);
html = "\t<option value=\""+ element['model'] + "\">" + element['model'] + "</option>\n";
$('#result2').append(html);
}
}
}
});
}
function getMarkas() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_markas',
dataType: 'json',
type: 'post',
beforeSend: function() {
$('.success, .warning, .attention, information, .error').remove();
},
success: function(json) {
if (json['success']) {
for (i in json['success']) {
var element = json['success'][i];
html = "\t<option value=\""+ element['marka'] + "\">" + element['marka'] + "</option>\n";
$('#result').append(html);
}
getMarkaData();
}
}
});
}
//--></script>
<script type="text/javascript">
let selectItem = document.getElementById('pneu');
let additionalRow = document.getElementById('additionalRow');
function checkSelected() {
if (selectItem.selectedIndex == "1") {
additionalRow.style.display = 'none';
} else {
additionalRow.style.display = 'flex';
getMarkas();
}
}
$('#result').on('change', function() {
getMarkaData();
});
if ($('#pneu').val() != '1') {
getMarkas();
}
</script>

Ajax code not working in safari and firefox

Ajax code for language switching from database is not working in safari and Firefox, but its perfectly working on chrome and edge. Safari doesn't respond to ajax call but in firefox it only work after a lot of attempts to change language.
My code is
<?php
session_start();
if($_SESSION)
{
$bid=$_SESSION['latest'];
}
else
{
$bid=1;
}
?>
<select name="sources" id="language_id" onclick="" onchange="location.reload();langchange();">
<?php
$language = mysqli_query($link, "select * from language_reference");
while ($lang = mysqli_fetch_array($language)) {
?>
<option value="<?php echo $lang['lang_id']; ?>"
<?php
if($lang['lang_id']==$bid)
{
echo 'selected="selected"' ;
}
?>
><?php echo $lang['lang_name']; ?>
</option>
<?php } ?>
</select>
<div class="row" >
<?php
$result = mysqli_query($link, "SELECT * FROM category AS c INNER JOIN category_language AS cl ON c.id=cl.category_id where parent_id IS NULL && lang_id='1' ");
$var = 0;
while ($row = mysqli_fetch_array($result))
{
?>
<div class="col-md-3 col-sm-3 col-xs-6 hvr-shrink" style="position: relative; margin-top: 50px;">
<a href="#" style="text-decoration: none;">
<div>
<img src="admin/uploads/category/<?php echo $row['cat_home_image']; ?>" class="img-responsive center-block" width="50px" />
<p class="category-caption" style="padding-top: 20px; text-align: center;" id="cat_desc<?php echo $var; ?>"></p>
</div>
</a>
</div>
<?php
$var++;
}
?>
ajax script
<script>
function langchange() {
var language_id = $('#language_id').val();
$.ajax({
type: "POST",
url: "ajax_lang_change.php",
data: "id=" + language_id,
success: function (value)
{
var data = value.split("|_,_|");
for (var i = 0; i < data.length; i++) {
$("#cat_desc" + i).html(data[i]);
}
}
});
$.ajax({
type: "POST",
url: "ajax_get_session.php",
data: "bid=" + language_id,
success: function (value) {
var data = value;
}
});
}
$(window).ready(function () {
langchange()
});
</script>
php script to get data from db
ajax_lang_change.php
<?php
include 'db_connect.php';
$id = $_POST['id'];
$result = mysqli_query($link, "SELECT * FROM category AS c INNER JOIN category_language AS cl ON c.id=cl.category_id where parent_id IS NULL && lang_id='$id'");
while($row=mysqli_fetch_array($result))
{
echo $row['category_description']."|_,_|";
}
?>
ajax_get_session.php
<?php
include 'db_connect.php';
session_start();
$bid = $_POST['bid'];
$_SESSION['latest']=$bid;
if(isset($_SESSION['latest']))
{
echo 'success';
}
else
{
echo 'failed';
}
?>
is there anyway to solve this problem? should I have to write ajax script for various browsers?

JS code working in chrome and IE, not in safari and firefox

I have the below js code that is working in chrome and IE but not safari and firefox. In both cases, the beforeSend: function works, but the success function does not work. Is this a problem with the CSS or am I missing something in the javascript?
---JS----
$("#updateBidButton").click(function () {
var bid_amount = document.getElementById("auction_bid_input").value;
var item_id = "<?php echo $this->item['id']?>";
var current_bid = "<?php echo $this->item['current_bid']?>";
var url_view = "<?php echo $this->item['url_view']?>";
$.ajax({
type: 'post',
url: "?module=items&controller=index&action=submitBid",
dataType: "text",
data: 'bid_amount=' + bid_amount + '&item_id=' + item_id + '&current_bid=' + current_bid + '&url_view=' + url_view,
beforeSend: function () {
$('.auction_box').animate({
'backgroundColor': '#ffdead'
}, 400);
},
success: function (result) {
if (result == 'ok') {
$.get(window.location.href, function (data) {
$('.auction_box').animate({
'backgroundColor': '#A3D1A3'
}, 400);
});
} else {
alert(result);
$('.auction_box').animate({
'backgroundColor': '#FFBFBF'
}, 400);
}
}
});
});
Here is the html:
<form action="" method="post">
<div id="<?php echo $this->item['id']; ?>">
<div class="auction_bid_box">
<label for="auction_bid_input">
<!-- Starting bid EXISTS -->
<?php if ($this->item['bid_count'] >= '1') { ?>
You have until <?php echo $this->data['item']['auction_start']; ?> to update the current bid.
<!-- Starting bid is MISSING-->
<?php } else { ?>
You have until <?php echo $this->data['item']['auction_start']; ?> to enter a starting bid.
<?php } ?>
</label>
<span class="auction_bid_container">
<input id="auction_bid_input" type="text" maxlength="12"
class="middle nmr event-clear-focus"
name="bid_amount" value="Enter Bid"/>
<input id="updateBidButton" type="submit"
value="<?php echo $this->translate('Update'); ?>"
class="button grey-button num-items-button"/>
</span>
</div>
</div>
</form>

How to get foreach input value in javascript and pass it to ajax data?

This is my Form
<form method="post" id="BargainForm">
<input type="hidden" name="pro_id" class="pro_id" id="pro_id" value="<?php echo $pro_id; ?>">
<input type="hidden" name="customer_id" class="customer_id" id="customer_id" value="<?php echo $customer_id; ?>">
<input type="text" name="bargain_qty" class="bargain_qty" id="bargain_qty" placeholder="Qty" required/></br></br>
<?php if($productType = 'Configurable'): ?>
<?php foreach($attributes as $attribute): ?>
<input type="text" name="<?php echo strtolower($attribute['store_label']); ?>"
class="<?php echo strtolower($attribute['store_label']); ?>"
id="<?php echo strtolower($attribute['store_label']); ?>"
placeholder="<?php echo $attribute['store_label'] ?>"></br></br>
<?php endforeach; ?>
<?php else: ?>
<?php endif; ?>
<input type="text" name="bargain_price" class="bargain_price" id="bargain_price" placeholder="Total Price" required/></br></br>
<input type="submit" name="bargain_btn" class="bargain_btn">
</form>
Here is my javascript code
<script type="text/javascript">
$(function () {
$('.bargain_btn').click(function(e) {
var qty = $( "#bargain_qty" ).val();
var price = $( "#bargain_price" ).val();
var pro_id = $( "#pro_id" ).val();
var customer_id = $( "#customer_id" ).val();
var att_lable = $( "#<?php echo strtolower($attribute['store_label']); ?>" ).val();
alert(att_lable);
e.preventDefault();
$.ajax({
url: "<?php echo Mage::getUrl('bargain/Ajax/index'); ?>",
type: "POST",
data: {qty,price,pro_id,customer_id},
success: function(data) {
if(data.success) {
}
}
});
});
});
In form i am using foreach. If i have 2 data so it will display 2 input tags, i just don't know how to save values of that 2 input and pass it to data: {qty,price,pro_id,customer_id},
Thank you in advance!
Provide a common class to all textbox that are generated using loop like:
foreach(...)
{
echo '<input class="myTxt" value="" id="" />';
}
Jquery:
var arr = [];
$('.myTxt').each(function(){
arr.push($(this).val());
});
pass this array i.e. arr to ajax call in data{} section using serialize or on an index.
Replace
data: {qty,price,pro_id,customer_id},
By
data: "qty="+qty+"&price="+price+"&pro_id="+pro_id+"&customer_id="+customer_id+"&att_lable="+att_lable,
Do not use:
data: { qty, price, pro_id, customer_id },
Instead use:
data: $("#BargainForm").serialize(),
It will work only if your $attribute['store_label'] name is unique.

How to grab the required value input on click?

For example, there is such a JS-code:
function openAlbum() {
$("#tracks").html('Some text...');
var uid = $("#uid").val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
}); }
And this html/php-code that is displayed in a cycle:
for ($i = 0; $i < count($searchAlbum); $i++) {
echo '<div id="cover"><form action=""><input type="hidden" id="uid" value="'.str_replace('https://example.com/', '', $searchAlbum[$i]->href).'"/><img src="'.$searchAlbum[$i]->images[1]->url.'"/><br><br><span>'.$searchAlbum[$i]->name.'</span><input type="submit" style="position: absolute;;left: -99999px;" /></form></div>';
}
Problem: currently by clicking grabs only the first input value on the page with id="uid".
How do I put a JS var uid value from the div, which clicked a link?
P.S. Sorry for my bad english.
I'm going to change the way you kinda do this a bit...
<?php
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div class="cover">
<form action="">
<input type="hidden" class="uid" value="<?php echo str_replace('https://example.com/', '', $searchAlbum[$i]->href); ?>"/>
<img src="<?php echo $searchAlbum[$i]->images[1]->url; ?>"/>
<span><?php echo $searchAlbum[$i]->name; ?></span>
<input type="submit" style="position: absolute;left: -99999px;" />
</form>
</div>';
<?php
}
?>
Script:
$(document).on('click','.cover img',openAlbum);
function openAlbum() {
$("#tracks").html('Some text...'); var uid = $(this).parent().find('.uid').val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
//$("#results").empty();
//$("#results").append(html);
$("#results").html(html);
}
});
}
This should cover everything. I switched all ids to classes and changed how you execute your jQuery.
Thank you all for your help!
As a result, I will be able to solve the problem.
JS-code:
function openAlbum(uid)
{
$("#results").html('Some text...');
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
});
}
HTML-code:
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div id="cover"><a href="#" onclick='openAlbum("<? echo $searchAlbum[$i]->id; ?>");'><img src="<? echo $searchAlbum[$i]->images[1]->url; ?>"/></a><br><br><span><? echo $searchAlbum[$i]->name; ?></span></div>
<?
}
Since id in HTML must be unique, it is taking only the first element's value. Make the ids unique or use class attribute as Cayce K has answered.

Categories