I have a button, when pressed has to call a function from an external php file and load it in a new page.
When I click the "SHOW" button on my index.php page, it shows me the message hold in "mesaj", but displays it in index.php page (that I don`t want!).
What I want to accomplish is when I click on the "SHOW" button on my index.php it shows me the content of the message into another php page, named - for eg - content.php. I want to set the href.
index.php
<input type = "button" class="btn btn-primary" id = "show" onClick = "show()" value = "SHOW"/>
functions.php
function show()
{
database();
$sql = "SELECT title FROM `Articles`";
$titleSql = mysql_query( $sql ) or die("Could not select articles:");
$html = '<html><body><div class="container"><h2>Basic List Group</h2><ul class="list-group">';
while ($title = mysql_fetch_array($titleSql)) {
$html .= '<li class="list-group-item">'.$title["title"].'</li>';
}
$html .= '</ul></div></body></html>';
echo $html;
//die(json_encode(array("mesaj" => "Entered data successfully ")));
}
function.js
function show(){
var n = $('#show').val()
$.post("functions.php", {show:n}).done(function(mesaj){
//$(document).html(mesaj);
document.write(mesaj);
});
}
There is no reason (apparently) to go from PHP to JS in your case. You'd use JS $.post if you need a change of the DOM after it loaded. You can just do this:
<a href="function.php" class="btn btn-primary" id="show"/>SHOW</a>
This works without going thru JS.
If you want to use BUTTON and go via JS then do this:
<input type="button" class="btn btn-primary" id="show" value="SHOW"/>
jQuery:
$('#show').click(function(e){
e.preventDefault();
window.location.href = 'function.php';
});
Plain JS:
document.getElementById("show").onclick = function(){
window.location.href = 'function.php';
}
As a note, be careful because <button> if used inside a form when clicked submits the form. That's why the e.preventDefault();
Let's say you have multiple functions in your function.php and you need to call one a specific one, I would do this:
function.php
if(isset($_GET['fn1'])){
function functionOne(){
//do something
}
}
if(isset($_GET['fn2'])){
function functionTwo(){
//do something else
}
}
And call it this way:
<a href="function.php?fn1" class="btn btn-primary" id="show"/>SHOW</a>
or
$('#show').click(function(e){
e.preventDefault();
window.location.href = 'function.php?fn1';
//window.location.href = 'function.php?fn2';
});
Related
I am creating an shopping page in which I have many Items that are displayed dinamically from database. I want to be able to add
product in cart without refreshing the page,
I want to know how to submit in javascript and be able to get that expecific data-id.
Normally I would just create a a href and pass product_id as a variable in the URL and then use php to manipulate the variable
<?php
$all_products = all_products();
echo '<div class="products">';
foreach($all_products as $key => $data){
echo '<div class="single-product">
<img src="'.$data['src'].'">
<h3>'.$data['name'].'</h3>
<h4>'.$data['price'].'</h4>
<button type="submit" class="addToCart" data-id="'.$data['product_id'].'">Add to cart</button>
</div>
';
}
echo '</div>';
?>
<script>
let addToCart = document.getElementsByClassName('addToCart');
addToCart.addEventListener("submit",(e)=>{
//let id = e.querySelector(data-id);
})
</script>
UPDATE
Thank you #M.Eriksson for your sugestion, I found online this, so if I replace the button with a href and pass javascript function add_to_cart() with product_id inside the variable I can access that variable in javascript using console.log, and I can get the id dinamically, however, I need to manipulate the id and send it using xmlhttpRequest, but it is giving status = 0, I dont see any mistakes in the sintax, and I used the same xmlhttpRequest in other page to request products from server and works
<?php
$all_products = all_products();
echo '<div class="products">';
foreach($all_products as $key => $data){
echo '<div class="single-product">
<img src="'.$data['src'].'">
<h3>'.$data['name'].'</h3>
<h4>'.$data['price'].'</h4>
<a ref="javascript:add_to_cart('.$data['product_id'].')">Add to cart</a>
</div>
';
}
echo '</div>';
?>
<script>
add_to_cart();
function add_to_cart(product_id=1){
console.log(product_id);
let form_data = new FormData();
form_data.append('product_id', product_id);
let url_data ="php/add_to_cart.php";
let ajax_request = new XMLHttpRequest();
ajax_request.open('POST', url_data);
let status1 = ajax_request.status;
console.log(status1);
ajax_request.onload = function(){
//console.log(ajax_request.responseText);
if(status1 == 200){
let output = JSON.parse(this.response);
//display product added sucessfully
let added_successfully = document.getElementById('added_successfully');
added_successfully.innerHTML=output['success'] ;
}
}
ajax_request.send(form_data);
}
</script>
what i would do is to change the button type to button aka: <button type="button">Button</button>
And after that change the EventListener to click and get the target from the event to access the data.
after which you can call a php script from javascript by using the fetch function which will send a HTTP request to your backend server.
eg: (untested)
<button type="button" class="addToCart" data-id="some data">Add to cart</button>
<script>
let buttonsList = document.getElementsByClassName('addToCart');
for (button of buttonsList) {
button.addEventListener("click",(e)=>{
fetch('/path/to/your/product/api?product_id=' + e.target.getAttribute('data-id')).then((data) => {
console.log('product added to cart!')
})
})
}
</script>
Hope this helps :-)
So I have this PHP page, with at the start some unimportant stuff and a session opening :
<?php
session_start();
?>
I want the disconnect button to appear only if the user is already connected, which means that $_SESSION['Pseudo'] is set. If this is the case, I create a button, and bind to that button a function to destroy the session. The problem is, each time I go on this page, the session is destroy, even though it's in a condition.
Here's my code :
<?php
if (isset($_SESSION["pseudo"])) {
echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>
<script>
let btn = document.getElementById('deco');
if (btn) {
btn.addEventListener('click', updateBtn);
function updateBtn() {
<?php
session_destroy();
?>
window.location.href = "/"
}
}
</script>
Any clue ?
You cannot combine PHP within Javascript like that.
When you're doing , it's not a part of the Javascript. It's PHP code and is executed as part of the PHP code in the file.
This means that it has nothing to do with the javascript aspect. your updateBtn function is effectively, when the page source code loads:
function updateBtn() { window.location.href = "/" }
What you really want to do is make it so that when someone clicks the button, it takes them to a logout page or a page with a logout query param.
eg.
<?php
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
session_destroy();
echo 'You have successfully logged out!';
}
if (isset($_SESSION["pseudo"])) {
echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>
<script>
let btn = document.getElementById('deco');
if (btn) {
btn.addEventListener('click', updateBtn);
function updateBtn() {
window.location.href = "/?action=logout"
}
}
</script>
I have been working on Like and Unlike feature with jQuery, AJAX and PHP. I am getting jQuery post request from indirect page. For example I have 2 PHP pages, viewProfile.php and LikeMail.php. LikeMail.php is being called by AJAX function in viewProfile.php.
Here is Section of viewProfile.php page's description
-----------------
| Like/Unlike |
-----------------
Here is button which actually comes from LikeMail.php by this AJAX function:
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('like1').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
HTML:
<div id="like1"></div>
Output is being shown here in this div. Button above may be Like or Unlike depends on the condition in LikeMail.php which will be described below in LikeMail.php description section.
When one of them (buttons) Like or Unlike is clicked. It then calls respective jQuery click function which sends post request to LikeMail.php.I have mentioned Indirect page in title because Like or Unlike buttons actually exists in LikeMail.php page. But due to AJAX call these buttons are being shown in viewProfile.php page. So I then send post requests through viewProfile.php to actual page LikeMail.phpIt is jQuery post for Unlike button
$(document).ready(function(){
$('#Unlike').unbind().click(function(){
$.post("LikeMail.php",
{Unlike: this.id},
function(data){
$('#response').html(data);
}
);
});
});
It is jQuery post or Like button
$(document).ready(function(){
$('#Like').unbind().click(function(){
$.post("LikeMail.php",
{Like: this.id},
function(data){
$('#response').html(data);
}
);
});
});
End of description section of viewProfile.php page
Here is Section of LikeMail.php page's description
Like or Unlike button is shown in viewProfile.php page depends upon this code:
$check_for_likes = mysqli_query($conn, "SELECT * FROM liked WHERE user1='$user1' AND user2='$user2'");
$numrows_likes = mysqli_num_rows($check_for_likes);
if (false == $numrows_likes) {
echo mysqli_error($conn);
}
if ($numrows_likes >= 1) {
echo '<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">';
}
elseif ($numrows_likes == 0) {
echo '<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">';
}
Button depends upon these two above conditions.
Now when Like button is clicked, post request from viewProfile.php comes here.
if(isset($_POST['Like'])) //When Like button in viewProfile.php is clicked then this peace of code inside if condition should run and insert some record in database
{
$total_likes = $total_likes+1;
$like = mysqli_query($conn, "UPDATE user SET user_Likes = '$total_likes' WHERE user_id = '$user2'");
$user_likes = mysqli_query($conn, "INSERT INTO liked (user1,user2) VALUES ('$user1','$user2')");
$query3 = "INSERT INTO notification (user1, user2, alert, notificationType) VALUE ('$user1','$user2','unchecked','like')";
if (mysqli_query($conn, $query3)) {
echo "Like";
} else {
echo mysqli_error($conn);
}
}
Similarly when Unlike button is clicked. This peace of code should run.
if(isset($_POST['Unlike'])) //This is the condition for Unlike button. It should delete record from databse
{
$total_likes = $total_likes-2;
$like = mysqli_query($conn, "UPDATE user SET user_Likes='$total_likes' WHERE user_id='$user2'");
$remove_user = mysqli_query($conn, "DELETE FROM liked WHERE user1='$user1' AND user2='$user2'");
$query3 = "DELETE FROM notification WHERE user1='$user1' AND user2='$user2' AND notificationType='like'";
$check = mysqli_query($conn, $query3);
if ($check) {
echo "Unlike";
} else {
echo mysqli_error($conn);
}
}
Problem:
Main problem is that jQuery post request is not being sent from viewProfile.php to LikeMail.php. Is there any way to send jQuery post request from indirect page?
I'm trying stop multiple submit buttons.I'm new to php and javascript.I did try lot of different options of stack overflow answers.I did check session token but it is not working for me because i'm submitting the form from JavaScript.You can see the code to disabled button . When i click the button it is disabled and form submited but it is not reaching the btn-paid code of php. Please help.
php code1:
<?php
include('sessionstart.php');
include('session.php');
include('processtransaction.php');
?>
<script src="js/mytransaction.js"></script>
php code1 will call the javascript and javascript has the form submit. If the form is submitted then it disable/(session token process) the button paid and it should call the code of btn-paid.
javascript code mytransaction:
$(document).ready(function() {
var table = $('#myTransactionitems').dataTable(); //Initialize the datatable
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'transactions',
dataType: 'json',
success: function(s){
console.log(s);
table.fnClearTable();
for(var i = 0; i < s.length; i++) {
var disp1 = '';
if (s[i][4] != 'Reserved') {
disp1 = 'display:none;'
}
table.fnAddData([
"<form method='post' action='reservationdetails'><input name = 'transactionid' type='hidden'\
value='"+s[i][0]+"'></input><input type='submit' id = 'btn-bank' name='btn-bank' value = '"+s[i][0]+"' class='btn btn-link'>\
</input></form>",
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
"<form method='post'><input name = 'transactionid' type='hidden'\
value='"+s[i][0]+"'><input name = 'donationid' type='hidden'\
value='"+s[i][2]+"'><input name = 'splitamount' type='hidden'\
value='"+s[i][3]+"'></input></input><input type='submit' id = 'btn-paid' name='btn-paid' value = 'Paid' onclick='this.disabled=true;this.form.submit();' style='" + disp1 +"' class='btn btn-sm btn-success pull-left '>\
</input></form><form method='post'><input name = 'transactionid' type='hidden'\
value='"+s[i][0]+"'><input name = 'donationid' type='hidden' \
value='"+s[i][2]+"'><input name = 'splitamount' type='hidden'\
value='"+s[i][3]+"'></input><input type='submit' id = 'btn-cancel' name='btn-cancel' value = 'Cancel' onclick='this.disabled=true;this.form.submit();' style='" + disp1 +"' class='btn btn-sm btn-danger pull-right'>\
</input></form>"
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
php code2 processtransaction:
<?php
if (isset($_POST['btn-paid'])) {
require_once("dbcontroller.php");
$db_handle = new DBController();
$conn = $db_handle->connectDB();
$query = "update MYTRANSACTION set STATUS =? where DONATION_ID=? AND ID=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("sii",$status,$donation_id, $transaction_id);
$stmt->execute();
$stmt->close();
$db_handle->closeDB($conn);
}
?>
If you want to prevent the user from clicking twice before page ends loading (causing 2 posts), it would better to use javascript. As you are already using jQuery, you can do the following:
$("input[type='submit']").click(function(e) {
e.preventDefault(); // Prevent the page from submitting on click.
$(this).attr('disabled', true); // Disable this input.
$(this).parent("form").submit(); // Submit the form it is in.
});
Edit:
To cater for someone immediately submitting before page loads completely (ie before JS loads), you can make the following changes.
In your HTML form, add disabled to your submit button:
<input type="submit" value="Submit" disabled />
And change your JS to the following:
$("input[type='submit']").attr('disabled', false); // Enable this input.
$("input[type='submit']").click(function(e) {
e.preventDefault(); // Prevent the page from submitting on click.
$(this).attr('disabled', true); // Disable this input.
$(this).parent("form").submit(); // Submit the form it is in.
});
What this does is makes the submit button disabled until JS has loaded. Once JS loads, it will enable the submit button and then remaining things will work as before.
I have a javascript function that is triggered when a button is pressed. That function loads an external page with the values of a field.
My problem is that when I refresh the page my clicked button is reset. What I want is to keep that button value when it refreshes so it still loads that page and only reset when another button is pressed.
js code
<script>
$(function() {
$("button.btn").click(function() {
var tip = document.getElementById("tip5").value;
var id_local = document.getElementById("id_local").value;
$("#tipuri_rezervare").load("select_tip_rezervare.php?id=" + id_local + "&tip=" + tip);
});
});
</script>
php code
$stmt = $dbh->prepare("SELECT *
FROM Tip_Rezervare
INNER JOIN Local ON Local.ID_Local=:id_local
INNER JOIN Leg_Tip_Local ON Tip_Rezervare.ID_Tip=Leg_Tip_Local.ID_Tip and Leg_Tip_Local.ID_Local=:id_local");
$stmt->bindParam(':id_local', $id, PDO::PARAM_INT);
$stmt->execute() ;
while ($row = $stmt->fetch()) {
$local = $row['Denumire_Local'];
echo'<button type="button" class="btn btn-danger" id="tip'.$row['ID_Tip'].'" value="'.$row['ID_Tip'].'">'.$row['Nume'].'</button>';
}
?>
</div>
<form id="tip" method="post">
<input type="hidden" name="id_local" id="id_local" value="<?php echo $id;?>">
<div id="tipuri_rezervare"></div>
You need to make an Ajax call & set a session during the result fetch from external page but before page refresh and read the session values after page refreshed & set it on page.