JQuery Update Options From Json Return - javascript

So I have this HTML form:
<select name="finder[4]" id="finder-2--4" class="pffield pf-make">
<option value="0">Please Select...</option>
<option value="52505">Alfa Romeo</option>
<option value="52506">Audi</option>
<option value="52499">BMW</option>
<option value="52501">Ford</option>
</select>
I have this jQuery
<script type="text/javascript">
jQuery("document").ready(function(){
//console.log('on load');
jQuery(".js-ajax-php-json").submit(function(){
//console.log('post');
var data = {
"action": "test"
};
data = jQuery(this).serialize() + "&" + jQuery.param(data);
jQuery.ajax({
type: "POST",
dataType: "json",
url: "/reglookup.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
console.log(data['make']);
//$(".pf-make option:selected").text("Ford");
//$(".pf-make option:contains(Ford)").attr('selected', true);
//$(".pf-make option[text=" + data["make"] +"]").attr("selected","selected");
$(".pf-make").val('52499');
alert("Form submitted successfully.\nReturned json: " + data["make"]);
}
});
return false;
});
});
</script>
I get the following return from the json post
Object {make: "Ford", model: "Focus", year: "2010", engine: 2.5, fuel: "Petrol"}
So the post and call back work fine as these get logged in the console, and I need to be able to take the called back make data["make"] and update the selected option in the select form.
You can see I have tried a number of different options, even hand typing "Ford" into the code, but I always seem to get the following error back in the console:
(index):221 Uncaught TypeError: Cannot read property 'val' of null
For the life of me I cant get this working at the moment.

get the option value using contains, then set the select:-
var ford = $('.pf-make option:contains("Ford")').val();
$('.pf-make').val(ford);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="finder[4]" id="finder-2--4" class="pffield pf-make">
<option value="0">Please Select...</option>
<option value="52505">Alfa Romeo</option>
<option value="52506">Audi</option>
<option value="52499">BMW</option>
<option value="52501">Ford</option>
</select>

A simple solution is to iterate over the options to find the matching text, then access its value.
var $select = jQuery('.pf-make');
var value = 0;
$select.find('option').each(function(){
if(jQuery(this).text() == data.make){
value = jQuery(this).val();
return false;
}
});
$select.val(value);

Instead of $ use jQuery, and also use Instead of data["make"] to data.make

see this updated code. Please take note that it uses ID rather than class name to make it more specific
<script type="text/javascript">
jQuery("document").ready(function(){
//console.log('on load');
jQuery(".js-ajax-php-json").submit(function(){
//console.log('post');
var data = {
"action": "test"
};
data = jQuery(this).serialize() + "&" + jQuery.param(data);
jQuery.ajax({
type: "POST",
dataType: "json",
url: "/reglookup.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
jQuery("#finder-2--4").val(data.make);
}
});
return false;
});
});
</script>

Related

How can I load a list of object into select tag with Ajax through API Controller?

I have a list of options inside a 'select' tag. For whichever option is selected, an 'onchange' function will be activated which carries on the value of that option. A function which activated will use Ajax to call to a controller to get a list of data that I can store into my others 'select' tag. How can I achieve this?
My HTML:
<select id="category-select" onchange="GetEmployee()">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
My JS:
function GetEmployee() {
var MaNguoiDung = 120;
var MaThuMuc = document.getElementById("category-select").value;
$('#employeeDisplay').change(function () {
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien?MaNguoiDung=" + MaNguoiDung + "&MaThuMuc=" + MaThuMuc,
success: function () {
alert('Get Success');
}
});
});
}
The alert was only to test if my ajax can run or not. Apparently, it can't. Also, I need to know how to stored query data into the second 'select'. Like after the URL attribute, I don't know what to write next after that. Sorry but I'm completely new in Ajax. Some referencing and tutorial online mostly shown how to load ajax into the table. There might be more but table is the only thing I can find so I'm very in need of a way to store it into select.
Edit: This is the response data I receive from my Controller
Sample JSON
You have several problems with the code shown.
The <select> you have the onchange in is not the same one you target to get value inside the function.
You are creating a new change event inside the function called by onchange. That new jQuery change() won't fire until next time you edit the <select>
You are manually creating the url query string but also providing a data object. Internally jQuery takes that object and will add it to the query string you manually created, effectively duplicating the parameters
So, lets get rid of the onchange , give the <select> an id and fix the query string in the ajax. Also you want an error handler to help troubleshooting
As for how to handle the response will need to see a sample of it first
HTML
<select id="category-select">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
JS
$(function () {
$('#category-select').change(function () {
var category = this.value;
// I don't know which variable is which in `data`
var MaNguoiDung = 120;// is this category ???
var MaThuMuc = null // confused where this comes from because other select is empty
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien",
success: function (response) {
// ^^ missing argument needed to receive the data
console.log(response)// log it to console for now
alert('Get Success');
},
error: function(xhr, status, message){
console.log('Status: ', status, ', Message: ', message)
}
});
});
});

JQuery chosen plugin - Sending the user typed input to an Ajax call

I am trying to populate the drop down using Chosen plugin for multiple select.
I have added the fiddle
http://jsfiddle.net/san1234/ymnj12xk/
My intention is to populate the "options" tag in the "select" tag, basing on JSON data obtained by sending user typed letter via the Ajax call.
For this I need to know, how to make an ajax call onkeyup i.e. if the user typed "Am", i want to send that input to an Ajax call and get the JSON response, something like ["America","Amsterdam"]
I'm new to this and I cant figure out a way to extract the user typed input in the 'select' box to actually send it as request in an Ajax call.
I have tried doing this but 'autocomplete' method in the JS file doesn't work
How do i do this? kindly help!
JS file
$(".chosen-select").chosen();
$(".chosen-select-deselect").chosen({
allow_single_deselect: true
});
$('.chosen-choices input').autocomplete({
source: function(request, response) {
$.ajax({
url: "/someURL/" + request.term + "/",
dataType: "json",
beforeSend: function() {
$('ul.chosen-results').empty();
},
success: function(data) {
alert("Success!");
response($.map(data, function(item) {
$('ul.chosen-results').append('<li class="active-result">' + item.name + '</li>');
}));
}
});
}
});
<link href="http://harvesthq.github.io/chosen/chosen.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<select class="chosen chosen-select" multiple="" data-placeholder="Choose a Country" style="width:200px">
<option value="America">America</option>
<option value="Amsterdam">Amsterdam</option>
<option value="Australia">Australia</option>
<option value="Dallas">Dallas</option>
<option value="GHI">hij</option>
</select>
I dont know if you are using PHP in your back end or any other program language but here's my solution using php and javascript :
First your javaScript:
//initialization of chosen select
$(".chosen-select").chosen({
search_contains: true // an option to search between words
});
$(".chosen-select-deselect").chosen({
allow_single_deselect: true
});
//ajax function to search a new value to the dropdown list
function _ajaxSearch (param){
return $.ajax({
url: "request.php",
type: "POST",
dataType: "json",
data: {param:param}
})
}
//key event to call our ajax call
$(".chosen-choices input").on('keyup',function(){
var param = $('.chosen-choices input').val();// get the pressed key
_ajaxSearch(param)
.done(function(response){
var exists; // variable that returns a true if the value already exists in our dropdown list
$.each(response,function(index, el) { //loop to check if the value exists inside the list
$('#mySelect option').each(function(){
if (this.value == el.key) {
exists = true;
}
});
if (!exists) {// if the value does not exists, added it to the list
$("#mySelect").append("<option value="+el.key+">"+el.value+"</option>");
var ChosenInputValue = $('.chosen-choices input').val();//get the current value of the search
$("#mySelect").trigger("chosen:updated");//update the list
$('.chosen-choices input').val(ChosenInputValue);//since the update method reset the input fill the input with the value already typed
}
});
})
})
your php file:
if (isset($_POST["param"])) {// check is the param is set
$param = $_POST["param"]; // get the value of the param
$array = array('JKL' => 'jkl' , 'MNO'=>'mno', 'PQR'=>'pqr','STU'=>'stu','VWX'=>'vwx','YZ'=>'yz' );//array of values
$matches = array();//array of matches
foreach($array as $key=>$value){//loop to check the values
//check for match.
if(strpos($value, $param) !== false){
//add to matches array.
$matches[]= array ("key"=> $key,"value"=>$value);
}
}
//send the response using json format
echo json_encode($matches);
}
Hope it helps

in ajax data is comming but data not displaying in field

<script>
function get_customer() {
$("#customer").html('');
$("#customer").html('<option value="0">SELECT CUSTOMER</option>');
$.ajax({
url: '<?=base_url();?>Drop_downs/get_customer/',
type: 'POST',
dataType: 'html',
success: function(response) {
$("#customer").append(response);
console.log(response);
}
});
}</script>
and this is my html
<select name="customer" id="customer" class="form-control select2" required tabindex="1" onFocus="get_customer()">
<option>SELECT CUSTOMER</option>
</select>
Response is not an HTML node, so you can not append it. Use $('#customer').html() instead.
It seems you are receiving option tag (html code) in response, so you've to use $('#customer').html(response);
<script>
function get_customer() {
$("#customer").html('');
$("#customer").html('<option value="0">SELECT CUSTOMER</option>');
$.ajax({
url: '<?=base_url();?>Drop_downs/get_customer/',
type: 'POST',
dataType: 'json',
success: function(response) {
$("#customer").html(response);
console.log(response);
}
});
}</script>
Without knowing what 'response' is we won't be able to provide specific help. Nonetheless, the following should help you:
Adding hard-coded values
To add a new option to it, with the text "Text 1" displaying in the drop down box, and the value "Value1" being what would be submitted from the form, do this:
var select = document.getElementById("customer");
select.options[select.options.length] = new Option('Text 1', 'Value1');
Adding options from an object
If you had an object that you wanted to use the property name as the value for the options, and the property value as the text to display, you could do this:
var myobject = {
ValueA : 'Text A',
ValueB : 'Text B',
ValueC : 'Text C'
};
var select = document.getElementById("customer");
for(index in myobject) {
select.options[select.options.length] = new Option(myobject[index], index);
}
Note that while the above is an object, it's often referred to incorrectly as an associative array, even though technically it is not. It can be accessed as an object e.g. myobject.ValueA, or like an array would be e.g. myobject['ValueA']
Now, this code is generic and should hopefully help you achieve what you require. But, if you could update your question with further detail such as what the response is returning, I would be able to be of more help and provide a solution for you.
Possible JQuery solution:
If you are using JQuery then it becomes even simpler:
$('#customer').append($('<option>', {
value: 1,
text: 'My option'
}));
If you're adding options from a collection of items, you can do the following:
var myOptions = {
val1 : 'Blue',
val2 : 'Orange'
};
var mySelect = $('#customer');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
You please provide the console.log(response);
Since I do not know your response I assumed that you have taken customer name in 'customer_name'.Please try the below code.
<script>
function get_customer() {
$("#customer").html('');
$("#customer").html('<option value="0">SELECT CUSTOMER</option>');
$.ajax({
url: '<?=base_url();?>Drop_downs/get_customer/',
type: 'POST',
dataType: 'json',
success: function(response) {
var i = 0;
while (i < data.length)
{
$('<option>').text(data[i].customer_name).appendTo('#customer');
i++;
}
}
});
}</script>

Selection OnChange change PHP Variable

Hello StackOverflow People.
I need you help. I have this code:
<select name="type" onChange="idk?" class="form-control">
<option value="H">Week 51</option>
<option value="V">Week 52</option>
</select>
And if an user change the week i want to change the file get content :s
$Week = "";
echo file_get_contents('http://rooster.farelcollege.nl/'.$Week.'/c/c00050.htm');
Thanks!
greetings from the Netherlands =)
you can send Ajax request to the "file_get_contents" url.
This is what I am using and it works fine :)
<select name="type" class="form-control">
<option value="H">Week 51</option>
<option value="V">Week 52</option>
</select>
$(document).ready(function() {
$( ".form-control" ).change(function() {
$.ajax({
data: {
// You are not sending any post variables right? Then leave this empty :-) otherwise use it as array 'var1': 'value', 'var2': 'value2' ...
},
url: 'http://rooster.farelcollege.nl/'+$(this).val()+'/c/c00050.htm',
method: 'POST',
success: function(msg) {
alert(msg); // Optional, show text that was given by URL, can be removed
}
});
});
});
jquery.com/jquery.ajax

Json submiting same data until refresh

I have a problem with submiting my "form" with json. Its not form in traditional way, i will post a code now:
$('#select').on('change', function() {
document.getElementById("info").setAttribute("data-info", this.value);
})
$('#info').on('click', function() {
var id = $(this).data('info');
add(info);
});
function add(info) {
$.ajax({
type: 'get',
cache: false,
contentType: content_type,
beforeSend: function(xhr) {xhr.overrideMimeType(content_type);},
data: {'action': 'info_add', 'info': info },
url: sitepath + 'info/all',
success: function() { update(); }
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="select">
<option value="1">data1</option>
<option value="2">data2</option>
<option value="3">data3</option>
<option value="4">data4</option>
</select>
<div id="info">Button</div>
So as you see, when select is changed it adds "data-info" attribute to div. And when div is pressed it send data-info to php script. And the problem is that it always send the same value. But after refresh it sends fine only once and than again the same value as first. Its hard to explain but here is example:lets say that i change select to "data2" and press on div. It sends "2". But then when i change it to "data3", and press on div, it still sends "2", not "3". There is no cache set or something. Sorry for bad english and thanks in advance :)
Use jQuery for setting if you are also going to be reading it with jQuery
Change
document.getElementById("info").setAttribute("data-info", this.value);
to
$"#info").data("info", this.value);
Still wondering why you are using data atrrbutes when you are not just reading the value on demand.
add($('#select').val());
You are using confusing code, you can achieve the same using:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="select">
<option value="1">data1</option>
<option value="2">data2</option>
<option value="3">data3</option>
<option value="4">data4</option>
</select>
<div id="info">Button</div>
<script>
$('.product__cart, .stock-product__cart').on('click', function() {
var info = $('#select').val();
$.ajax({
type: 'get',
cache: false,
data: {'action': 'info_add', 'info': info },
url: sitepath + 'info/all',
success: function() { update(); }
});
});
</script>

Categories