PHP jQuery trigger button on dom change - php

I have this scenario:
I have a simple php file with only few html elemnts: a div called switch, another called lamp and a couple of buttons.
The two buttons are labeled On and Off.
The lamp div is empty.
The switch div is empty too, but is updated using jQuery and Ajax with the content of a txt file, that only contains one word: it could be On or Off.
What i'm traying to achieve is this: whenever the file is updated with the word On or Off i would like the On or Off button to be triggered correspondingly and the lamp div to change the background color. Is it possible?
UPDATE:
Example:
(function($){
$(document).ready(function() {
$.ajax({
url : "testfile.txt",
dataType: "text",
success : function (data) {
$("#switch").html(data);
// this doesn't seems to work...
var word = data.toLowerCase();
$('#' + word).trigger('click');
// this works
$(document).ajaxStop(function(e){
var response = $("#switch").html();
$("#" + response.toLowerCase()).trigger("click");
});
var $container = $("#switch");
var refreshId = setInterval(function()
{
$container.load('testfile.txt').html();
}, 2000);
}
});
});
})(jQuery);
<div id="switch"></div>
<div id="on" class="button">On</div>
<div id="off" class="button">Off</div>
<div id="lamp"></div>

Since the response is only one word. Why not try
var word = data.toLowerCase();
$('#' + word).trigger('click');
in the success callback.

If you have only one ajax request, you can do like this:
$(document).ajaxStop(function(e){
var response = $("#switch").text();
// do what you want with variable response here
$("#" + response.toLowerCase()).trigger("click");
});

Maybe this can help for what you need:
(function($){
$(document).ready(function() {
var $container = $("#switch");
$container.load("testfile.txt", function() {
setInterval(function() {
$container.load("testfile.txt");
}, 2000);
});
});
})(jQuery);
Use clearInterval() to stop the timer when needed.

Related

jquery: prevent resubmission of form until first one event is done

I have a form that I am intercepting through Ajax / jQuery.
The problem here is in case some fields are not filled I show errors from textStatus into an error div.
My function then removes the div completely and reinserts a new empty one after removal of the original one (to have the div again for error showing).
What happens is that if I submit the form multiple times the new error div will be inserted multiple times in the dom, and the errors will be presented three times immediately in the original error div. I of course only need one error div and one set of errors to be shown.
My script is as follows:
jQuery(function ($) {
$(document).ready(function () {
$("#AddModel").on("submit", function (e) {
var SubmitButton = $("#AddBtn");
SubmitButton.blur();
var form = $(this);
var postData = new FormData($("#AddModel")[0]);
var errors = $('#errors');
var theForm = $('#theForm');
var divAlert = "<div id=\"errors\">AAA<\/div>";
$.ajax({
type: 'POST',
url: form.prop('action'),
processData: false,
contentType: false,
data: postData,
success: function (data) {
console.log(data);
},
error: function (textStatus) {
var json = JSON.parse(textStatus.responseText);
$.each(json, function (key, value) {
var errorVar = "";
errorVar += "<div id=\"error\" class=\"col-lg-6 alert alert-danger\">";
errorVar += "" + value + "";
errorVar += "<a class=\"close\" data-dismiss=\"alert\">×<\/a>";
errorVar += "<\/div>";
errors.append(errorVar);
});
if (errors.is(":visible")) {
errors.not('.alert-important').delay(7000).fadeOut(350).promise().done(function () {
errors.remove().promise().done(function () {
$(divAlert).insertAfter(theForm);
})
});
}
}
});
e.preventDefault();
});
});
});
for example at initial stage I will have this situation in the page:
<div id="errors"></div>
If I press submit button 3 times in a row at the end, after showing the errors and removing the div I will get this situation in the page:
<div id="errors"></div>
<div id="errors"></div>
<div id="errors"></div>
What happens right before the insertion of those three elements is:
<div id="errors" style="display: none;">
I guess this is during the fadeOut(350) part of the script.
What I would like to achieve is if the button is pressed then wait for the script to finish and then be able to submit again.
I don't like the timeout option as I don't know exactly how much time the browser will take to display the errors and then removing and reinserting the error div. So how can I disabled subsequent submission until this part of the script has ended? ->
if (errors.is(":visible")) {
errors.not('.alert-important').delay(7000).fadeOut(350).promise().done(function () {
errors.remove().promise().done(function () {
$(divAlert).insertAfter(theForm);
})
});
}
You can trace your script progression by declaring a variable right before your on('submit') function and use it to limit submissions:
jQuery(function ($) {
$(document).ready(function () {
var isEnded=true;
$("#AddModel").on("submit", function (e) {
if(isEnded){
isEnded=false;
.... YOUR CODE
}
});
});
});
When your specific portion of code is over, just add :
isEnded=true;

jquery ajax in wordpress page not found error

this link from ajax call
ajax call from this page
output page
$('#sw_stop,#cd_stop').live('click', function() {
clicks += 1;
if (clicks>=10) {
clicks=10;
var alt="Kick Count Completed!";
$("#alert").show();
document.getElementById("alert").innerHTML=alt;
$.APP.stopTimer();
var h=$("#sw_h").text();
var m=$("#sw_m").text();
var s=$("#sw_s").text();
alert(s);
//var name=$("#name").val();
//var message=$("#message").val();
$.ajax({
type:"POST",
url:"http://www.mummycenter.com/kick-ajax/",
data:{hour:h,minute:m,second:s},
success:function(data){
$("#info").html(data);
}
});
}
document.getElementById("clicks").innerHTML = clicks;
});
above code for jquery ajax this code page not found error please help me.
You're adding jquery library from external source, but wordpress by default adds jquery to the page. Loading it twice is not efficient, and might give conflicts, so either disable that in wordpress, or just don't add the external script source.
The jquery that comes with wordpress runs in no-conflict mode, meaning that you can't use the $ shorthand. Instead you must use jQuery. You can use the $ in your code if you wrap it inside
jQuery(document).ready(function($) {
// your $ code here
});
.live is deprecated in v1.7 and removed in v1.9. Use .on instead.
thanks for comment but problem is pre-defined keyword "hour","minute" that's why ajax not called but by renaming this pre-define keyword now work perfectly
$('#sw_stop,#cd_stop').live('click', function() {
clicks += 1;
if (clicks>=10) {
clicks=10;
var alt="Kick Count Completed!";
$("#alert").show();
document.getElementById("alert").innerHTML=alt;
$.APP.stopTimer();
var h=$("#sw_h").text();
var m=$("#sw_m").text();
var s=$("#sw_s").text();
alert(s);
//var name=$("#name").val();
//var message=$("#message").val();
$.ajax({
type:"POST",
url:"http://www.mummycenter.com/kick-ajax/",
data:{ho:h,mi:m,se:s},
success:function(data){
$("#info").html(data);
}
});
}
document.getElementById("clicks").innerHTML = clicks;
});

ToolTip - does not work after refresh the div

I ask you for help. Namely, struggling with the tooltip in ajax. Everything works beautifully when the page is load or after such as F5. However, in the part web I use refresh div every 60 seconds by ajax
<script type="text/javascript" >
$.ajaxSetup({ cache: false });
var auto_refresh = setInterval(
function()
{
$('#loaddiv').load('refresh_clusterdx_2.php');
}, 60000);
</script>
The code of my tooltip
<script type="text/javascript">
$(document).ready(function(){
function showProfileTooltip(e, id){
var top = e.clientY -45;
var left = e.clientX + 25;
$('.p-tooltip').css({
'top':top,
'left':left
}).show();
//send id & get info from get_prefix.php
$.ajax({
url: '/Info/get_prefix.php?id='+id,
beforeSend: function(){
$('.p-tooltip').html('Loading..');
},
success: function(html){
$('.p-tooltip').html(html);
}
});
}
function hideProfileTooltip(){
$('.p-tooltip').hide();
}
$('.profile').mouseover(function(e){
var id = $(this).attr('data-id');
showProfileTooltip(e, id);
});
$('.p-tooltip').mouseleave(function(){
hideProfileTooltip();
});
});
</script>
All beautifully and looks ok until the div is not refreshed. When a div to be refreshed, the tooltip no work :( I can not find a solution to the problem, whether it is at all possible to solve.
Thank you for any help.
Regards
tjakob
To ensure that your functions work after ajax loaded content, you'll have to modify them a little:
$(document).on('mouseover', '.profile', function() {
var id = $('.profile').attr('data-id');
showProfileTooltip(e, id);
});
$(document).on('mouseleave', '.p-tooltip', function() {
hideProfileTooltip();
});
You should always use .on with dynamically loaded content - I'm in the habit of doing this for all my functions now.

Other jquery functions NOT working after successful ajax function

EDIT
JQUERY-AJAX REQUEST CODE:
<script type="text/javascript">
$(document).ready(function(){
$(".form").submit( function(e) {
e.preventDefault();
var form = $(this);
var div_add_comment = $(form).parent();
var div_comments = $(div_add_comment).parent();
$.ajax({
type: "POST",
data: $(form).serialize(),
url: "includes/comment.php",
success: function(msg){
$(div_comments).html(msg);
}
});
return false;
});
});
</script>
JQUERY SHOW ALL - COLLAPSE COMMENTS CODE
<script type="text/javascript">
$(document).ready(function(){
$('.see_all').click(function(){
var thisItem = $(this);
thisItem.parent().find('#comment2').slideDown('fast');
thisItem.parent().find('.collapse').css('display','inline-block');
thisItem.css('display','none');
return false;
});
$('.collapse').click(function(){
var thisItem = $(this);
thisItem.parent().find('#comment2').slideUp('fast');
thisItem.css('display','none');
thisItem.parent().find('.see_all').css('display','inline-block');
return false;
})
})
</script>
JQUERY REMOVE DEFAULT VALUE TEXT UPON FOCUS - TEXTAREA
<script type="text/javascript">
$(document).ready(function(){
var Input = $('textarea[name=comment]');
var default_value = Input.val();
$(Input).focus(function() {
if($(this).val() == default_value)
{
$(this).val("");
}
}).blur(function(){
if($(this).val().length == 0)
{
$(this).val(default_value);
}
});
})
</script>
Please let me know if you need anything else, I have the damndest of time copying code and formatting it in these posts.
END EDIT
I am having a weird little problem. I have created a jquery-ajax function to transfer data from a comments section of my page. The page has an instance of this form under each user post. So this page will have X amount of posts with X amount of comments for each posts, like a social network. My ajax request sends, recieves and displays the data perfectly BUT I have two other jquery functions called on elements inside that no longer work after the ajax function returns the html. All the other ones not acted upon by the ajax function STILL WORK. I have the checked and rechecked the response html from the ajax function and it is identical to the html of a standard post-comment instance.
Please let me know what you would like to see or if you have questions.
Thanks, your help is always appreciated!
Be sure to bind the jQuery functions in such a way that the element doesn't have to exist.
$('ul').on('click', 'li', function(){ /* do something */ });
This will execute on LIs that have been added after the binding of the function.
In your case you would want to bind to the parent of the comments section and target the elements that have the click behavior.
$('.comments')
.on('click', '.see_all', function(){...})
.on('click', '.collapse', function(){...})
.on('focus', 'textarea[name=comment]', function(){...})
.on('blur', 'textarea[name=comment]', function(){...})
Try removing the $() from form.
You have this:
var form = $(this);
var div_add_comment = $(form).parent();
var div_comments = $(div_add_comment).parent();
It should be this:
var form = $(this),
div_add_comment = form.parent(),
div_comments = $(div_add_comment).parent();
Since you declared var form = $(this); you don't need to wrap form...how you have it now is the equivalent of $((form))
Not sure if this will fix your problem, but jQuery may be getting hung up on this since you are spawning children from $(this).

data in mysql show after barcode split and matches character

i need some code for the next step..this my first step:
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
});
</script>
after matches..i want the result can connect to data base then show data from table inside <div id="value">...how to do that?
you can start here. $.ajax();
You should have some server side scripting knowledge also.
You will need to do it using an ajax call (matches will be a parameter for the call). The php script called through ajax will have to fetch the data and give it back to the calling page.
There you will need to parse the ajax response and display what you want.
A helpfull tutorial can be found here.
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
$.ajax({
type:"post",
url:"process.php",
data:params,
cache :false,
async :false,
success : function() {
alert("Data have been input");
$("#value").html(matches);
return this;
},
error : function() {
alert("Data failed to input.");
}
});
return false;
});
</script>
and i change my process.php become:
select itemdata as version from settingdata where version = "tunerrange";

Categories