I am trying to make an autocomplete widget that will display item's codes returned from a database.
I have successfully made it so my database will return the appropriate JSON response.
The problem now is I don't know why the drop-down list doesn't show up.
Here's the code down below:
<input type="text" id="search" class="form-control" placeholder="">
<form action="post" action="" id="spareParts" class="spareparts">
</form>
$('#search').keyup(function(event) {
var search = $(this).val();
if($.trim(search).length){
var arr = [];
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: search},
success: function (data) {
arr = $.parseJSON( data );
console.log(arr);// CONSOLE.LOG WORKS WELL
//[Object { id="1", value="25.00", desc="Fuel pump", more...}]
// AUTOCOMPLETE DOESN'T WORK
$('#spareParts').autocomplete({
minLength:0,
source: arr
});
}
});
}
});
The autocomplete with AJAX loaded data should be configured differently. source property can be a function which accepts a callback parameter. You should feed this callback with data loaded from server.
Also you don't need to bind keyup event manually. Your code will become:
$('#search').autocomplete({
minLength: 0,
source: function(request, response) {
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: request.term}
}).done(function(data) {
response(data.map(function(el) {
return {
value: el.value,
label: el.desc
};
}))
});
}
});
Related
I'm trying to make it so that when my ajax call is returned with an object/array, I can match up the results to checkboxes so that if there is a match I auto check the boxes
Here are my checkboxes
<input type="checkbox" name='Magazine' data-md-icheck />
<input type="checkbox" name='Website' data-md-icheck />
<input type="checkbox" name='Advertisement' data-md-icheck />
Now my ajax call is successful
I get back:
0: {}
type: "Magazine"
1: {}
type: "Website"
so in my ajax success, what I would like to do is take any result in that object, whether just one or all 3, and if the type matches the 'name' of the checkbox I want to check that box.
Here is my function that makes the successful ajax call. I just can't figure out a way to loop the return that I get so that I can match up any result that comes through
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
},
});
};
So in this case, how would I modify my ajax success to check the magazine and website boxes?
Here is a pure JS and simple solution to this:-
// Assuming you get the response as an array of objects, which has a key as type
success: function (data) {
data.forEach(obj => {
let ele = document.getElementsByName(obj.type)[0];
if(ele) {
ele.checked = true;
}
});
}
This is how I would tackle it:
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
for(var i=0;i<data.length;i++){
var item = data[i].type;
var checkbox = $('input[name="'+item+'"]);
if (checkbox.length){
checkbox.prop('checked', true);
}
}
},
});
};
Assume the result is pure text exactly the same as you provided (ES6+)
let a = 'result...'
['Magazine', 'Website', 'Advertisement'].filter(item => a.indexOf(item) != -1).forEach(item => {
let inputs = document.getElementsByName(item)
if (inputs.length > 0)
inputs[0].checked = true
})
I'm trying to pass a checkbox array into an AJAX call for a search form im working on:
HTML:
<form id="searchForm">
<input type="checkbox" class="typesSearch" name="types[]" value="Fundraiser" checked /> Fundraiser<br>
<input type="checkbox" class="typesSearch" name="types[]" value="Conference" checked /> Conference<br>
</form>
JavaScript:
var types = [];
var eventTypes = document.forms['searchForm'].elements[ 'types[]' ];
for (var i=0, len=eventTypes.length; i<len; i++) {
if (eventTypes[i].checked ) {
types.push($(eventTypes[i]).val());
}
}
$.ajax({
url: "https://www.example.com/search.php",
method: "post",
data:{
eventname: eventname,
types: types
},
dataType:"text",
success:function(data)
{
$('#eventsList').html(data);
$('#eventsList').slick($opts);
}
});
PHP:
$event_types = $_POST['types'];
The types array is fine on the javascript side, its when it hits the PHP side that $_POST['types'] is read as being empty.
Why is it that $_POST['types'] is read as empty? Is there something in the AJAX call where I need to define that I'm passing in an array instead of a string?
Try to use the following at "data":
$.ajax({
url: "https://www.example.com/search.php",
method: "POST",
data:{
eventname: eventname,
types: JSON.stringify(types)
},
dataType:"text",
success:function(data)
{
$('#eventsList').html(data);
$('#eventsList').slick($opts);
}
});
With this, the types is a string and you need to parse it to array object on PHP side.
On server side, you can use the following code to get the array. The $item[0]
$event_types = $_POST['types'];
$item = (json_decode(stripslashes($event_types)));
You need to serialize your array in order to receive it in $_POST, so your ajax should look like:
$.ajax({
url: "https://www.example.com/search.php",
method: "post",
data:{
eventname: eventname,
types: JSON.stringify(types) //serializied types[]
},
dataType:"text",
success:function(data)
{
$('#eventsList').html(data);
$('#eventsList').slick($opts);
}
});
You might want to try this solution too:
JS:
data: { typesArray: types }
PHP:
$types = $_REQUEST['typesArray'];
I have seen several examples and can't seem to get the hang of passing more than one variable to mysql using jquery. Here is my situation:
I have a page with 2 cascading drop downs,( they work great using jquery to update second drop down based on the first drop down.)
when the first drop down is selected jquery updates the second drop down AND passes the customer id to a php script that creates a new record in the tblinvoice table (this also works great no problems.)
when the second drop down is selected I need to pass that value along with the invoice number to my php script so I can update the record with the instid.(this is the part that don't work)
If I only pass the instid and manually put the invoice number in the where clause of the query all works fine. If I omit the where clause all records are updated as expected. I need to know what I am doing wrong or what is missing.
I will try to post the code here
jquery code
$(document).ready(function() {
$("select#cust").change(function() {
var cust_id = $("select#cust option:selected").attr(
'value');
var test = $("#test").val();
var din = $("#idate").val();
$("#inst").html("");
if (cust_id.length > 0) {
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
$('#inst').html(
'<img src="loader.gif" alt="" width="24" height="24">'
);
},
success: function(html) {
$("#inst").html(html);
}
});
if (test == 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
},
success: function(html) {
$("#invoice").html(html);
$("#test").val(1);
var inum = $("#inv").val();
$("#invnum").val(din +
"-" + inum);
}
});
}
}
});
$("select#inst").change(function() {
var inst_id = $("select#inst option:selected").attr(
'value');
var custid = $("select#cust option:selected").attr(
'value');
var invid = # ("#inv").val()
if (inst_id.length > 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: {
inst_id: inst_id,
}
cache: false,
beforeSend: function() {
},
success: function() {
}
});
}
});
});
I have tried using data: {inst_id:inst_id,custid:custid,invid:invid,} (no update to the table like this)
I also tried data: "inst_id="+inst_id+"&custid="+custid+"&invid="+invid,(this also gives no results.)
Can someone PLEASE look at this jquery and see if I am making a simple error?
Try this format:
data: { inst_id: inst_id, custid: custid, invid: invid },
You can post a JSON object to the server so long as you serialize it and then let the server know the data type.
First you need to define your JSON object:
var postData = { inst_id: inst_id, custid: custid, invid: invid };
Then update your ajax to use the serialized version of that object and let the server know the data type:
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: JSON.stringify(postData),
contentType: "application/json",
..continue the rest of your ajax....
I have an MVC application with a controller named Angular (I use AngularJS as well), which has an action called GetQuestion. That action returns a JsonResult which looks like this (grabbed from Chrome):
{"game":{"Title":"Diablo III","ImgPaths":["d31.jpg","d32.jpg"]},"Answers":["Diablo III","World of Tanks","Need for Speed"]}
My JS function is like this:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(data); })
});
But instead of the Json I wrote above, alert window only says [object Object]
Update
Ok, that was fixed, thaks. However as you may suspect, my goal is not to present this data in alert box, but use it somehow. So here's my controller in Angular
function QuestionCtrl($scope) {
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: function (data) {
$scope.answers = JSON.stringify(data.Answers);
$scope.imgPath = JSON.stringify(data.game.ImgPaths[0]);
}
});
}
And then the view:
<div ng-controller="QuestionCtrl">
<img class="quizImage" src="~/Gallery/{{imgPath}}"/>
#using (Html.BeginForm("Answer", "Angular", FormMethod.Post))
{
<p ng-repeat="answer in answers"><input type="radio" name="game" value="{{answer}}"/> {{answer}}</p>
<p><input type="submit" value="Answer"/></p>
}
</div>
And I don't have neither image or the questions. If I hardcode them in controller then it's ok.
An alert will show that, i would suggest using console.log(data)
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { console.log(data); })
});
or as the comments states:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(JSON.stringify(data)); })
});
I resolved my second problem like this:
function QuestionCtrl($scope, $http) {
$http.post('/Angular/GetQuestion',null).success(function(data) {
$scope.answers = data.Answers;
$scope.imgPath = data.game.ImgPaths[0];
//console.log($scope.answers);
//console.log($scope.imgPath);
});
}
Note that it's AngularJS.
The reason it's happening is because JSON is an Object in JavaScript. When you type
alert(data);
It will attempt to cast the object to a string which in this case will only output that fact that it's an Object.
To view the contents of an object you can write a simple function to use with an alert or console.log.
function outputProperties(anObject) {
var props = '';
for (var prop in anObject) {
props += '\n' + prop + ' value: ' + anObject[prop];
}
return props;
}
And use it like this
alert(outputProperties(data));
For starters... when ever you are dynamically building the src url for an image (using the {{expression}} syntax from Angular) you need to not use the "src" attribute and use the "ng-src" angular directive. It allows angular time to process your url before the image is loaded.
I have such code:
var regions = [{'label': 'array', 'value': '1'}]; //default values
$("#auto1").select({
regions = jQuery.parseJSON( //updating process
$.ajax({
type: 'POST',
url: '/ajax/place/',
data: { country: value }
})
);
return false;
});
$("#auto2").some_func({
initialValues: regions, //here must be updated values, but it's not
});
I think it is understandable from above code: when page loaded, element #auto2 has default values, but when I select smth from #auto1 it must be updated, but it's not.
How can I update the values corresponding to data value.
Thanks!
$("#auto1").select({
regions = jQuery.parseJSON( //updating process
$.ajax({
type: 'POST',
url: '/ajax/place/',
data: { country: value },
success: function( data ) {
//trying yo update values, after successfull response
//some cool code is here or calling a function to update values
},
error: function( data ) {
//error to update
}
}
})
);
return false;
});
Your problem is with how you are trying to get your ajax data back. ajax calls are asyncrynous, which means they will not hold up the code until they return. Because of this jQuery.ajax allows for you to tie into success and failure callbacks which fire depending on if the ajax response returned a success or failure code. You need to parse your data in the success callback and store it in a variable at a scope where your some_func method can see it
var regions = [{'label': 'array', 'value': '1'}]; //default values
$("#auto1").select({
$.ajax({
type: 'POST',
url: '/ajax/place/',
data: { country: value },
success: function(data){
regions = jQuery.parseJSON(data);
}
});
return false;
});
$("#auto2").some_func({
initialValues: regions
});