I have a button that A) executes a PHP script and B) has a function to hide/show a loading indicator while the script is running.
While the script is running I want to disable the button. The problem I'm running into is that I can disable the button, but this prevents the PHP stuff from running.
Button
<form method="post">
<button id="CheckConnectionBtn" name="CheckConnectionBtn" class="CheckConnectionBtn" button onclick="ShowWaiting()">Test connection</button>
</form>
PHP
<?php
if(isset($_POST['CheckConnectionBtn'])){
$output = shell_exec("/script.sh");
$_SESSION["CONNECTION_CHECK"] = "$output";
}
?>
Function
<script>
function ShowWaiting() {
document.getElementById("loader_id").style.display = "block";
document.getElementById("loader_text_id").style.display = "block";
}
</script>
I tried adding $("#CheckConnectionBtn").attr("disabled", true); to the function but this causes the loader to show up indefinitely, it appears the PHP is not triggered.
I also tried adding a onclick disabled to the button but this only causes a refresh of the page (loader shows up for a sec) and also does not appear to trigger the PHP.
Finally I tried adding
<script>
$("#CheckConnectionBtn").attr("disabled", true);
</script>
To the PHP but this causes a page that doesn't display anything even before clicking the button.
How can I disable the button on click but still trigger the php and my function?
Consider the following code.
$(function() {
function showWaiting() {
$("#loader_id, #loader_text_id").show();
}
function endWaiting() {
$("#loader_id, #loader_text_id").hide()
}
$("#CheckConnectionBtn").click(function() {
var self = $(this);
$.ajax({
url: "this.php",
data: {
CheckConnectionBtn: true
},
method: "POST",
beforeSend: showWaiting,
success: endWaiting
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="CheckConnectionBtn" class="CheckConnectionBtn">Test Connection</button>
Making use of $.ajax(), you can setup the beforeSend callback to start the loading images and then in success callback, turn them off. This does not require a form since it's operating with AJAX. Obviously, replace this.php with the URL of your connection script.
First, replace the button with input type = button,Input attempts to add onclick = "return sub ();"function sub() {document.getElementById('btn').disabled = true;//The ID I'm looking for here is the ID of the input tag//document.forms[0].submit();}
Related
I have a bug (or feature) whereby any button that is inside a Bootstrap 3 modal will fire the click event several times. Besides going "old-school" and calling a script from an HTML button directly (which always works), is there a workaround for this?
<div class="modal-footer">
<span id="spanSendReport">
<button type="button" id="btnSendReport" class="btn btn-success" data-dismiss="modal">Send Report</button></span>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
And the jquery
$("#btnSendReport").click(function (e) {
... my code
});
Using Bootstrap v3.4.1 and jQuery v3.3.1
Never ran into this before (except with things posting back, but there are no postbacks of any kind happening - checked in the browser and in debugger).
There is only 1 button in the DOM with the Id (first thing I checked), but it fires the click event 4 times, every time!
Any ideas?
NOTE: I forgot to mention, the modal is opened from another modal. Maybe that has something to do with it.
The complete code inside the click event function (just in case it has something to do with it):
$("#btnSendReport").click(function (e) {
var parElem = $(this).parent().parent().parent();
var listID = parElem.find("#hidLID").val();
var problemTypes = $.map(parElem.find('option:selected'), function (e) { return e.value; }).join(',');
var problemTypeOther = parElem.find("#txtProblemTypeOther").val();
var obj = {};
obj.lid = listID;
obj.ProblemTypes = problemTypes;
obj.ProblemTypeOther = problemTypeOther;
try {
$.ajax({
type: "POST",
url: "../../api/reportdiscrepancy/",
data: obj,
dataType: "json",
success: function (data) {
var result = data;
},
error: function (err) {
console.log(err);
}
});
} catch (err) {
console.log(err);
}
});
Found the problem and the answer to many issues I've been running into before and the culprit is function pageLoad() which is what older ASP.Net webforms uses for client side actions.
I removed the '#btnSendReport' click to OUTSIDE of the pageLoad() function and it's only firing once now.
It looks like any MS-AJAX accumulates ALL event bindings (not actually firing them) within an UpdatePanel, then a final call to a click event (or whatever) will fire x number of times.
I was clued in as I made 3 changes to get to the modal and the last thing I did was click on the button (so it fired 4 times).
I believe it may have to do with the default setting of the UpdatePanel with ChildrenAsTriggers=True (unfortunately, I have to leave that on as other functionality breaks if set to false).
I have looked at a bunch of different Q/A on stack and I can not seem to solve my issue for why my rest interface is not getting called on the button submit. I would appreciate it if you guys could look and see where the issue could be.
The goal is to have a form input values (for now they are hard coded until I get it to work), and submit to change the database they are in via a REST call.
EDIT: On button click, no errors in console, nothing shows up in DB.
<?php
$id = "123456";
$auth = "XYZ123"; //this will change daily
$url = "http://update/this/id/$id"; //this will change based on user
?>
<script >
const URL = <?php echo json_encode($url);?>;
const auth = <?php echo json_encode($auth);?>;
const data = {
"flag":"Y" //in the database flag has a value of N want to change to Y
}
$.ajaxSetup({
headers: {
'auth-key': '${auth}',
'api-version': '1.0',
'Content-Type': 'application/json',
'Accepts': 'application/json',
'Verbosity' : '4'
}
});
$('.btn').click(function(){
$.post(URL, data, function(data, status){
console.log('${data} and status is ${status}')
});
})
</script>
<button type="submit" class="btn">Send it!</button>
The JavaScript executes before the DOM is loaded (<script> tags interrupt the DOM parser). By the time the script executes there is no .btn element yet.
Either
move the script to the end of the body (or at least after the submit button),
or add the event listener after the DOM has been loaded,
or use the global event listener
$(document).on('click', '.btn', function() { ... }
I need a Google AdWords conversion script to work whenever someone submits a form for a free quote. Google has provided the script which I'm put into a Snippet with WordPress and activated it for the site.
I now need to call that function when the submit button is pressed, but I can't remember the correct syntax and Google searches so far have led me down long paths of .php file creations that isn't answering what feels like a simple solution would solve.
Currently I have added the function in line with the existing code for the submit, but I'm not convinced this is correct. The below code is on the contact form that the page uses.
[submit id:submit class:btn class:btn-primary gtag_report_conversion() "Send"]
Below is the code I put into the Snippet minus the full "send to" AW address:
<script>
function gtag_report_conversion(url) {
var callback = function () {
if (typeof(url) != 'undefined') {
window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': 'AW-.....',
'event_callback': callback
});
return false;
}
</script>
Depending on how that shortcode was implemented, odds are you can't just add inline event handlers to it like that - and without seeing the source code it's hard to determine (but I'd wager that it's most likely the case).
Just add this in the old fashioned way with the onclick or onsubmit event handler. I'd recommend the onsubmit since forms can be submitted without clicking on the button.
Since you've already loaded in your Script, you can just add to it:
<script>
function gtag_report_conversion(url){
var callback = function () {
if (typeof(url) != 'undefined') {
window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': 'AW-.....',
'event_callback': callback
});
return false;
}
document.getElementById("your-form-id").onsubmit = function(){
gtag_report_conversion();
};
</script>
Just replace your-form-id with the id of your <form> element (not your submit button).
On my page I have a list of users. Each user has a profile page on an external site (not the same domain name). To save my client updating their profile details in 2 places, I am using PHP simple HTML Dom Parser. This gets the content of the users external profile page and returns it on my site.
What I am trying to do is load the users profile information into a div on my site only when the users name is clicked.
Each user looks like this:
<div class="actor_container" data-url="www.external-profile-url.com">
<img src="http://placehold.it/500x500" />
</div>
To get the contents of the external page I use this code:
$html = file_get_html('http://www.spotlight.com/5094-1276-6177');
echo $html->find('div.credits', 0);
Obviously this works at the minute as it is hard coded. However I need to make it dynamic so that the external profile info for each user is loaded when the relevant user is clicked.
Update from answer below:
I added this script to the top of the user list:
<script>
jQuery(function ($) {
$(".actor_container").load(function () {
return "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=" + $(this).data("url");
});
});
</script>
then in my.php
<?php
$html = file_get_html($_GET["url"]);
echo $html->find('div.credits', 0);
Currently, when I click on a user, nothing happens
UPDATE
OK I've moved to using AJAX to access my.php. Here is what I have so far:
<script>
jQuery(document).ready(function ($) {
$('.nial_actor').on("click", function (e) {
e.preventDefault();
$.ajax({
url: "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=" + $(this).data("url"),
type: 'GET',
success: function(res) {
var data = $.parseHTML(res);
// append all data
$('#all_data').append(data);
}
});
}); //on
}); // ready
</script>
However this returns the following error:
GET http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=undefined 500 (Internal Server Error)
So for some reason the url in data-url is not adding to the end of my ajax url. Have I missed something obvious?
Something like this works?
$(function () {
$(".actor_container").load(function () {
return "my.php?url=" + $(this).data("url");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="actor_container" data-url="www.external-profile-url.com">
<img src="...actor profile img..." />
</div>
And in the PHP file, you can add url as your GET param:
$html = file_get_html($_GET["url"]);
Note that there are lots of vulnerabilities in this methods. Keep this just as a guidance.
Is there a way to call a (jquery action/write an html text) to a div of a new page after calling the window.location command?
Im trying to make an ajax form submit where the user will be redirected to a new page upon submit,
and in that new page a hidden div will appear with text inside of it
currently this is my code
script.js
$.ajax({
url:url,
type:'POST',
data:datastr,
success:function(result){
if(result=="duplicate"){
$("#status").attr('class', 'span12 alert alert-error');
$("#status").show();
$("#status").html("<h4><center>Duplicate Username</center></h4>");
$("#dept_name").closest(".control-group").attr('class', 'control-group');
$("#username").closest(".control-group").attr('class', 'control-group error');
$("#password").closest(".control-group").attr('class', 'control-group');
$("#username").focus();
}
else{
$("#dept_name").closest(".control-group").attr('class', 'control-group');
$("#username").closest(".control-group").attr('class', 'control-group');
$("#password").closest(".control-group").attr('class', 'control-group');
window.location = base + 'admin/departments/edit_dept/' + result;
}
}
});
i want to make this block of code below work on the page where window.location is going
$("#status").attr('class', 'span12 alert alert-error');
$("#status").show();
$("#status").html("<h4><center>Successfully added Department</center></h4>");
is it possible?
thanks
You can use CI session flash data.
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
Before triggering window.location, set the message in flashdata. On the landing/redirected-to page, check to see if flashdata has a value (success/failure). If so, display (or trigger a js method to show) the message.
You could add a parameter with your window.location, like:
window.location = base + 'admin/departments/edit_dept/' + result + '?showMessage=12'
Then on the next page, have a jquery script that looks for that parameter and shows the message. See this question.
Or you can do it in on the server. But with jquery it works with static html too.
This is a patchup, May require some tuning though.
window.location = base + 'admin/departments/edit_dept/' + result+'/err'; //changed to catchup with the view part
In the Controller:
<?php
if($this->uri->segment(4) == "err"){
$data['err'] = true; #will reflect that we need to show the js in the view
$this->load->view('view', $data);
}
?>
In the view part:
<?php if(isset($err)){ ?>
<script type="text/javascript">
$("#status").attr('class', 'span12 alert alert-error');
$("#status").show();
$("#status").html("<h4><center>Successfully added Department</center></h4>");
</script>
<?php } ?>