Javascript load from php and onchange variable - javascript

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);

Related

jquery .load keeps firing javascript after .remove

I'm making a chat with the simple javascript:
<script>
function chatClick(messages_other_user) {
$('#chatBox').remove();
document.body.innerHTML += "<div id='chatBox' class='chatDiv'></div>";
$("#chatBox").load("subs/chat/chat.php?ou="+messages_other_user);
}
</script>
This function is called in several links with the variable "messages_other_user" changing.
In the file "chat.php" I get the variable of "ou" and I have a script that writes to the console:
if (isset($_GET['ou'])) { $otherUserChat = $_GET['ou']; } else $otherUserChat = 0; // get $otherUserChat
<script>
$(document).ready(function() {
var chatUpdateVar = setInterval(function() {
console.log("<?= $otherUserChat ?>");
}, 2000);
$.ajaxSetup({ cache: false });
});
</script>
But the .remove line doesn't quite get rid of the javascript in the chat.php file. When I click a link to call the javascript chatClick function, it works fine. But when I then click another link that calls chatClick with a different variable for "messages_other_user" the old one keeps firing along with the new one.
How can I destroy the old javascript completely so it doesn't run anymore?
I found the solution - and I was mistaken by the true culprit of the issue.
I thought a console.log would yield the same result as what I truly do - I just chose to replace with console.log in the code for simplicity. So I guess I've learned that's a stupid thing to do.
What is actually happening in the chat.php file in the document ready script is this:
$(document).ready(function() {
var chatUpdateVar = setInterval(function() {
$("#chatArea").load("subs/chat/chatContent.php?ou="+<?= $otherUserChat ?>);
console.log("updated");
}, 4000);
});
I figured out I didn't readlly need to use the document ready, so I instead, I just do this directly in my script:
var chatUpdateVar = setInterval(function() {
$("#chatArea").load("subs/chat/chatContent.php?ou="+<?= $otherUserChat ?>);
console.log("updated");
}, 4000); // CHECK FOR UNREAD: 1000 equals 1 second
$.ajaxSetup({ cache: false });
For closing the chat window, I now trigger this function:
function closeChat() {
clearInterval(chatUpdateVar);
$('#chatBox').remove();
}
And in the file that calls the above script (chat.php), I check if the function closeChat exists - and if it does, I run it. This is part of the cal to the chat.php:
function chatClick(messages_other_user) {
if (typeof closeChat === "function") {
closeChat();
}
document.body.innerHTML += "<div id='chatBox' class='chatDiv'></div>";
$("#chatBox").load("subs/chat/chat.php?ou="+messages_other_user);
}

Check the div's height every 5 seconds and change class if true

I have this function already, which checks for change, and if true only updates this div.
jQuery(document).ready( function($) {
var auto_refresh = setInterval(function() {
$.ajax({
success: function(data) {
var result = $('<div />').append(data).find('div#vs').html();
$('div#vs').html(result);
}
})
}, 5000); // refreshing after every 5000 milliseconds
})
This works great, but now I want to add another function, I have made this javascript http://jsfiddle.net/jockebq/ocLh1rLd/
What it does is that if the height of the div #vs exceeds 300px it will add class .vscroll to #vs.
I have managed to make this work great in JSFiddle, but I cannot figure out how to merge this together with my javascript above.
I'm very much stuck, and I cannot find any information on how to do this. All help and tips are much appreciated!
I am sure i am missing something here but why not just
add it inside the function passed to setInterval and run it alongside the ajax call
var auto_refresh = setInterval(function() {
$.ajax({
success: function(data) {
var result = $('<div />').append(data).find('div#vs').html();
$('div#vs').html(result);
if (document.getElementById('vs').clientHeight > 300 )
$('div#vs').addClass('vscroll');
}
});
}, 5000); // refreshing after every 5000 milliseconds
})
PS: Your ajax better not be as you pasted it here!
EDIT: added the code in the success callback, since you probably want to resize when the new content is appended,as said by Pierre

Two ajax forms not working at the same time

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>

Handling State changes jQuery and History.js

Ok, so I need some insight into working with History.js and jQuery.
I have it set up and working (just not quite as you'd expect).
What I have is as follows:
$(function() {
var History = window.History;
if ( !History.enabled ) {
return false;
}
// Capture all the links to push their url to the history stack and trigger the StateChange Event
$('.ajax-link').click(function(e) {
e.preventDefault();
var url = this.href; //Tells us which page to load
var id = $(this).data('passid'); //Pass ID -- the ID in which to save in our state object
e.preventDefault();
console.log('url: '+url+' id:'+id);
History.pushState({ 'passid' : id }, $(this).text(), url);
});
History.Adapter.bind(window, 'statechange', function() {
console.log('state changed');
var State = History.getState(),
id = State.data.editid; //the ID passed, if available
$.get(State.url,
{ id: State.data.passid },
function(response) {
$('#subContent').fadeOut(200, function(){
var newContent = $(response).find('#subContent').html();
$('#subContent').html(newContent);
var scripts = $('script');
scripts.each(function(i) {
jQuery.globalEval($(this).text());
});
$('#subContent').fadeIn(200);
});
});
});
}); //end dom ready
It works as you'd expect as far as changing the url, passing the ID, changing the content. My question is this:
If I press back/forward on my browser a couple times the subContent section will basically fadeIn/fadeOut multiple times.
Any insight is appreciated. Thanks
===================================================
Edit: The problem was in my calling all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.
The problem was in my calling of all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.

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.

Categories

Resources