Two ajax forms not working at the same time - javascript

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>

Related

How can I randomize my JSON responses?

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("");
};
});

Error Loading AJAX on Document Ready Using JQuery

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.

Page refresh after the request is Done

I have a page with many checkboxes on it, I wrote a JS code that makes call to PHP page for each page, I want to refresh the page after the call has completed..
Here is my code
$(".matchFrnds").each(function(){ //For each CheckBox
if($(this).is(':checked')){
var sendData= $(this).val();
$.post('Call to PHP Page',{sendData:sendData},function(data){
window.location.reload();
});
}
});
The problem is that the page reloads after completing few checboxes, so if there are 60 checkboxes, the page reloads after making call for 10 checkboxes. I also changed the place for window.location.reload(); but the results are same, I want that once the call for all the checkboxes is completed then it reloads.
You can check how many calls you have finished then reload
var boxes = $(".matchFrnds:checked").length;
var calls = 0;
$(".matchFrnds").each(function(){ //For each CheckBox
if($(this).is(':checked')){
var sendData= $(this).val();
$.post('Call to PHP Page',{sendData:sendData},function(data){
calls++;
if(calls >= boxes) {
window.location.reload();
}
});
}
});
It is really easy.
You just need to set a counter, and call reload() on the last one.
The idea would be to have another variable...
// Save the element to iterate in a variable
var matchFrnds = $(".matchFrnds"),
//and save its length too
length = matchFrnds.length;
//Iterate over it
matchFrnds.each(function() {
// modify the counter
--length;
if ($(this).is(":checked")) {
// do your things
$.post( ... , function(data) {
//do what you need to do with the data...
// ....
// ....
});
}
//and, if it's the last element
if (!length) {
// LAST ITERATION!
window.location.reload();
}
});
And that's it.
You could use the .ajaxStop-Event
http://api.jquery.com/ajaxStop/
you can try with this after complete your request:
location.reload();

Javascript load from php and onchange variable

i have a script that loads some div ids from php and every x seconds reloads the new values.. I want to implement an onchange value inside the script in order to trigger loading a new variable if (in this example artist changes) but i cant figure out how..
the script is:
setInterval(function(){
cache: false,
$("#artist").load("test.php #artist");
$("#song").load("test.php #song");
}, 2000);
I need to tell if artist changes then load a new variable from php, using this wrapper code i found here How can I make a program wait for a variable change in javascript??
function Wrapper(callback) {
var value;
this.set = function(v) {
value = v;
callback(this);
}
this.get = function() {
return value;
}
}
If i use the same example with input box:<input type="text" onchange="wrapper.set(this.value)"/>
it works.. But i cant figure out how to make it work using the #artist pulled from the php in the first part..
I tried doing this :
<script type="text/javascript">
setInterval(function(){
cache: false,
$("#artist").load("test.php #artist").onchange(wrapper.set(this.value));
$("#song").load("test.php #song");
}, 2000);
</script>
and a lot of other combinations but neither works.. Can you help me please!
PS: Keep in mind that im a startet in javascript..
Thank you for your answers.
setInterval(function(){
cache: false,
$.get('test.php',function(data){
var artist = $('<div>' + data + '</div>').find('div#artist').html();
if(artist != $('#artist').html()){
$('#artist').html(artist );
wrapper.set(artist)
} //in here I assumed #artist is a div or span,... if its a textbox change it to $('#artist').val()
});
$("#song").load("test.php #song");
}, 2000);

How do I get first value instantly if my throttle is set to 120000

So basically I wan't to get data from server at start and then update it every 2 minutes, but instead it gets first value only after 2 minutes, what can I do about this?
Here is my js markup:
var itemViewModel = {
item: ko.observable().extend({ throttle: 120000 }),
loadcontent: function (getID) {
$.ajax({
url: '/api/item/details/' + getID,
dataType: 'json',
success: function (data) {
itemViewModel.item(data);
}
});
}
};
Maybe this will help, here is a HTML markup:
<div id="item-details-content">
<input type="hidden" id="item-id" value="#id" data-bind=""/>
<div class="item-list" data-bind="init: itemPage.loadcontent(#id), with: itemPage.item">
Conditions
There need to be and initial call of loadcontent
Everything must be inside viewModel
That's not what the throttle extender (link) is meant for. Use setInterval (link) instead.
throttle is meant to handle a scenario where you may receive an arbitrary amount of events in a short timespan and you do not want to act upon every single event. E.g. you have a search field with autocomplete functionality that uses a REST-API. You do not want to call the REST-API every single time a user pushes a key. Rather, you'd like to wait a bit until the user is done typing. This is a perfect use case for throttle.
What you are looking for is a way to repeat an action on a predetermined interval. JavaScript has a builtin function just for that and it's called setInterval.
var itemViewModel = {
item: ko.observable().extend({ throttle: 120000 }),
loadcontent: function (getID) {
var loadData = function()
{
$.ajax({
url: '/api/item/details/' + getID,
dataType: 'json',
success: function (data) {
itemViewModel.item(data);
}
});
}
loadData(); // initial call
setInterval(loadData, 120000); // repeat every 2 minutes
}
};
Throttle's intended use is to make sure the function does not execute more then once every x seconds. As Martin said, setInterval would be better in this situation
var interval = setInterval(function() {
ko.observable();
}, 120000);
ko.observable();

Categories

Resources