I am using JQuery UI for autocompletion where I take input and ping a server with that input and end create an array to be given to the source of autocomplete. Right now it works perfect sometimes, but when i print the people array sometimes not all the source data shows up on the screen that is shown in console.
let input =$("<input type='text'/>")
.appendTo('#dynamic-form-elements');
input.autocomplete({
source: [] // Initially empty
}).on('input', function () {
$.ajax({
url: "https://lookmeup/json/person/" + input.val(),
dataType: "json",
success: function (parsed_json) {
let people = [];
let results = parsed_json.data;
for (i = 0; i < results.length; i++) {
people.push(results[i][1])
}
console.log(people)
input.autocomplete('option', 'source', people);
}
});
})
You need to include the "minLength:" attribute in the autocomplete so it waits til you hit the minimum length before it performs the ajax.
You can see this in use here:
https://jqueryui.com/autocomplete/#remote-jsonp
The final code should look like this:
input.autocomplete({
source: function(req, response) {
$.ajax({
url: "https://lookmeup/json/person/" + req.term,
dataType: "json",
success: function (parsed_json) {
// do the stuff here and call response callback
}
});
},
minlength: 3
})
You should do this, use source as function: https://jqueryui.com/autocomplete/#remote
input.autocomplete({
source: function(req, response) {
$.ajax({
url: "https://lookmeup/json/person/" + req.term,
dataType: "json",
success: function (parsed_json) {
// do the stuff here and call response callback
}
});
}
})
Related
I'm using an $.ajax(); request to make a call to my controller. Inside the console.log();, it's correctly displaying all of the data coming in but when I try to display it on the browser via $('#displayCoins').text(item.oldCoins); - only the very last piece of data if being displayed instead of all of the data.
What am I doing wrong and how can I go about rectifying this in terms of displaying all of the data on the browser?
$.ajax({
type: "GET",
url: '/my/endpoint',
dataType: "html",
success: function (response) {
var resp = response;
var respParsed = $.parseJSON(resp);
$.each(respParsed, function(i, item) {
console.log(item.oldCoins);
$('#displayCoins').text(item.oldCoins);
});
}
});
The problem that you are having is you are REPLACING the text every time through the loop instead of appending it.
One solution is to append the data to an array, then output it to the DOM via a single join.
$.ajax({
type: "GET",
url: '/my/endpoint',
dataType: "html",
success: function (response) {
var resp = response;
var respParsed = $.parseJSON(resp);
oldCoins = [];
$.each(respParsed, function(i, item) {
console.log(item.oldCoins);
oldCoins.push(item.oldCoins);
});
$('#displayCoins').text(oldCoins.join("\n"));
}
});
I'm trying to make a notification system that gets data every 5 secs but I don't know why it doesn't work properly. It outputs the notification endlessly but it should get the data and compare it to the last data it stored and if the data is not the same it should append the notification(s) and when it's the same it should alert "same".
var appliedData;
setInterval(getNotifications, 5000);
function getNotifications(){
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "json",
async: false,
success: function(data) {
if ( appliedData != data ) {
appliedData = data;
for(i=0; i < data.length; i++){
$( ".notification-container" ).append('<div class="notification"><p>' + data[i].user + '</p></div>');
}
}else{
alert("sammee");
}
}
});
}
Objects (any non-primitive: an array is an object) will never be equal to each other unless they reference the same place in memory. When comparing, your appliedData will always be different from your data, so that condition will always fail. If the response strings can be guaranteed to be the same when they represent the same object, you can simply compare the strings, as shown below. If not, you'll have to carry out a deep comparison instead.
let lastDataStr;
setInterval(getNotifications, 5000);
function getNotifications() {
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "text", // change here, then parse into an object in success function
async: false,
success: function(newDataStr) {
if (newDataStr === lastDataStr) {
alert('same');
return;
}
lastDataStr = newDataStr;
const newData = JSON.parse(newDataStr);
newData.forEach(({ user }) => {
$(".notification-container").append('<div class="notification"><p>' + user + '</p></div>');
})
}
});
}
What I want is a technique to refresh my div if there are changes in my database. Here is the point,
What i want: How can i condition to know if the first value from my database is lesser than the upcomming value.
In my situation, i put my ajax function to be run every 5secs here is it:
lastcountQueue is declared as global in javascript
function check_getqueue() {
$.ajax({
url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
type: "POST",
dataType: "JSON",
success: function(data) {
lastcountQueue = data[0]['count'];
}
});
}
Q:where would i put the condition something if lastcountQueue < data[0]['count]; condition means something if the data is lesser than lastcountQueue it means there was a change in my database portion.
Another Clear Situation for my question:
I want to make a function like these: the ajax will run every 5 seconds where it query a value to count my no. of queues in database. If my first query is giving me 5 value, and the second is giving me again another 5, then there must be nothing change happens, then if my third value gives me 4, where it is not equal to the last query, then i would do something
Probably something like this:
function check_getqueue() {
$.ajax({
url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
type: "POST",
dataType: "JSON",
success: function(data) {
var tmpCountQ = data[0]['count'];
if (tmpCountQ < lastcountQueue) {
// Process the change
}
lastcountQueue = tmpCountQ;
}
});
}
Here is the updated answer:
function check_getqueue() {
$.ajax({
url: siteurl + "sec_myclinic/checkingUpdates/" + clinicID + "/" + userID,
type: "POST",
dataType: "JSON",
success: function(data) {
if (data[0]['count'] != lastcountQueue) {
//Your logic here
lastcountQueue = data[0]['count'];
}
}
});
}
hi actually i read many topic about array and jquery and they all show example using jquery inside the hmtl script tag but what i try to learn is how to read an array sent by php throught ajax inside a js file
here is my php example
$record = array('jazz','rock', 'punk', 'soft', 'metal');
echo json_encode($record);
then here is my ajax
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
// here i want to read the array and make a loop for each element
},
});
thanks if you can help me
try basic for loop with count using length This .. this should help surely.
function ajax_test()
{
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response)
{
for (var i = 0; i < response.length; i++)
{
alert(response[i]);
}
}
});
}
Try a for loop to loop the records
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
var record;
for(record in response)
{
console.log(response[record]);
});
},
});
Please use below code :
$(response).each(function(key,value){
console.log(value);
});
Here each loop of response array and value get ('jazz',rock,...etc).
try see this, clear solution for your question
https://stackoverflow.com/questions/20772417/how-to-loop-through-json-array-in-jquery
$.each : A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. Reference documentation
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
//Check if the response is in expected JSON format.
var flag = isJSON(response);
if(flag === true)
{ response = JSON.parse(response); }
//Iterate the Array using for each loop of jquery
$.each(response, function( index, value ) {
console.log( "Index : " + index + "Value : " + value );
});
} // End of success function
}); //End of Ajax
//JSON format check
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
You can get array indexes and values by using .each in jQuery as:
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
$.each(response, function(index,value)
{
console.log(index); // print all indexes
console.log(value); // print all values
});
},
});
<div id="dat" name="dat"></div>
<script type="text/javascript">
$.ajax({ url: "music_list.php",
dataType: 'json',
cache: false,
success:function(response) {
for( res in response) {
document.getElementById('dat').innerHTML+=response[res]+"<br/>";
}
}
});
</script>
I have a piece of code that retrieves the last question on a program and it is suposed to update the values of HTML5 progress bars with the latest values.
Now for some reason that I cannot find, when I console.log the data parameter, it is full. But when I try to use it nothing is shown.
Is there something wrong in the code that I cannot realize?
//Run timer
$(document).ready(function () {
if($('input[name=active_question]').val()!="")
{
start_timer();
}
});
function start_timer()
{
var x=0;
function doStuff() {
x++;
$('.timer').html(x+' sec');
console.log('Timer:'+x);
$.ajax({
method: "GET",
url: "/services/get_active_question/"
})
.done(function( data ) {
//It is time to regenerate the question values.
console.log('Data:'+data);
if(data['id']!=0)
{
regenerate_question(data);
}
});
}
setInterval(doStuff, 1000);
}
function regenerate_question(data)
{
if(data['id']!=0)
{
console.log('A: '+data['a']);
$('.progress-a').prop('value',data['a']);
$('.progress-b').prop('value',data['b']);
$('.progress-x').prop('value',data['x']);
$('.progress-y').prop('value',data['y']);
}
}
Your return from the ajax is json string. But the ajax is not identifying it as JSON. So you'll need to specify the dataType as JSON.
$.ajax({
method: "GET",
url: "/services/get_active_question/",
dataType: 'json'
}).done(function( data ) {
//It is time to regenerate the question values.
console.log('Data:'+data);
if(data['id']!=0)
regenerate_question(data);
});
Alternative way is to use
data = JSON.parse(data)
in the done function.