how to get JSON value through Dropdown - javascript

We have JSON like this
"[{\"UserID\":1,\"Name\":\"demo\"},{\"UserID\":4,\"Name\":\"ekova\"},{\"UserID\":2,\"Name\":\"Himansu-it\"},{\"UserID\":3,\"Name\":\"Himansu-it Services\"}]"
We need Show UserName to drop-down list and if I Select Name on dropdown We need to get UserID.Like if We Select ekvoa We need get UserID 4
We show userName drop Down like this
function selectitems(){
var getCustomerIDs = jQuery.parseJSON( customerID );
$(getCustomerIDs).each(function() {
console.log(this.UserID);
console.log(this.Name);
$('#date').append('<option>'+this.Name+'</option>');
});
}
We need to post UserID like this
$.ajax({
url:'http://www.himansuit.com/DemoSalesApp/MyService.svc/GetCurrentGeoLocationsByUserID/'+userID,
dataType: 'jsonp',
type:'get',
cache:false,
timeout: 10000,
error: function(x, t, m) {
if(t==="timeout") {
debugger;
$('#alertmessage').empty();
alert("NO Internet Connection");
// withOutNetConnection();
} else {
//alert(t);
}},
success:function(data) {
debugger;
GetAllElementsjson=data;
elements();
}
});
Please guide me .

Set the value of the option to the UserID like so:
$('#date').append('<option value="'+this.UserID+'">'+this.Name+'</option>');
Then when #date changes, you can grab the value ($('#date').val()), which should be the userid.

Add user id as a value in option.get selected option on change event of select box(#date')
$('#date').append('<option value='+this.UserID+'>'+this.Name+'</option>');
call ajax on change event of (#date).
$('#date').on('change',function(){
var userID = $(this).val();
$.ajax({
url:'http://www.himansuit.com/DemoSalesApp/MyService.svc/GetCurrentGeoLocationsByUserID/'+userID,
dataType: 'jsonp',
type:'get',
cache:false,
timeout: 10000,
error: function(x, t, m) {
if(t==="timeout") {
debugger;
$('#alertmessage').empty();
alert("NO Internet Connection");
// withOutNetConnection();
} else {
//alert(t);
}},
success:function(data) {
debugger;
GetAllElementsjson=data;
elements();
}
});
})

Related

select2 returning position of items, not ID of items

I'm using a select2 to allow the user to select multiple options. Everything is working fine, except for one frustrating issue.
The first time I click the save button to save the items, it works. But then on subsequent calls, the ID of the items are replaced with the position of the items. For for example, if I have IDs 3, 6 and 10 selected, the first Save will work and 3,6,10 are passed to the controller.
But then if I reload the view and click save, the numbers 0,1,2 are passed in (ie, their relative positions in the select).
Here is the code:
Firstly, the HTML:
<select id="selectGroup" class="form-control" multiple="true">
On $(document).ready:
// Load Groups
$("#selectGroup").select2({ placeholder: 'Select' });
$.ajax({
url: ROOT_URL + "Group/GroupList",
type: "GET",
success: function (data) {
let dropdown = $('#selectGroup');
dropdown.empty();
dropdown.append($('<option></option>').attr('value', 0).text("(Select)"));
$.each(JSON.parse(data), function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.GroupID).text(entry.GroupName));
})
},
error: function (passParams) {
Notify(passParams, "Unexpected Error Loading Groups", "error");
}
});
And finally the js for the save (called from a button which passes in the loanID):
function LoanGroupSave(loanID) {
var grpIDs = '';
[].forEach.call(document.querySelectorAll('#selectGroup :checked'), function (elm) {
grpIDs += elm.value + ',';
})
var editURL = location.protocol + '//' + location.host + "/Loan/LoanGroupSave";
//alert(editURL);
var obj = { "LoanID": loanID, "GroupIDs": grpIDs };
alert(JSON.stringify(obj));
$.ajax({
type: "POST",
url: editURL,
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (response) {
if (response.success) {
Notify("Group(s) information has been saved", "Saved", "success", false, "toast-top-right", 5000);
}
else {
OpenPopupGeneral("Error(s)", response.message);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
OpenPopupGeneral("Unexpected Error(s)", "Error = " + errorThrown);
});
}
Posting for people who make the same mistake.
Problem was in my load - I needed to add the GroupID as the key, not the row number which was in the key parameter value:
success: function (data) {
$.each(JSON.parse(data), function (key, entry) {
var $newOption = $("<option selected='selected'></option>").val(entry.GroupID).text(entry.GroupName);
$("#selectGroup").append($newOption).trigger('change');
}

Storing JSON result from ajax request to a javascript variable for Easyautocomplete

I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});

Updating quantity of multiple field from selections using jQuery

I'm updating quantities in an order form with predefined "packs" from the database. Updating the from fields from the "packs" dropdown in the first function works, but the second function that uses those values and multiplies them by the value in a text input does not update the fields.
Also, when looking at the console output, it looks like the ajax request from the first and second function both run when the quantity input is changed.
jQuery(document).ready(function($) {
$("[id^=packs]").on('change', function() {
var packname = this.value;
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1);
$('#'+lineno+'-size1').attr("value", obj.packdetail[0].size1);
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
//multiply packs
$("[id^=packs_qty]").on('change', function() {
var pack_qty = this.value;
var packname = $(this).attr("data-name");
console.log("qty:"+pack_qty);
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1*pack_qty);
$('#'+lineno+'-size1').attr("value", (obj.packdetail[0].size1*pack_qty));
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15*pack_qty);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2*pack_qty);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25*pack_qty);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3*pack_qty);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35*pack_qty);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4*pack_qty);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45*pack_qty);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5*pack_qty);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55*pack_qty);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6*pack_qty);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65*pack_qty);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7*pack_qty);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75*pack_qty);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8*pack_qty);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85*pack_qty);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9*pack_qty);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95*pack_qty);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10*pack_qty);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105*pack_qty);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11*pack_qty);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115*pack_qty);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12*pack_qty);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125*pack_qty);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
});
can you please convert obj.packdetail[0].size1 and pack_qty in to Number and try,
for this you can use
parseInt(obj.packdetail[0].size1) * parseInt(pack_qty);
Please have a try..

SyntaxError:JSON.parse:unexpected character at line 1 column 1 of the JSON data

I've been looking all over for the solution but I cannot find anything that works,I keep getting the following error,I have a submit event that will call the function SUValidation with the data thats being
submitted through a text box in php form,I have tried putting contentType: "application/json",//note the contentType defintion looking at other posts but nothing helped..can anyone provide guidance on how to debug this error or at the best provide a solution
Error:-
SyntaxError:JSON.parse:unexpected character at line 1 column 1 of the JSON data
RESPONSE OF SUVALID.py
Just outputs the content of the python script
Hi,
submit event:-
$("#su_validation").submit(function(event) {
console.log("su_validation.submit");
event.preventDefault();
//SUValidation('#su_validation', '#su_validation_table', '#gerrits_su_validation', showDialog, "#su_validation_dialog");
$("#SUValidation_su_validation_table").empty();
var data = { 'product_lines' : [], 'gerrits' : [], 'contacts' : []};
//find all pl's that are checked
data['product_lines'] = ($("#product_line_su_validation").val()).split(",");
data['gerrits'] = ($("#gerrits_su_validation").val()).split(",");
data['contacts'] = ($("#contacts_su_validation").val()).split(",");
console.log(data);
SUValidation(data, '#SUValidation_su_validation_table', '#gerrits_su_validation', "su_validation_form");
});
Function call:-
function SUValidation(data, table_name, gerrit_form, caller) {
console.log("su_validation_form");
console.log(data);
//console.log($(form_name).find('input, select, textarea').serialize());
su_validation_return = null;
//if maintained, we care if they are in ODS
//if not maintained, we don't really mind if they aren't in ODS database
var maintained = null;
console.log("start when");
$.when(
$.ajax({
dataType: "json",
type: "POST",
url: "scripts/suvalid.py",
timeout: 180000,
data: JSON.stringify(data),
success : function(response){
su_validation_return = [];
console.log("python");
console.log(response);
....
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("error");
//alert(xhr.status);
alert(thrownError);
}
})
).then(function() {
console.log("THEN");
var gerrits = data['gerrits'];
console.log(su_validation_return);
var valid_gerrits = true;
..................

How do I get the right $.ajax data type

could you please help with this. I have the following javascript:
$('form').click(function (e)
{
if (e.target.getAttribute('id') === 'SubmitAddLevel')
{
var parent = $('#' + e.target.getAttribute('attr')),
var Data = [];
parent.find('.input').children().each(function (i, e)
{
Data.push(e.getAttribute('id') + ":" + e.value);
console.log(Data);
});
$.ajax({
type: "POST",
url: 'AjaxControls.aspx/CreateUserLevel',
//data: Data, //.join(','),
dataType: "text",
contentType: "application/json; charset=utf-8",
//error: function (er) { alert(er); },
success: function (response)
{
if (response.d === "true")
{
$("#ErrorDivAddLevel").html('Level created successfully!').fadeIn('slow');
}
else
{
$("#SuccessDivAddLevel").html('Level creation failed!').fadeIn('slow');
}
},
});
}
The result of 'Data' I got on the console is :["LevelNameAddLevel:Admin", "PriviledgeIDAddLevels:|1|2|3|4|5|6|7|"]. How do I convert this to what ajax will pass to my web menthod?
Here is the web method
<WebMethod(EnableSession:=True)>
Public Shared Function CreateUserLevel(userLevel As String, userPriviledges As String) As String
return "true"
end function
I think your Data should look something more like this:
[{"LevelNameAddLevel":"Admin"}, {"PriviledgeIDAddLevels":"|1|2|3|4|5|6|7|"}]
So you have key / value pairs inside of an array. In the request, you should then be able to fetch the data via the keys in the request.
But I'm not quite sure what this is supposed to mean : "|1|2|3|4|5|6|7|"

Categories

Resources