How to make a html button lead to a php site? - javascript

I'm creating the buttons dynamically based on if the user is logged in or not.
I'm trying to set the onclick function for the loginBtn for example using location="login.php", but that doesn't seem to do it.
I also tried it with:
$("#loginBtn").click(function(){
$.ajax({
type:'POST',
url:'login.php'
success: function(data) {
alert(data);
}
});
});
but that didn't work either.
Here's the code that creates the buttons:
window.onload = function () {
var loggedIn = '<?php echo $_SESSION["loggedin"] ?>';
//Set login buttons to register/login or logout
if(loggedIn == 1)
{
document.getElementById("loginButtons").innerHTML =
'<button id="logoutBtn" type="button" class="btn btn-primary myButtons">Abmelden</button>'
}
else{
document.getElementById("loginButtons").innerHTML =
'<button id="regBtn" type="button" class="btn btn-primary myButtons" >Registrieren</button>'+
'<button id="loginBtn" type="button" class="btn btn-primary myButtons" onclick="location="warungyoga.de/login.php"" >Anmelden</button>'
}
When the user clicks the Button, it should just lead to the page without any url parameters.

You'll need to wait on setting up the click event listener until the document is ready. This is because the element you want to set up with an event listener is created dynamically after page load (rather than being part of the initial html) and isn't immediately ready.
To wait for the document to be ready, wrap that portion of code in:
$( document ).ready(function() { /* code here */ });
Alternatively, you could listen for clicks on the document with a selector for the specific element as the first parameter:
$(document).click("#loginBtn",function(){ ...
Some other lil' bugs:
You seem to be missing a comma (See the line url:'login.php').
There's no need for a "onclick" attribute when setting up event listeners with jquery.

There's no need to use Javascript here, you can just set up a basic PHP conditional statement to display a different link depending on if the user is logged in or not:
<?php
$loggedIn = $_SESSION["loggedin"];
if ($loggedIn == 1) {
echo '<a id="loginBtn" class="btn btn-primary myButtons" href="/logout.php">Ausloggen</a>';
} else {
echo '<a id="loginBtn" class="btn btn-primary myButtons" href="/login.php">Anmelden</a>';
}
?>

What are you doing :D
`
// If user logged set session id
if(isUserLogged($email, $pass) > 0){
// Set user id
$_SESSION['user']['id'] = 1;
}
if($_SESSION['user']['id'] > 0){
// user logged
echo 'LogOut';
}else{
echo 'LogIn';
}
?>

Related

Javascript - append returned call_id to button

Hi everyone i have a problem with opening modal with javascript. I'm trying to open modal with returned data from jquery function. I can explain with examples:
My javascript code:
function (data) {
$.ajax({
type : 'POST',
url : '<?php echo site_url('home/check_call/'); ?>',
success : function(data){
if (data.calls == 200 && $('#re-calling-modal').length == 0 && $('#re-talking-modal').length == 0) {
if ($('#calling-modal').length == 0) {
$('body').append(data.calls_html);
if (!$('#re-calling-modal').hasClass('calling')) {
$('#re-calling-modal').modal({
show: true
});
PlayVideoCall('play');
}
}
}
}
and at this line appending data from response (response "calls_html" includes in_call.php modal page):
$('body').append(data.calls_html);
in_call.php file:
<div class="modal-footer" >
<button data-href="#" type="button" onclick="AnswerCall(' ###CALL ID HERE### ', '<?php echo site_url('call/'); ?> ###CALL ID HERE### ');"> Answer</button>
<button type="button" onclick="DeclineCall(' ###CALL ID HERE### ')"> Decline</button>
</div>
ajax response includes call_id. I want to apend call id to : onclick="DeclineCall(' ###CALL ID HERE### ')"
How can I add this?
P.S: Sorry my bad english :)
I would first make your button easier to find by adding an ID if possible. Then your success callback you can do:
$("button#someId").attr("onclick", "DeclineCall(' ###CALL ID HERE### ')")
This should set the attribute "onclick" for your button. But maybe you want to just observe the event in JS completely:
$("button#someId").click(function(){ DeclineCall("callid"); });

jquery function is being called more than once on single click

I am having more than one button with same class name and different id. but when I click on button, it's called for more than one everytime. for information about code in action, please see the video : https://nimb.ws/3RMoNP
Here is my code
$(document).on("click", ".delete_attachment_confirmation", function(e){
e.preventDefault();
var attachment_id = $(this).data('attachmentid');
$('#delete_attachment_confirmation_'+attachment_id).attr("disabled", true);
$('#delete_attachment_confirmation_'+attachment_id).text("Deleting file");
$.ajax({
url: "<?php echo base_url('attachment/delete_attachment/')?>"+$(this).data('attachmentid'),
type: "GET",
dataType: "text",
success: function(data){
$("#row_"+attachment_id).remove();
$("#attachment_message_body").text(data);
$('#delete_attachment_'+attachment_id).modal('hide');
// attachment message
$('#attachment_message').modal('show');
// modal issue removal trick
$('.modal-backdrop').removeClass('modal-backdrop');
}
});
});
<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?>
updated button code
<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?>
Highlighted part is showing us that ajax function is being called more than once.
There is nothing in above JS code that is causing it run twice, just that button does not have closing tag and multiple buttons without closing tags and having same class may be the reason, i just ran your code in codepan and it is running fine.
<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?></button>
https://codepen.io/balramsinghindia/pen/OJLzjbo
I have used solution provided in this question.
Ajax, prevent multiple request on click
$(".classNamw").unbind().click(function() {
//Your stuff
})

Javascript working on console, but not onclick event

I'm fairly new with JavaScript, I'm trying to give access to users to update products stock for WooCommerce. I've made "Update" button to run the script, but it won't run, the page only refreshes. But when I execute the script from console, it works (eg. js_update_stock('20');)
I'm working by modifying existing plugin for WordPress, so I'm sorry if the codes are a bit scattered. If you need anything else, please let me know.
HTML side of things:
<input type="number" id="stock'. $postid . '" name="stock'. $postid .'" value="'. get_post_meta( $postid, '_stock', true ) .'">
<button class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>
I put this script on the same page:
echo '<script type="text/javascript">
function js_update_stock(product_id) {
var isnum = /^\d+$/.test(document.getElementById("stock" + product_id).value);
if(isnum){
if(confirm("Do you really want to update the stock of this product?")){
var data = {
action: \'update_stock\',
security: \'' . $ajax_nonce . '\',
id: product_id,
stock: document.getElementById("stock" + product_id).value
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
if(response == \'true\'){
location.reload(true);
}
});
}
else{
// do nothing
}
}
else{
alert("Please enter a valid stock quantity");
}
}
</script>';
AJAX Callback function:
add_action('wp_ajax_update_stock', 'update_stock_callback');
function update_stock_callback() {
check_ajax_referer( 'blahblah', 'security' );
if(isset($_POST['id'])){
$id = intval( $_POST['id'] );
$stock = intval( $_POST['stock'] );
wc_update_product_stock( $id, $stock );
echo 'true';
}
else{
echo 'false';
}
die(); // this is required to return a proper result
}
Any help is appreciated, as this has been bugging me for 2 days now. Thank you.
By default a button is of type submit so it's submitting your form, thats why your page refreshes.
You want to define button type as button so form doesn't submit.
<button type="button" class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>
The page is refreshing because I guess the button you are using is in a form. So when you click on it, it will launch the request for the form and leave the page.
So to prevent that, you will just need to add the click event to your function and cancel it before the page has unload :
<button class="button button-primary"
style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;"
onclick="js_update_stock(event, \''. $postid .'\')">
'. __('Update','update_button') .'
</button>
And for javascript :
function js_update_stock(e, product_id) {
e.preventDefault();
// more code...
Javascript event prevent default on W3schools
I hope this solved your problem ;)
For most of the new browsers, default type of button element is "Submit".
That means, when click on it, your form will get submitted before calling your "onclick" function. Also, in your form you may not have specified action attribute, and that's why form is submitting to self.
You can specify type attribute for your button element to "button" specifically and it will now call to your "onclick" function.
For more information on button default type according to browser, visit :
What is the default button type?
Instead of button tag, you can use :
<a href='javascript:void(0);' id='updateBtn' class='btn btn-default'>Update</a>
$(document).ready(function () {
$('#updateBtn').on('click', function () {
// Make AJAX call here.
// Your logic will come here.
$.ajax({
url: 'Add url here',
data: 'Add data which is need to be update in json',
type: 'POST',
dataType: 'json',
success: successCallback,
complete: completeCallback,
error: errorCallback
})
});
var successCallback = function () {
// AJAX success callback
}
var completeCallback= function () {
// AJAX complete callback
}
var errorCallback= function () {
// AJAX error callback
}
});
NOTE: Also make sure you are not redirecting from backend(PHP) and just giving back response with statusCode.

Update view without page refresh in Ajax

I have the following code which runs when a button is clicked.
$.ajax({
type: "POST",
url: base_url+"/controller/method",
data: {val: value},
success: function(data){
data = jQuery.parseJSON(data);
if(data.status === true){
show_notify_message("Success",data.msg,'success');
} else {
show_notify_message("Error",data.msg,'error');
}
}
});
HTML Code:
<button class='btn btn-xs alert-success' onclick='method(1)'><font color='black'>Take</font></button>
Once the changes are made the entire page refreshes and the updated values are seen in the view.
How can I perform the same action without the entire page refreshing?
try it this way
HTML code
<button class='btn btn-xs alert-success' data-method='1'><font color='black'>Take</font></button>
JQuery script
$(document).ready(function(){
$("[data-method]").click(function(event){
event.preventDefault();
//value from the button
value=$(this).data("method");
// ajax call
});
});
if you use a <button> element, set it's type to "button" like this:
<button type="button">Click Me</button>
for some reason the default type is "submit"

Posting Javascript variable to PHP document

I want to get the value of data-id in my tag and transfer it to a PHP variable.
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
I already got the value of data-id using the javascript below and placed it into a variable, however its not posting on the page.
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid});
});
I tried doing this...
print_r($_POST);
but the array being displayed is empty What am I doing wrong here? Kinda new at this.
If you're trying to post on the same page (which is a bad idea anyway), you should have always have an exit/die; on that PHP catch block, and a success function callback on the $.post.
Example:
Simulated JS:
<?php $adminid = 1; ?>
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid}, function(response){
console.log(response);
});
});
</script>
Here on the PHP (same page):
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
}
Or
if(isset($_POST['admin_to_pass'])) {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
// you must have this or you'll catch the whole document
}
And since in your current code you don't have one, you need the success callback function to process the response which came from the server:
$.post("index.php", {admin_to_pass: adminid}, function(response){
^^^^
console.log(response); // your response from the server is inside (you can name it any name you want)
});

Categories

Resources