How to set response data to javascript code - javascript

How to set response data
$.ajax({
type : "POST",
async: true,
url : "<?php echo base_url(); ?>" + "Graphs/get_graphs",
dataType: 'json',
data :{hotel_name_realm:$("#hotel_names").val()},
success : function(res){
obj = JSON.parse(res);
console.log(obj.upload);
console.log(obj.download);
series: [{
name: 'Download',
data: [
(obj.Download) // I need set obj.download data here
]
}
}
Here is my console.log(obj) image

i do like this,
$.ajax({
method: "POST",
url: "chat/searchuser",
data: {name: $(this).val(), length: "10"}
})
.done(function (data) {
$('#scroll_user').val('10');
var html = '';
$.each(JSON.parse(data).data, function (k, v) {
html += '<div class="row sideBar-body getUserdata userchat" data-username="' + v.fname + '" data-id="<?php echo $key; ?>" onclick="showDiv()" id="' + v.fname + '"><div class="col-sm-3 col-xs-3 sideBar-avatar"><div class="avatar-icon"><img src="<?= base_url('assets/user2.jpg') ?>"></div></div><div class="col-sm-9 col-xs-9 sideBar-main"><div class="row"><div class="col-sm-12 col-xs-12 sideBar-name" data-username="' + v.fname + '"><span class="name-meta">' + v.fname + ' ' + v.lname + '(' + v.username + ')</span></div></div></div></div>'
$('#usersindiv').html(html);
});
}).fail(function () {
alert("failed");
});

You are doing it right, you just missed the right square bracket. JS is also case sensitive, obj.Download is not obj.download
$.ajax({
type : "POST",
async: true,
url : "<?php echo base_url(); ?>" + "Graphs/get_graphs",
dataType: 'json',
data :{hotel_name_realm:$("#hotel_names").val()},
success : function(res){
obj = JSON.parse(res);
console.log(obj.upload);
console.log(obj.download);
series: [{
name: 'Download',
data: [
(obj.Download) // shouldn' it be obj.download? (small D)
]
] // you are missing the right bracket here
}
}

Related

Json not work in asp.net mvc

I wanna to use this json to my sites shopping cart .it works well in visual studio 2017 but in visual studio 2013 it does not work. please help me to solve it.
function AddtoCart() {
$.ajax({
url: '/Home/AddToCart',
type: 'POST',
dataType: 'Json',
data: {
ProductID: #Model.product.id,
count: My_Count.value
},
error: function(err) {
alert(err.status);
}
}).done(function(data) {
$('#Total_Cost').text(data.Total_Price)
var Text = "";
$.each(data.lst_ShoppingCart, function(index, val) {
Text += "<tr><td class='col-sm-8 col-md-6' ><span id='Product_Name'>" + val.Product_Name + "</span></td ><td class='col-sm-1 col-md-1' style='text-align: center'><input type='text' class='form-control' id='exampleInputEmail1' value='" + val.Count + "'></td><td class='col-sm-1 col-md-1 text-center'><span id='Product_Cost'>" + val.Single_Price + "</span></td><td class='col-sm-1 col-md-1 text-center'><span id='Total_ProCost'>" + val.Price + "</span></td><td class='col-sm-1 col-md-1'><button type='button' onclick='RemoveCart(" + val.ID + ")' class='btn btn-danger'>Remove</button></td></tr>";
})
$('#Pro_Cart').html(Text);
});
}
also I know that this part of code not working:
url: '/Home/AddToCart',
type: 'POST',
dataType: 'Json',
data: {
ProductID: #Model.product.id,
count: My_Count.value
},

Add to cart button when a product has a required option in OpenCart 2.3.0.2

How would one go about adding required options to an ajax call after clicking an add to cart button?
Currently the code in the common.js is:
var cart = {
'add': function(product_id, quantity) {
$.ajax({
url: 'index1.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
success: function(json) {
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$.notify({
message: json['success'],
target: '_blank'
},{
// settings
element: 'body',
position: null,
type: "info",
allow_dismiss: true,
newest_on_top: false,
placement: {
from: "top",
align: "right"
},
offset: 20,
spacing: 10,
z_index: 2031,
delay: 2000,
timer: 1000,
url_target: '_blank',
mouse_over: null,
animate: {
enter: 'animated fadeInDown',
exit: 'animated fadeOutUp'
},
onShow: null,
onShown: null,
onClose: null,
onClosed: null,
icon_type: 'class',
template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-success" role="alert">' +
'<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
'<span data-notify="message"><i class="fa fa-check-circle"></i> {2}</span>' +
'' +
'</div>'
});
$('#cart_block #cart_content').load('index1.php?route=common/cart/info #cart_content_ajax');
$('#cart_block #total_price_ajax').load('index1.php?route=common/cart/info #total_price');
$('#cart_block #cart_count_ajax').load('index1.php?route=common/cart/info #cart-total');
$('#cart-total').html(json['total']);
}
}
});
},
'update': function(key, quantity) {
$.ajax({
url: 'index1.php?route=checkout/cart/edit',
type: 'post',
data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
success: function(json) {
if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
location = 'index.php?route=checkout/cart';
} else {
$('#cart_block #cart_content').load('index1.php?route=common/cart/info #cart_content_ajax');
$('#cart_block #total_price_ajax').load('index1.php?route=common/cart/info #total_price');
$('#cart_block #cart_count_ajax').load('index1.php?route=common/cart/info #cart-total');
}
}
});
},
'remove': function(key) {
$.ajax({
url: 'index1.php?route=checkout/cart/remove',
type: 'post',
data: 'key=' + key,
dataType: 'json',
success: function(json) {
if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
location = 'index1.php?route=checkout/cart';
} else {
$('#cart_block #cart_content').load('index1.php?route=common/cart/info #cart_content_ajax');
$('#cart_block #total_price_ajax').load('index1.php?route=common/cart/info #total_price');
$('#cart_block #cart_count_ajax').load('index1.php?route=common/cart/info #cart-total');
$('#cart-total').html(json['total']);
}
}
});
}
}
Obviously, options are not added in this call to add it to the cart. I did managed to show the options, you can see an example here:
https://www.amsterdamvapes.com/eleaf-istick-pico-set
There you will see 7 related products, all with 1 required option.
The related options are getting saved in a $product['options]' array and they're showed by this code in the product.tpl file;
<?php if ($product['options']) { ?>
<div class="options">
<?php foreach ($product['options'] as $related_option) { ?>
<?php if ($related_option['type'] == 'select') { ?>
<div class="form-group<?php echo ($related_option['required'] ? ' required' : ''); ?>">
<label class="control-label" for="input-option<?php echo $related_option['product_option_id']; ?>"><?php echo $related_option['name']; ?></label>
<select name="option[<?php echo $related_option['product_option_id']; ?>]" id="input-option<?php echo $related_option['product_option_id']; ?>" class="form-control">
<option value=""><?php echo $text_select; ?></option>
<?php foreach ($related_option['product_option_value'] as $related_option_value) { ?>
<option value="<?php echo $related_option_value['product_option_value_id']; ?>"><?php echo $related_option_value['name']; ?>
</option>
<?php } ?>
</select>
</div>
<?php } ?>
<?php } ?>
</div>
<?php } ?>
In the product.tpl file the add to cart button gets this code;
<li><a onclick="cart.add('<?php echo $product['product_id']; ?>','1','<?php echo $related_option_value['name']; ?>');" class="btn-secondary btn-buy"><i class="fa fa-shopping-cart"></i><?php echo $button_cart; ?></a></li>
I can understand I would have to add all the possible options to that onclick function where the product_id is added. And then add code to the common.js to get the options from that onclick event but I have no clue on how to do that.
Can anyone steer me in the right direction to add those option values to the ajax call?
Sincerely hope anyone can help out! Cheers, David

Need to be able to get the return string from javascript method in yii2

I am working on Yii2 and having a problem with returning the content of the javascript method to be sent when using the Html::a -hyperlink
The javascipt is in order to obtain the selected value of the checkboxes and it is outputting correctly.
<script>
function getNewPermissions() {
var permissions = '';
var rows = $(document).find('.permission');
$.each(rows, function (key, value) {
if($(value).find('input').prop('checked') == true)
permissions += value.id+'$&/';
})
permissions = permissions.substring(0, permissions.lastIndexOf("$&/"));
return permissions;
}
</script>
echo Html::a(Yii::t('app', 'Edit'), ['permissions/edit' ,'id'=> $name], [
'class' => 'btn btn-primary',
'onclick' =>'js:getNewPermissions()',
'data-method' => 'post',
'data' => [
'params' => ['newPerms'=>'js:getNewPermissions()','_csrf' => Yii::$app->request->csrfToken],
],
])
In the yii1 the value was read correctly from the params.
Just cant find any source to help get js in the params directly and the onclick does work.
in my project use another way
<a style="float:left;" class="btn btn-success" onclick="myFunction(this)"
type="<?php echo $value->id; ?>">
</a>
and use js function in end of layout
<script>
function updateSession(e)
{
var csrfToken = $('meta[name="csrf-token"]').attr("content");
var pid = e.getAttribute('type');
var key = e.getAttribute('title');
var pqty = $("#id_" + key).val()
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/updatecard') ?>',
type: 'Post',
data: {
productid: pid,
key: key,
pqty: pqty,
_csrf: csrfToken
},
success: function (data) {
alert(data);
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcard') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#collapseCart").empty();
$("#collapseCart").append(data);
}
});
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcardpage') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#get_card2").empty();
$("#get_card2").append(data);
}
});
}
});
}
</script>

load ajax array data into select2 dropdown format

i have a problem with filling dropdown data from ajax script.
here's my controller:
public function ajax_get_kota($idProv='')
{
$kota = $this->data['namaKota'] = $this->registrasi_model->get_nama_kota($idProv);
echo json_encode($kota);
}
here's my model:
public function get_nama_kota($idProv='')
{
$query = $this->db->query('SELECT id_kab, nama FROM kabupaten WHERE id_prov = '.$idProv.' ORDER BY nama ASC');
return $dropdowns = $query->result();
}
and view:
<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">
<?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
<div class="col-sm-3">
<?php
$atribut_kota = 'class="form-control dropKota"';
echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
set_validation_icon('Kota');
?>
</div>
<?php if (form_error('Kota')) : ?>
<div class="col-sm-9 col-sm-offset-3">
<?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
</div>
<?php endif ?>
<script>
$(document).ready(function () {
$(".dropProv").on("change", function(){
var idProv = $(this).val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
var kota = [];
$.ajax({
url: baseUrl,
data: kota,
success: function(datas){
$(".dropKota").select2({
placeholder: "Pilih Kota",
data: datas
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
});
});
</script>
</div>
what i'm trying to do here is how to pass this data that im getting from ajax:
[{"id_kab":"5103","nama":"KAB. BADUNG"},{"id_kab":"5106","nama":"KAB. BANGLI"},{"id_kab":"5108","nama":"KAB. BULELENG"},{"id_kab":"5104","nama":"KAB. GIANYAR"},{"id_kab":"5101","nama":"KAB. JEMBRANA"},{"id_kab":"5107","nama":"KAB. KARANGASEM"},{"id_kab":"5105","nama":"KAB. KLUNGKUNG"},{"id_kab":"5102","nama":"KAB. TABANAN"},{"id_kab":"5171","nama":"KOTA DENPASAR"}]
into the dropdown dropKota. those data is dynamically generated when another dropdown value is changed.
current result:
select2 requires a specific format so it can be properly displayed in dropdown
var data = [{ id: 0, text: 'enhancement' } //something like this
how do i do this?
U have to do like this :
$.ajax({
url: url,
type: "POST",
async: false,
data: {id: id},
success: function(data) {
var data_array = $.parseJSON(data);
$.each(data_array.emp, function(key, value) {
$('#Your_drop_down_id').append($('<option>', {
value: key,
text: value,
}));
});
}
});
U have to parse the data(JSON to array) and then use $.each for looping all values.
Try this:
success: function(datas){
var data = JSON.parse(datas);
var options = '<select name="dd_name"><option>Select</option>';
for(i=0; i<data.length; i++)
{
options += '<option value="'+ data.col_name +'">'+ data.col_id +'</option>';
}
options += '</select>';
$('#div_id').html(options); // where #div_id is the id of a div in which this drop down is required.
},
Change $.ajax call as below
$.ajax({
url: baseUrl,
data: kota,
dataType: "JSON",
success: function(datas){
var s= document.getElementById('<Element Id>');
s.eampty();
$.each(datas, function(index, el) {
s.options[index]= new Option(index, el);
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
dataType: "JSON", will respond output of ajax call in json format.
Replace <Element Id> with element id to which you want to add data.
Full Source
<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">
<?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
<div class="col-sm-3">
<?php
$atribut_kota = 'class="form-control dropKota"';
echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
set_validation_icon('Kota');
?>
</div>
<?php if (form_error('Kota')) : ?>
<div class="col-sm-9 col-sm-offset-3">
<?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
</div>
<?php endif ?>
<script>
$(document).ready(function () {
$(".dropKota").select2({
placeholder: "Pilih Kota"
});
$(".dropProv").on("change", function(){
var idProv = $(this).val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
var kota = [];
$.ajax({
url: baseUrl,
data: kota,
dataType: "JSON",
success: function(datas){
var s= document.getElementById('<Element Id>');
s.eampty();
$.each(datas, function(index, el) {
s.options[index]= new Option(index, el);
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
});
});
</script>
</div>
Finally, i found the solution after asking here and there, so here's the solution:
JS and select2 script:
<script>
$(document).ready(function () {
$(".dropProv").on("change", function(){
var idProv = $(this).val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
var kota = [];
$.ajax({
url: baseUrl,
dataType: 'json',
success: function(datas){
//since select2 need a specific format u need to do this
var kota = $.map(datas, function (obj) {
obj.id = obj.id || obj.id_kab; // replace id_kab with your identifier
obj.text = obj.text || obj.nama // replace nama with your identifier
return obj;
});
$(".dropKota").select2({ //change dropKota into your element
placeholder: "Pilih Kota",
data: kota
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
});
});
</script>

dynamically create radiobuttons and labels

Ok what I want to achieve is that it creates this automatically for each record I got back from my webservice.
<label for="ZAALID_1">Zaal 1</label>
<input id="ZAALID_1" type="radio" name="RESERVATIE.ZAALID" value="1" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,'1'),CHECKED,)~" />
I am calling this webservice with an ajax call. There is nothing wrong with this call. I tested it with printing down the values.
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
if (zalen.length > 0) {
$.each(zalen, function (index, zaal) {
createRadioElement(zaal.zaalId);
createLabel(zaal.zaalNaam,zaal.zaalId);
});
}
}
});
So I think there is an mistake in CreateRadioElement and createLabel.
Here are these two functions.
function createRadioElement( id ) {
var radioInput;
try {
var radioHtml = '<input id="ZAALID_' + id + '" type="radio" name="RESERVATION.ZAALID" value="' + id + '" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ';
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', 'RESERVATION.ZAALID');
}
return radioInput;
}
function createLabel(name,id) {
var label;
var labelHTML = '<label for="ZAALID_' + id + '">'+ name +'</label>';
label = document.createElement(labelHTML);
return label;
}
Now another thing that I want to do is that is places these radiobuttons inside the div with id=zaalField
here is the HTML of that div
<div id=ZaalField data-role="fieldcontain" class="knoppen_boven">
<LABEL for=zaal>Zalen ter beschikking: </LABEL>
//Here should go the radiobuttons and labels.
</div>
Can anybody help ?
Kind regards
---EDIT---
function getZalen()
{
var dateB = $("#DATUM_BEGIN").val();
var dateE = $("#DATUM_EINDE").val();
console.log(dateB);
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
alert(JSON.stringify(zalen));
if (zalen.length > 0) {
$.each(zalen, function (i, entity) {
$('ZaalField ').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
}
});
}
$(document).ready(function () {
var data = { "d": [{ "__type": "Reservatie", "zaalId": 2, "opmerking": null, "zaalNaam": "Zaal 2" }, { "__type": "Reservatie", "zaalId": 3, "opmerking": null, "zaalNaam": "Zaal 3"}] };
// $.ajax({
// url: "/SelligentMobile/Webservice/WebService.asmx/getReservaties",
// type: "POST", contentType: "application/json; charset=utf-8",
// dataType: "json", data: { 'DATUM_BEGIN': '2012-05-09 10:10:36', 'DATUM_EINDE': '2012-05-09 12:10:45' },
// success: function (data) {
if (data.d.length > 0) {
$.each(data.d, function (i, entity) {
$('body').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
// }
// });
});
function createLabel(id, name){
var name = "Zaal 2";
var label = document.createElement("label");
label.setAttribute("for","RANDOM"+id);
label.innerHTML = name;
return label;
}
var label = createLabel(2, "Zaal 2");
$(document.body).append(label); //add it to the body, or to whatever else you want to add it to.
This code works for me, while the code you have written doesn't.

Categories