I have an ajax call that is returning me the data to be populated in a drop down list. Now, I need to be able to select a value which is returned and set the value of the drop down in the same function if possible. But by using $("#idOfDropDown").val(data), it is not getting set i.e While I am submitting the data, in the database all the options that were returned and populated are getting submitted and not the selected option. So, How do I set the selected value only?
Here's my AJAX function:
$.ajax({
type: "POST",
dataType: 'json',
url: "/Controller/Action",
data: {
param: param,
},
success: function(data) {
if (data.Response == "Unsuccessful") {
console.log("Unsuccessful");
} else if (data.Response == "Successful" || data.Response == "ConditionallySuccessful") {
for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
$("#Exterior_Color").append($("<option></option>").val(data.ExteriorColor.Data[i]).html(data.ExteriorColor.Data[i]));
console.log(data.ExteriorColor.Data[i]);
}
var html = '<ul>'
for (var i = 0; i < data.Options.length; i++) {
html += '<li>' + data.Options[i] + '</li>';
}
html += '</ul>'
$("#twoColumnOptions").append(html);
$("#twoColumnOptions").data(html);
$("#Options").val(data.Options);
$("#Exterior_Color").val(data.ExteriorColor.Data).change(); //Value to be changed
if (data.ExteriorColor.isInstalled == true)
$("#Exterior_Color").attr("disabled", true);
}
},
error: function(result) {
console.log("Error while fetching data");
}
});
Try to trigger the change you made using .trigger('change') like:
$("#Options").val(data.Options).trigger('change');
//Or
$("#Options").val(data.Options).change();
I implemented something similar in my solution and my code is like this, you need to set the value like this:
success: function (response) {
var array = response;
if (array != '') {
for (i in array) {
$("#district").append("<option value='"+
array[i].Id + "'>" + array[i].DistrictName + "</option>");
}
}
},
Related
I have some javascript that takes user input, queries an endpoint with that input via ajax, and returns a field from the results as an appended <option> to a datalist. This is working properly and I see exactly what I need in the options list.
The next portion I've worked on is that when I click the option, I want other fields related to it in the object to populate the value of a form input. I've got this all structured but when I click an item it says result is not defined
in this line:
$("#groupName").val(result[$(foundOption).attr('srindex')]._source.name);
So my options are correct, and when I click an option it reflects the clicked option in the console. The issue is that I'm not passing the result into my else if correctly, apparently.
The heirarchy of my _source is correct but I just don't know how I need to change my .val argument in order to pull the right value.
Any ideas?
$('#productInput').on('input', function () {
let _this = $(this);
let foundOption;
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ((foundOption = $('#returnedProducts').find(optSelector)).length) {
console.log(optSelector); //this prints the option[value] of the clicked value as it should
$("#groupName").val(result[$(foundOption).attr('srindex')]._source.name);
$("#groupNum").val(result[$(foundOption).attr('srindex')]._source.code);
} else {
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
search_result:searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
console.log(response);
console.log(searchResult);
$("#returnedProducts").empty();
let result = response.hits.hits;
console.log(result);
for(let i = 0; i < result.length; i++) {
$("#returnedProducts").append("<option srindex=" + [i] + " value=" + result[i]._source.name + ">" + result[i]._source.name + "</option>");
}
}
});
}
});
Update:
my object looks like this
hits
hits
_source
name
code
fiddle http://jsfiddle.net/qhbt569o/8/
Working example.
You've just to change _source by source inside the loop like :
for (let i = 0; i < result.length; i++) {
$("#returnedProducts").append("<option srindex=" + [i] + " value=" + result[i].source.name + ">" + result[i].source.name + "</option>");
}
I have a GET ajax call as follows :
var changeUrl = "changePriority?newValue=" + targetValue + "&justification=" + justification
if (dataInfo == "row") {
changeUrl += "&id=" + id
}
changeUrl += "&executedConfigId=" + executedConfigId + "&currUser=" + currentUser + "&productName=" + productName + "&eventName=" + eventName + "&alertDetails=" + JSON.stringify(alertArray);
//if the selected signal is not null then we show the product names
$.ajax({
url: changeUrl,
type: "GET",
success: function (data) {
for (var index = 0; index < checkedRowList.length; index++) {
var row = checkedRowList[index]
signal.list_utils.change_priority(row, targetValue);
}
$('#change-priority-modal').modal('hide');
if (applicationName == "Signal Management") {
signal.list_utils.set_value(parent_row, 'dueIn', id, signal.list_utils.get_due_in, applicationName);
$(parentField).html(targetValue);
}
location.reload();
},
error: function (exception) {
console.log(exception);
}
});
The value of changeUrl as I get in my browser's developer console is :
http://localhost:8080/signal/singleCaseAlert/changePriority?newValue=Medium&justification=test%20justification%20first.&id=6816&executedConfigId=6704&currUser=15&productName=Wonder%20Product&eventName=1.Pyrexia&alertDetails=[{%22alertId%22:%226816%22,%22event%22:%221.Pyrexia%22,%22currentUser%22:%2215%22}]
But I get a 400 bad request status and a http header parse error in the backend. Can someone help me resolve this?
On your JSON.stringify(alertArray) you'll need to also encodeURI();
encodeURI(JSON.stringify(alertArray));
A better solution would be send your JSON in the body of a POST request if thats feasible within your design
Cancel all Ajax Request if search field is empty and if the search character length is < 3
$('#search-box').keyup(function() { // bind the search data
var input = $('.search-input').val();
if (input.length >= 3) {
$.getJSON({ // get JSON data
url: 'example.com?keyword=' + input,
success: function(data) {
// do processing.
var output = "<ul class='search-lists'>"; //output search data list
$.each(data, function(key, val) {
output += '<li><a>' + val.term + '</a></li>';
});
output += '</ul>';
$('.search-results').html(output);
}
}); // JSON request
}
}); // data bind
From your code it's OK to use but what happens when second request finish after first request? for example first send "ab" and send "abc" later, the second result will be replace with the first. You can use abort() to abort the first connection before start the second one.
if(ajaxRequest){ajaxRequest.abort();}
ajaxRequest = $.ajax({
url: '...',
success: function(){
/* ... */
}
});
Use keyup event of search inputbox instead of section element.
$('#search').keyup(function() { // bind the search data
var input = $('.search-input').val();
if (input.length >= 3) {
$.getJSON({ // get JSON data
url: 'example.com?keyword=' + input,
success: function(data) {
// do processing.
var output = "<ul class='search-lists'>"; //output search data list
$.each(data, function(key, val) {
output += '<li><a>' + val.term + '</a></li>';
});
output += '</ul>';
$('.search-results').html(output);
}
}); // JSON request
}
}); // data bind
I am trying to load data into table using JQuery and AJAX but when I click on the button data is not retrieved. I have done coding as shown below:
var globalgrid;
Here I am going to call json url and try to display it in the table.
function loadgrid() {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://instatalk.in/sip/GetApprovedUsersList?page=1&limit=10',
success: function(griddata) {
globalgrid = griddata.lines;
// remove all data - but the headers!
$("#gridtable").find("tr:gt(0)").remove();
if (globalgrid.length === 0) {
$('#errormsg').html('Sorry, <strong>no</strong> rows returned!');
return;
}
for (var i = 0; i < globalgrid.length; i++) {
var line = globalgrid[i];
// insert after last row!
$('#gridtable > tbody:last').append('<tr><td>' + line.Id + '</td><td>' + line.AccountId + '</td><td>' + line.Name + '</td><td>' + line.IsFranchiseUser + '</td></tr>');
}
},
error: function(data, errorText) {
$("#errormsg").html(errorText).show();
}
});
}
I am getting the table heading only. When I click on the button I want data to be retrieved from the json data. I don't know where I am going wrong. Please do help.
This is my json file:
{"results":[{"Id":17,"AccountId":"5737329468","Name":"Martin (Nigeria)","IsFranchiseUser":false},{"Id"
:16,"AccountId":"3644824444","Name":"Deep Patel","IsFranchiseUser":false},{"Id":15,"AccountId":"4692068407"
,"Name":"Jacob (kiribati)","IsFranchiseUser":false},{"Id":14,"AccountId":"4650982975","Name":"sebin John
(spain)","IsFranchiseUser":false},{"Id":13,"AccountId":"2855375107","Name":"Jassi want(new jersey)"
,"IsFranchiseUser":false},{"Id":12,"AccountId":"6242007588","Name":"Moussa","IsFranchiseUser":false}
,{"Id":11,"AccountId":"3075258818","Name":"srkrbm (saudi arab)","IsFranchiseUser":true},{"Id":10,"AccountId"
:"3615509810","Name":"Om Saini","IsFranchiseUser":false},{"Id":9,"AccountId":"9251133143","Name":"swati
mohandas","IsFranchiseUser":false},{"Id":8,"AccountId":"8143395019","Name":"babu Kuppu","IsFranchiseUser"
:false}],"totalAccounts":16}
This line: globalgrid = griddata.lines;
According to your Json data format, you should use griddata.results.
I can't call an arrays passed from the php json encode. I would concatenate 2 select state-contry-city. How can I do this??
This is the code:
I have 2 selects. I send the first value to an action:
php action into my controller:
public function regioniProvinceComuniAction(){
$response = $this->getResponse();
$request = $this->getRequest();
if ($request-> isPost()){
$post_data = $request->getPost();
$regione = (int)$post_data['regione'];
$province = (int)$post_data['province'];
}
if(isset($regione)){
$prov = $this->getProvincia($regione);
}
if(isset($province)){
$com = $this->getComuni($province);
}
$response->setContent(\Zend\Json\Json::encode(array('prov' => $prov, 'com' => $com)));
return $response;
}
This is my js file:
$("select#Regione").change(function () {
var regione = $("select#Regione option:selected").attr('value');
$.ajax({
type: 'POST',
url: '/zf-tutorial/public/regioni-province-comuni',
datatype: 'json',
data: { regione: regione },
success: function (data) {
alert (data);
}
});
});
An example of the alert function is like this:
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
I tried to populate my second select via data.post like this, but the values are "undefined":
success: function (data) {
$('select#Provincia option').each(function(){$(this).remove()});
for(var i=0; i<data.length; i++){
$("select#Provincia").append('<option value="' + data[i].prov.id + '">' + data[i].prov.nome + '</option>');
}
i tried to do
for (var i = 0; i < data.prov.length; i++) {
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
if i set manually the var data, works fine, but with the response data doesn't work. i tried to do:
var prov = data.prov;
$("div#id").html(prov);
but it doesn't work. works only like this:
$("div#id").html(data);
and the output is the same
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
You need to loop through the items in data.prov. Change your for loop to this:
for (var i=0; i<data.prov.length; i++){
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
jsFiddle Demo
EDIT
Solution found in comments: Can you try to change datatype in your $.ajax() call to dataType. I'm not sure if the case is important. Sounds like data is a string and not an object