Im pretty new with javascript, so im not sure how I would do this. But basically I want to add a for loop in the ajax data: call, instead of list each item manually.
jQuery(document).ready(function()
{
var $payment = {
card: 'ajax-card',
month: 'ajax-month',
year: 'ajax-year',
cvv: 'ajax-cvv',
zip: 'ajax-zip',
phone: 'ajax-phone'
};
jQuery.each( $payment, function($key, $val)
{
jQuery('.'+$val).attr({ id: $val });
});
jQuery('#pay-bill form input[type=submit]').click(function()
{
jQuery.ajax(
{
type: "POST",
url: "<?php echo get_bloginfo('template_directory').'/cnotethegr8/functions/braintree.php'; ?>",
dataType: "json",
data:
{
card: jQuery('#'+$card+' input').val(),
month: jQuery('#'+$month+' input').val(),
year: jQuery('#'+$year+' input').val(),
cvv: jQuery('#'+$cvv+' input').val(),
zip: jQuery('#'+$zip+' input').val(),
phone: jQuery('#'+$phone+' input').val()
},
success: function(data)
{
if (data)
{
alert(data.msg);
}
}
});
return false;
});
});
Replace the code after var $payment = {...} by the code below. I have adjusted the loop where you're assigning IDs to the elements.
var data = {};
jQuery.each( $payment, function($key, $val)
{
var $element = jQuery('.'+$val);
$element.attr({ id: $val }); //<-- This line can be removed, depending on the
// circumstances
data[$key] = jQuery('input', $element).val();
});
jQuery('#pay-bill form input[type=submit]').click(function(){
jQuery.ajax(
{
type: "POST",
url: "<?php echo get_bloginfo('template_directory').'/cnotethegr8/functions/braintree.php'; ?>",
dataType: "json",
data: data,
success: function(data)
{
if (data)
{
alert(data.msg);
}
}
});
return false;
});
If the values you want to pass in are in a form you can use $('#myForm').serialize()
Make a variable before calling $.ajax, and make a loop to set the values.
var postData = {};
$.each($payment, function(k, v){
//postData[k] = $('#'+v+' input').val();
postData[k] = $('.'+v+' input').val();
});
$.ajax({
type: 'POST',
data: postData,
// ...
});
P.S. You don't need the loop you have (setting $('.'+$val).attr({ id: $val });), you can just do $('.'+v+' input').val(); (inside a loop).
If you want an each function that can iterate with key->value pairs, checkout underscore.js: http://documentcloud.github.com/underscore/#each
_.each({key:'value',key2:'value2'},function(value,key){
// access the key->value during each iteration
});
Related
good afternoon, have all of you, I have this problem. I am using selectr mobius1 and when I click to edit data, the "Type of Service" field does not show me the value that it should show me.
my select is initialized like this
$selecttSE = new Selectr("#tipo_SAPIE",{});
I use this onchange so that when a product is chosen the list of services changes
$("#tipo_productoE").on('change', function() {
var tipoprod = $("#tipo_productoE option:selected").val();
var select_servapi = $("#tipo_SAPIE");
$.ajax({
url: '<?= base_url('productos/select_servicios') ?>',
type: 'get',
data: {
tipoprod: tipoprod
},
beforeSend: function(){
$selecttSE.removeAll();
},
success: function(response) {
if (response.length >2 ) {
select_servapi.attr('disabled', false);
$.each(JSON.parse(response), function(i, item) {
$selecttSE.add([{
value: item.servicioapiid,
text: item.alias+' '+item.moneda+''+item.costo}])
});
let select = $("#tipo_SAPIE").parents().children('small')[0];
$(select).empty();
$(select).html('Requerido');
$(select).addClass('badge badge-soft-danger');
} else {
select_servapi.attr('disabled', true);
}
},
});
});
And my function to get the data is this
function getProducto(idproducto) {
var idproducto = idproducto;
$.ajax({
url: '<?= base_url('productos/getProducto') ?>',
type: 'GET',
data: {
idproducto: idproducto
},
success: function(response) {
console.log(response)
$selecttSE.removeAll();
$.each(JSON.parse(response), function(i, item) {
document.getElementById("tipo_productoE").value = item.tipoproductoid;
$("#tipo_productoE").trigger('change');
$selecttSE.setValue(item.servicioapiid);
});
},
error: function(errors) {
},
});
}
Thank you for taking the time to see my post have a great afternoon and much success.
i am trying to display some field data from table mysql into the select2 option but whatever i do it still shows me only one.
This is how I expected: Screenshot
Any suggestions? Thanks
in javascript file I have this code
<script type="text/javascript">
//List ajax for list product
$(".js-productList").select2({
ajax: {
url: "halaman/hal_search2ajax/productsList.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function(data){
return { results: data };
},
cache: true
},
minimumInputLength: 3,
});
</script>
my code in html
<select name='item' class=\"js-productList form-control\" required></select>
Code in productList.php
<?php
// connect to database
require('../../config/koneksi.php');
$q = $_POST['q'];
$sql = mysql_query("select id_item as id, item_name as text, item_code as code from item where item_name like '%".$q."%'");
$num = mysql_num_rows($sql);
if($num > 0){
while($data = mysql_fetch_assoc($sql)){
//I want to show the item_name and item_code
$tmp[] = $data;
}
} else $tmp = array();
echo json_encode($tmp);
?>
Something like this. Seems to be the typical parse json.
I prefer tu use $.post:
<select name='item' id="itemselect" class=\"js-productList form-control\" required></select>
var data = {
q: params.term // or the way you obtain them
}
$.post('halaman/hal_search2ajax/productsList.php', data, function(response) {
$.each(response,function(i,item){
$('#itemselect').append($('<option>', {
value: item.code,
text : item.code
}));
}
}, 'json');
with append it understand what goes into value and the text
<option value="'+value+'">'+text+'</option>
You just need to manipulate response return by ajax call using map() function
try like this
$(".js-productList").select2({
ajax: {
url: "halaman/hal_search2ajax/productsList.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function(data){
output = $.map(data, function (obj) {
obj.text = obj.text + "-" + obj.code
return obj;
});
return { results: output };
},
cache: true
},
minimumInputLength: 3,
});
Here is working example https://jsfiddle.net/6tzkLtvL/2/
I hope it will help you.
i have this drop-down dependent on the choices of the other 2 drop-downs i have debugged the java script but it has an error on my error logs that says,
Undefined index: TRANCHE
here is my controller
public function dependent_dropdown()
{
if(isset($_POST['TRANCHE']) || isset($_POST['GRADE']))
{
$data = $_POST['TRANCHE'];
$data1 = $_POST['GRADE'];
$this->output
->set_content_type("application/json")
->set_output(json_encode($this->EmployeeSalary_Model->getType($data, $data1)));
}
}
and here is my javascript
jQuery(document).ready(function(){
$("#GRADE").change(function() {
var TRANCHE = {"TRANCHE" : $('#TRANCHE').val()};
var GRADE = {"GRADE" : $('#GRADE').val()};
console.log(TRANCHE);
console.log(GRADE);
$.ajax({
type: "POST",
data: (TRANCHE, GRADE),
url: "<?php base_url(); ?>EmployeeSalary/dependent_dropdown/",
success: function(data){
var select = $('#SAL_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.ID+"'>"+option.AMOUNT+"</option>");
});
}
});
});
});
please tell me the problem and how can i debug it. thanks
You have to make an array to send both values.
var postData = [ TRANCHE , GRADE ]
$.ajax({
type: "POST",
data: JSON.stringify(postData), ////stringify is important
url: "<?php base_url(); ?>EmployeeSalary/dependent_dropdown/",
success: function(data){
var select = $('#SAL_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.ID+"'>"+option.AMOUNT+"</option>");
});
}
});
the jquery Select2(Version: 3.5.4) plugin doesn't show my initial value which I loaded on the initSelection function of the plugin. Here is my code:
$("#materialFieldTags").select2({
tags: true,
initSelection : function (element, callback) {
console.log(element);
console.log(callback);
var countryId = "3"; //Your values that somehow you parsed them
var countryText = "mater3";
var data = [];//Array
var tempJSONMat = {
materials: []
};
$.ajax({
url: "php/FormProcessing.php",
type: "post",
data: "main=" + "materialFault" + "&faultid="+ main.faultId,
dataType: 'json',
success: function(data){
data.forEach(function(column) {
//console.log(column);
tempJSONMat.materials.push({
"id" : column.material_id,
"text" : column.name
});
});
}
});
callback(tempJSONMat.materials[0]);
},
ajax: {
type: "POST",
url: 'php/FormFilling.php',
dataType: 'json',
data: function (params) {
return "main=" + "allMaterials" + "&searchterm=" + params;
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
};
})
};
},
cache: true
}
});
Can you take I look at my code? Because I can't see it!! I also have try the:
$("#materialFieldTags").select2("data",mydata);
After the initialization of the plugin, but I am getting the same result.
Finally, I found my mistake! It was define two element by the same id, by mistake! The data appeared on first one and I was looking the second one.
The var inc is incrementing using ajax below:
var inc = 100;
jQuery('.mybuttonin').click(function()
{
jQuery.ajax
({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: {
'action':'myaction',
value : inc
},
success: function(data)
{
inc = data;
alert(inc);
},
error: function(data)
{
console.log(data);
}
});
});
I want this var to put inside an input id and name:
<input id='wpjobus_resume_skills['+inc+'][1]' name='wpjobus_resume_skills['+inc+'][1]' value='100%'>
how can i do this? the above input is dynamically creating.
If your element is already created use this.
$('.input_element_class').attr(
{ id: 'wpjobus_resume_skills['+inc+'][1]', name: 'wpjobus_resume_skills['+inc+'][1]', type: 'text', value:'100%'}
);
if you want to create an element you can do something similar.
$('<input />').attr(
{ id: 'wpjobus_resume_skills['+inc+'][1]', name: 'wpjobus_resume_skills['+inc+'][1]', type: 'text', value:'100%'}
).appendTo('.parent_elemnt_class');