I'm getting my response from my GET requests to this API that I'm working with which is great. I just need the responses to be random every time I click my button, but I'm having trouble with that. I have a math.random function below in my code, but I don't have it active right now because I'm not sure what to do with it. I've tried some different approaches but nothing seems to work.
$(document).ready(function(){
//When you click the submit button it fires off the getRequest.
$(function(){
$('#search-term').submit(function(e){
e.preventDefault();
myFunction();
//clearText();
});
});
// This is the get request. I want it to have a random function that randomizes the callback data. Once you get the randomizes data, it shows in the console window. I want this function display three random results based on the myFunction() below
function getRequest(){
$.ajax({
url:'https://api.foursquare.com/v2/venues/search? ll=40.7,-74&client_id={my client id]&client_secret=[my secret]',
type: 'GET',
dataType:'json',
success: function(data){
var venues = data['response']['venues'];
//This is my random function which I do not know what to do with
var random = [Math.floor(Math.random() * venues.length)];
$.each(venues, function(key,index){
console.log(index.name);
$('#search-results').append(index.name + '<br>');
})
}
})
};
//This is the function that calls getRequest function three times then stops.
function myFunction(){
var myVar = setInterval(function(){getRequest();}, 500);
//clearTimeout(myVar);
setTimeout(function( ) { clearInterval( myVar); }, 1600);
}
//This function clears the text that exists in the form so that the new random text can populate it.
function clearText(){
$("#search-results").text("");
};
});
Related
I have a page displaying data from a json feed and I also have a button which loads more of the feed on click of a button. My aim is to append some content inside the page for each feed item. I have been able to create a function which does this on load of the page, but I am unsure how to make this work with the aysynchronous loading of more data.
I understand I need to use the .done() callback to make this work but need some guidance how to implement it correctly.
This function appends the new content initially:
function appendFeed() {
$('.feed__item').each(function (index) {
$feedItem = $('.feed__item', $(this));
$feedItem.append('<div class="feed-gallery"></div>');
for (var i = 1; i <= 5; i++) {
var $count = i;
if ($count > 1) {
$('.feed.gallery', $(this)).append('<div><img data-lazy="//placehold.it/50x50"></div>');
};
});
}
This is where the .done() callback is referred, on click of a button:
$('button').click(function(){
$.getJSON(uri, function (json, textStatus) {
// do stuff
}).done(function (json) {
// do stuff - in my case this would be appendFeed()
});
});
I have already called the appendFeed() function, but if I put it inside the .done() callback on click the button, then it appends the feed again. How do i prevent the duplication for the feed that is already on the page?
This is how you will write.
<script type="text/javascript">
$.getJSON("/waqar/file.php").done(function (data) {
$(".output").append(data);
});
</script>
I have two boxes, one box is called min amount and another is called max amount. When you put 100 in the max amount, it will find products that are less then $100. But when you put lets says later $50 in the min amount, it wont work unless you refresh the page
My question is, how do I make this script work for both of my boxes as if I use one box for the ajax the other ones doess not work without refreshing.
I'm sorry if I sound a bit confusing but this is what I tried so far and it still doesn't work.
<script>
//on keyup, start the countdown
$('#maxprice').keyup(function(){
doneTyping();
});
function doneTyping() {
var value = $('#maxprice').val();
$.post("script/limitedfetcher/maxprice.php",
{
name: value
},
function(data, status){
$("#loader").empty();
$('#loader').html(data);
});
}
</script>
<script>
$('#minprice').keyup(function(){
doneTyping();
});
function doneTyping() {
var value = $('#minprice').val();
$.post("script/limitedfetcher/minprice.php",
{
name: value
},
function(data, status){
$("#loader").empty();
$('#loader').html(data);
});
}
</script>
Use this!!
Pass the element where keyup occurs to the function.
Then, based on which of the two it is... decide about the URL... The rest of the function is the same, no need to define it twice.
<script>
//on keyup, start the countdown
$('#minprice, #maxprice').keyup(function(){
doneTyping(this);
});
function doneTyping(element) {
var value = $(element).val();
if($(element).attr("id")=="maxprice"){
url = "script/limitedfetcher/maxprice.php";
}else{
url = "script/limitedfetcher/minprice.php";
}
$.post(url,{
name: value
},
function(data, status){
$("#loader").empty();
$('#loader').html(data);
});
}
</script>
I am working on a dynamic online form website. In the main form, I have multiple sub-forms which can be added and deleted dynamically.
<div class='subform'>
//form fields
<input ...>
...
<button class='subform_submit'>
</div>
For each subform, I bind an AJAX call on the subform's submit button like this:
$('#main').on('click', '.subform_submit', function(){
// Get this subform's user input
...
$.ajax({
url: ..,
type: ..,
data: /* this subform's data */
});
});
So in that page, I may have 0 to 10 subforms depending on the user's selection.
I also have a main submit button on the bottom of the page, which can submit those subforms and the main form's data together.
$('#main').on('click', '#submit', function(e){
$('.subform_submit').click(); // Submit each subform
bootbox.confirm({ });
})
Once main submit button is clicked, I want to show a loading picture and then show a dialog box (I use bootbox.confirm() here) until all AJAX calls have completed.
This dialog box is telling user that whole form including sub-forms has been submitted.
But the problem is that each AJAX call may take 2 seconds to complete and I don't know how may calls may be pending completion. How can I write this main submit button so that it will:
Show the loading image immediately, and
Hide the loading image and show the dialog box after all AJAX calls have completed?
Keep track of how many sub-forms there are;
$subFormsCount = $('.subform').length;
Keep track of how many forms have been submitted;
$submittedForms = 0;
Each time a form finishes submitting, add to the $submittedForms;
$.ajax({
..
..
done: function(){
$submittedForms++;
}
})
Create a global timer to see if the number of submitted forms matches the total number of subforms. If true, hide the dialog box;
setInterval(function(){
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}, 50ms)
Edit
You could skip the global timer (as this will probably be a few milliseconds out) - include the check in your ajax.done instead;
$.ajax({
..
..
done: function(){
$submittedForms++;
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}
})
You want to use .done() in order to specify code that should wait until the AJAX asynchronous function completes.
$.ajax({
url:..,
type: ..,
data: /* this subform's data*/ })
.done(function() {
//Put code here
});
Have you tried .ajaxStop() event handler ?
$(document).ajaxStop(function() {
// place code to be executed on completion of last outstanding ajax call here
});
also, check this answer
I assume you have 9 subform and 1 main form.
Code for 8 subform will be same.
I use here async:false : Means next ajax will not be call until 1st one is not completed.
Sample Code Format :
var id = 5;
$.ajax({
url: ,
type: 'POST',
data: {'id':id},
dataType: 'JSON',
async: false,
error : function(xhr, textStatus, errorThrown) {
alert('An error occurred!');
},
success : function(response){
}
});
Just set variable in your last sub form that is 9th subform.
success : function(response){
var counter = true;
}
if(counter){
/* Code to show dialog.*/
}
You can use $.when to wait for each request to complete. Something like this should get you close. You'd basically want to store all the ajax requests in an array and pass that to when as the arguments.
$('#main').on('click', '.subform_submit', function () {
var formRequests = $('.subform').map(function () {
var $form = $(this);
return $.ajax({
url: '',
data: $form.serialzeArray()
});
}).get();
$.when.apply(undefined, formRequests).done(function () {
console.log('All done!');
});
});
Here goes a very similar little demo I just made up: https://jsfiddle.net/g9a06y4t/
I'm trying to create a PHP page that periodically updates values of several elements on the page. I'm using a host that limits my hits per day, and each hit to any page they're hosting for me counts against my total. Therefore, I'm trying to use JQuery/AJAX to load all of the information that I need from other pages at one time.
I'm calling the following index.php. This method achieves the desired affect exactly the way I want it, but results in three hits (dating.php, dgperc.php, and pkperc.php) every two seconds:
var focused = true;
$(window).blur(function() {
focused = false;
});
$(window).focus(function() {
focused = true;
});
function loadData() {
if (focused) {
var php = ["dating", "dgperc", "pkperc"];
$.each(php, function(index, value) {
$('#'+this).load(this+'.php');
});
}
}
$(document).ready(function() {
loadData();
});
setInterval(function() {
loadData();
}, 2000);
I'm calling the following index1.php. This is where I'm at as far as a method that only results in one hit every two seconds. My workaround is that I have combined the three php pages that I was loading into one, dating1.php. I load this into a div element, #cache, all at once. This element is set to hidden using CSS, and then I just copy its inner HTML into the appropriate elements:
var focused = true;
$(window).blur(function() {
focused = false;
});
$(window).focus(function() {
focused = true;
});
function loadData() {
if (focused) {
var php = ["dating", "dgperc", "pkperc"];
$('#cache').load('dating1.php');
$.each(php, function(index, value) {
$('#'+this+'1').html($('#'+this).html());
});
}
}
$(document).ready(function() {
loadData();
});
setInterval(function() {
loadData();
}, 2000);
Dating1.php will produce different outputs every time it's run, but here is an example of the output:
<span id = "dating">4 years, 7 months, 3 weeks, 10 seconds ago.</span>
<span id = "dgperc">21.9229663059</span>
<span id = "pkperc">22.2121099923</span>
On document ready, index1.php does not function properly: the #cache element isn't filled at all, so the other elements don't get filled either. However, after two seconds, the loadData() function runs again, and then the #cache element is filled correctly, and so are the other elements. For some reason, this isn't a problem on my index.php page at all, and I'm not sure why there's a difference here.
How can I get #cache to load the first time so that the page loads correctly? Or is there a better way to do this?
Each AJAX call is basically a page visit in the background. Like telling your assistant three different times to get you one coffee. Or telling them one to get you three coffees.
If you don't want to combine your three PHP pages into one - thus keeping code separate and easier to maintain. Consider creating one "cache.php" script and inside it:
cache.php:
$outputData = array('dating' => false, 'dgperc' => false, 'pkperc' => false);
foreach($outputData as $file => &$data)
{
//buffer output
ob_start();
//run first script (be smart and file_exists() first)
include_once($file . '.php');
$data = ob_get_clean();
}
//output JSON-compliant for easy jQuery consumption
echo json_encode($outputData);
Then in your javascript:
function loadData() {
if (focused) {
//call ajax with json and fill your spans
$.ajax({
async: true,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqxhr) {
$('#dating').html(data.dating);
$('#dgperc').html(data.dgperc);
$('#pkperc').html(data.dgperc);
// NOTE... do a console.dir(data) to get the correct notation for your returned data
},
url: 'cache.php'
});
}
You are calling cache.php once every two seconds, saving on the 3-hits of calling the php files individually. Using a middle-man file you keep your scripts separate for maintainability.
I currently have the below function which updates the data in a div when the page is refreshed and this works fine however i want to edit the function to make it constantly update say every 2 seconds without having to refresh the page. How would i go about doing this?
<script>
$(document).ready(function ajaxLoop() {
//-----------------------------------------------------------------------
// Send a http request with AJAX Jquery
//-----------------------------------------------------------------------
$.ajax({
url: 'getOrderStatus.php', // Url of Php file to run sql
data: "",
dataType: 'json', //data format
success: function ajaxLoop(data) //on reciept of reply
{
var OrdersSubmitted = data[0].SUBMITTED; //get Orders Submitted Count
var OrdersFulfilled = data[0].FULFILLED; //get Orders Fulfilled count
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#OrdersSubmitted').html("SUBMITTED:" + OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:" + OrdersFulfilled); //Set output html divs
}
});
});
</script>
You can chain setTimeout calls to achieve this:
$(document).ready(function() {
function updateOrders() {
$.ajax({
url: 'getOrderStatus.php',
dataType: 'json',
success: function ajaxLoop(data) {
var OrdersSubmitted = data[0].SUBMITTED;
var OrdersFulfilled = data[0].FULFILLED;
$('#OrdersSubmitted').html("SUBMITTED:"+ OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:"+ OrdersFulfilled);
setTimeout(updateOrders, 2000);
}
});
});
The alternative is setInterval(), however if the requests slow down this can lead to calls being queued, which will eventually lead to memory issues.
You need to add a repeating event to call your updateOrders function. Like:
function startUpdateOrdersTimes() {
setInterval(function() {
updateOrders();
}, 2000);
//Call now (otherwise waits for first call)
updateOrders();
}
Using "window.setInterval" (https://developer.mozilla.org/en/docs/Web/API/window.setInterval) you can repeatedly execute a function at a specified time interval.
function SomeFunction()
{
$.ajax({...});
}
window.setInterval(SomeFunction,2000);
This would execute SomeFunction every 2 seconds
Hope this helps
timerupdateorders = setInterval(function() {
ajaxLoop();
}, 2000);
You may use
clearInterval(timerupdateorders);
to end the timer