Javascript - append returned call_id to button - javascript

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

Related

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

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';
}
?>

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.

Ajax function call not working

I am trying to learn Ajax function calls in jquery. But I could not get the expected output. My code is below
The HTML and Script File is stored in the file 'addevent.php'
HTML Code:
<form id="addinfo">
Year: <div class="styled-select">
<select id="year">
<option>2017</option><option>2018</option>
<option>2019</option><option>2020</option>
</select>
</div>
Team:<div class="styled-select">
<select id="team">
<option>UG</option><option>PG</option>
</select>
</div>
<button class=btn name="add_event" id="add_event" />Add Event
<span id="result"></span>
</form>
</body>
</html>
Script Part:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: 'checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
}
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
The code in the file checkevent.php is below
header("Content-Type: application/json", true);
$db = new PDO('mysql:host=localhost;dbname=register;charset=utf8mb4', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$year =$_POST['year'];
$team =$_POST['team'];
$table=$team.$year;
try
{
if ($db->query("SHOW TABLES LIKE '" . $table . "'")->rowCount() > 0)
{
$r=array("result"=>"already stored");
echo json_encode($r);
}
else
{
$r=array("result"=>"continue");
echo json_encode($r);
}
}//end of try
catch(PDOException $e)
{
$r=array("result"=>"error");
echo json_encode($r);
}//end of catch
?>
Please Note: I have stored the file 'addevent.php' (HTML+Script) in the location 'registration/view/'
The checkevent.php file is stored in the location 'registration'
I tried to check if the button click function for add_event button is working by placing an alert inside it. But it doesn't work.
My expected output is if the table exist the span should display 'already stored' else it should say 'continue'
P.S: I am new to using these ajax call,so sorry if this seems silly. Please help to understand these concepts clearly.
Thanks in advance
You change this line :
url: 'checkevent.php',
By this :
url: '../checkevent.php',
Type F12 and inspect your ajax Call in the console to see if everything is OK
EDIT
OK got it. You missed a comma between success and error callbacks, which broke your Javascript...
Please change script to this and it should work:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: '/registration/checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
},
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
You have a <button> element inside a form. The default type of a button is type="submit" and therefore the form is submitted before the button onclick listener works. Also you need to close a button element with </button>
Try to change it from
<button class=btn name="add_event" id="add_event" />Add Event
to
<button type="button" class=btn name="add_event" id="add_event" >Add Event</button>
As for the ajax URL, if you are running it from a page located in 'registration/view' and you're calling a page located in 'registration', you need to change the url to something like: url: '/registration/checkevent.php'
because the php file isn't located in the same place as the script that's calling it.
Good luck

click button execute php file then redirect

Good day to all,
Been searching all day on how to do this. What I want is to make every 'click' to go into one php file and determine what will be the action.
itemAction.php
include 'inc/database.php';
include 'inc/functions.php';
if ($_GET['action'] == 'delete') {
// do delete action <-- this one is working
} else if ($_GET['action'] == 'edit') {
// do edit action; NOW HERE I WANT TO REDIRECT TO ANOTHER PAGE
header("location: edit.php"); // I can't do something like this. Why?
}
html
<div class="action">
<a id="delete" href="itemAction.php" rel="<!--some_id-->"><img src="images/trash.ico" alt="delete"></a>
<a id="edit" href="itemAction.php" rel="<!--some_id-->"><img src="images/Pencil-icon.png" alt="edit"></a>
</div>
js
$("div.action a#delete").click(function (e) {
var decision = confirm("Are you sure you want to delete the item?");
if (decision) {
e.preventDefault();
$.get('itemAction.php', {action : 'delete', id : $(this).attr("rel")}, function (data) {
location.reload();
alert("Succssfully deleted!");
});
}
return false;
});
$("div.action a#edit").click(function (e) {
e.preventDefault();
$.get('itemAction.php', {action : 'edit', id : $(this).attr("rel")});
});
The delete action seems to be working.. But I can't do I want in the edit action which is to redirect to other page. What better ways are there to do it that way? Any help would be much appreciated. Thanks
You can not do this because ajax will only send you response html, text, xml or json response but can not do redirection.
For redirecting you must return anything say "redirectme." and based on that response you need to add code in javascript to redirect at desired location.
what you can do is?
in php file add below code,
echo json_encode(array('status' => 'edit', 'url' => 'edit.php'));
based on above response modify your $.get response callback as below.
$.get('itemAction.php', {action : 'delete', id : $(this).attr("rel")},
function (data)
{
if(response.status == 'edit'){
window.location = response.url;
}
});
it just a guide line you need set it according to your need.
Comment Response
if js is disabled then you need to code accordingly.
first of all you need to modify your html links as below,
<a id="delete" href="itemAction.php?action=delete&id=someid"
<a id="edit" href="itemAction.php?action=edit&id=someid"
and by clicking on above link use their href attribute to pass into $.get as below.
$.get( $(this).href()
by doing so it js is disabled your code will work too.
Have your button go somewhere
<form method="get" action="someScript.php">
<button>Do things</button>
</form>
Then in someScript.php
<?php
// do things
header("Location: redirectToHere.php");

Categories

Resources