onclick load function in php - javascript

I m have 2 my code and one work and when i use code 2 not work.
Javascript is still the same.
This is javascript and work
function addto(selid)
{
var i;
var item = "";
for (i = 0; i < 1000; i++) {
item = "incart_"+i;
if(getCookie(item) == "")
{
setCookie(item,selid,24);
break;
}
}
}
This code work
<button onclick='addto("1");' data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button >
but when i use php does not respond
// If i use the action in php it goes.
<button <?php echo "onclick='addto('".$row["id"]. "');'"; ?> data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button>

Use PHP only on the dynamic part:
<button onclick="addto('<?= $row['id'] ?>')" data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"></i></button>

You have an escaping issue, you can either echo the whole button and use proper escaping on the quotes, or just echo the dynamic part
Echo just the dynamic part (best option)
<button onclick="addto('<?php echo $row["id"]; ?>')" data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button>
Echo the whole button
<?php echo '<button onclick="addto(\''. $row["id"] .'\')" data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button>'; ?>

Related

I am doing a Live Search and then on button click the page refreshes how do I prevent this?

I am working on a page where I can search for a name or surname and filter actively (this part works perfectly). Once I have found the relevant record I then need to be able to complete an action using one of four buttons related to the record. All of this needs to work without the page refreshing (I am therefore using ajax). if I do not search and click one of the four buttons it works perfectly and I get an alert at the top of the page without any refresh BUT when I do a search and try the page refreshes and therefore I do not get the alert at the top of the page and my search is cleared. I have made other submissions before and noone has helped me at all so I am really hoping that this time someone will be able to assist.
I have tried the solutions listed below:
Type=Button: for each of the buttons - the button does not work at all in the search option
With the above one I have tried including a submit action in the javascript - it still does not work
e.stopPropagation(): page still refreshes
using $_SESSION['msg']: doesn't show the alert for the non-search option and refreshes the page for the search option so my search is still cleared
My code is as follows:
The search page
<?php
include("includes/header.php");
if (isset($_GET['event_id'])) {
$event_id = $_GET['event_id'];
$event = new Event($con, $userLoggedIn);
$eventname = $event->getEventName($event_id);
$table = $event->getTableName($event_id);
$guest = new Guest($con, $userLoggedIn);
// echo "<script>console.log(" . $eventname . ")</script>";
}
$stmt = $con->prepare("SELECT * FROM " . $table);
$stmt->execute();
$result = $stmt->get_result();
?>
<div class="flex-container">
<div class="stats_details column">
**... code not related to the question**
</div>
<div class="main_column column">
<?php
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
} ?>
<div id="message"></div>
<hr>
<div class="form-inline">
<label for="search" class="font-weight-bold lead text-dark">Search Record </label>
<input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Search...">
</div>
<hr>
<div class="cards-list" id="table-data">
<?php while ($row = $result->fetch_assoc()) { ?>
<div class="card m-2">
<div class="card-header <?= $row['checkin_guests'] > 0 ? 'success' : 'deep_blue'; ?> text-muted">
Guests: <?= $row['total_guests']; ?> | Checkedin: <?= $row['checkin_guests']; ?>
</div>
<div class="card-body">
<div class="card-title h3"><i class="fas fa-user"></i> <?= $row['first_name']; ?> <?= $row['last_name']; ?></div>
<p class="card-text"><i class="fa fa-building" aria-hidden="true"></i> <?= $row['company']; ?></p>
<p class="card-text"><i class="fa fa-at" aria-hidden="true"></i> <?= $row['email']; ?></p>
<p class="card-text"><i class="fa fa-phone" aria-hidden="true"></i> <?= $row['phone']; ?></p>
</div>
<div class="card-footer default text-muted">
<form action="" method="POST" class="action_buttons">
<input type="hidden" class="gid" value="<?= $row['id']; ?>">
<button class="btn success checkin" data-toggle="tooltip" data-placement="top" title="Checkin"><i class="fas fa-user-check" aria-hidden="true"></i></button>
<button class="btn warning" data-toggle="tooltip" data-placement="top" title="Checkout" name="Checkout"><i class="fas fa-user-times" aria-hidden="true"></i></button>
<button class="btn info" data-toggle="tooltip" data-placement="top" title="Edit" name="Edit"><i class="fas fa-user-edit" aria-hidden="true"></i></button>
<button class="btn danger" data-toggle="tooltip" data-placement="top" title="Cancel" name="Cancel"><i class="fas fa-user-slash" aria-hidden="true"></i></button>
</form>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
var event = <?php echo $event_id; ?>;
//live search
$("#search_text").keyup(function() {
var search = $(this).val();
$.ajax({
url: 'action.php',
method: 'POST',
data: {
query: search,
event: event
},
success: function(response) {
$("#table-data").html(response);
}
});
});
//checkin
$(".checkin").click(function(e) {
e.preventDefault();
$("#message").html('');
var $form = $(this).closest(".action_buttons");
var gid = $form.find(".gid").val();
$.ajax({
url: 'action.php',
method: 'POST',
data: {
gid: gid,
checkin: 'checkin',
event: event
},
success: function(response) {
$("#message").html(response);
window.scrollTo(0, 0);
}
});
});
});
</script>
</body>
</html>
action.php
<?php
require 'config/config.php';
include("includes/classes/User.php");
include("includes/classes/Event.php");
include("includes/classes/Guest.php");
$userLoggedIn = $_SESSION['username'];
$event = new Event($con, $userLoggedIn);
$guest = new Guest($con, $userLoggedIn);
if (isset($_POST['query'])) {
$output = '';
$search = $_POST['query'];
$event_id = $_POST['event'];
$table = $event->getTableName($event_id);
$_SESSION['search'] = $search;
$stmt = mysqli_query($con, "SELECT * FROM `$table` WHERE first_name LIKE '%$search%' OR last_name LIKE '%$search%'");
if (mysqli_num_rows($stmt) > 0) {
while ($row = mysqli_fetch_assoc($stmt)) {
$checked_class = $row['checkin_guests'] > 0 ? "success" : "deep_blue";
$output .= '
<div class="card m-2">
<div class="card-header ' . $checked_class . ' text-muted">
Guests:' . $row['total_guests'] . ' | Checkedin: ' . $row['checkin_guests'] . '
</div>
<div class="card-body">
<div class="card-title h3"><i class="fas fa-user"></i> ' . $row['first_name'] . ' ' . $row['last_name'] . '</div>
<p class="card-text"><i class="fa fa-building" aria-hidden="true"></i> ' . $row['company'] . '</p>
<p class="card-text"><i class="fa fa-at" aria-hidden="true"></i> ' . $row['email'] . '</p>
<p class="card-text"><i class="fa fa-phone" aria-hidden="true"></i> ' . $row['phone'] . '</p>
</div>
<div class="card-footer default text-muted">
<form action="" method="POST" class="action_buttons">
<input type="hidden" class="gid" value="' . $row['id'] . '">
<button class="btn success checkin" data-toggle="tooltip" data-placement="top" title="Checkin"><i class="fas fa-user-check" aria-hidden="true"></i></button>
<button class="btn warning" data-toggle="tooltip" data-placement="top" title="Checkout"><i class="fas fa-user-times" aria-hidden="true"></i></button>
<button class="btn info" data-toggle="tooltip" data-placement="top" title="Edit"><i class="fas fa-user-edit" aria-hidden="true"></i></button>
<button class="btn danger" data-toggle="tooltip" data-placement="top" title="Cancel"><i class="fas fa-user-slash" aria-hidden="true"></i></button>
</form>
</div>
</div>
';
}
echo $output;
} else {
echo "<h3>No Records Found</h3>";
}
}
if (isset($_POST['checkin'])) {
$event_id = $_POST['event'];
$table = $event->getTableName($event_id);
$gid = $_POST['gid'];
$result = $guest->checkin($event_id, $gid);
/* $_SESSION['msg'] = '<div class="alert alert-success alert-dismissible mt-2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Guest ' . $gid . ' Checked In Successfully in ' . $table . ' response: ' . $count . '</strong>
</div>'; */
echo $result;
}
?>
The guest checkin class
public function checkin($event_id, $id) {
$table= $this->event_obj->getTableName($event_id);
$guest_list_query = mysqli_query($this->con, "SELECT checked, checkin_guests FROM " . $table ." WHERE `id`='$id'");
//echo "<script>console.log(" . $table . ")</script>";
$count = mysqli_num_rows($guest_list_query);
//echo "<script>console.log(" . $count . ")</script>";
/* $_SESSION['msg'] = '<div class="alert alert-success alert-dismissible mt-2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Guest ' . $id . ' Checked In Successfully in ' . $table . ' response: ' . $count . '</strong>
</div>'; */
echo '<div class="alert alert-success alert-dismissible mt-2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Guest ' . $id . ' Checked In Successfully in - response rows: ' . $count . '</strong>
</div>';
}
what i get from your explanation is, $(".checkin").click not work after you do a search, its because javascript only work once, when all page finish loaded.
when you do search, a new button will appear and javascript not called again to give button check in onclick, thats why your button on click not working.
so i suggest you to using solution no. 1 Type=Button: for each of the buttons
copy your javascript $(".checkin").click, document ready and other function/include that need to copy to make checkin click work to action.php
example: copy this to action.php
<script type="text/javascript">
$(document).ready(function() {
var event = <?php echo $event_id; ?>;
//checkin
$(".checkin").click(function(e) {
e.preventDefault();
$("#message").html('');
var $form = $(this).closest(".action_buttons");
var gid = $form.find(".gid").val();
$.ajax({
url: 'action.php',
method: 'POST',
data: {
gid: gid,
checkin: 'checkin',
event: event
},
success: function(response) {
$("#message").html(response);
window.scrollTo(0, 0);
}
});
});
});
</script>
or
still using solution no 1 type button, then make your javascript onclick as function outside document ready then make button onClick (action.php and search page) to call that function
} -> end document ready
function checkinButton(){
var $form = $(this).closest(".action_buttons");
var gid = $form.find(".gid").val();
$.ajax({
url: 'action.php',
method: 'POST',
data: {
gid: gid,
checkin: 'checkin',
event: event
},
success: function(response) {
$("#message").html(response);
window.scrollTo(0, 0);
}
});
}
Button:
<button onClick="checkinButton()" class="btn success checkin" data-toggle="tooltip" data-placement="top" title="Checkin"><i class="fas fa-user-check" aria-hidden="true"></i></button>

How can I pass a form value to another page when ID is inside <span>?

I have a website that has info on some people, like name, social security number and birthday. When the user clicks a button, it redirects them to https://meu.inss.gov.br/central/index.html#/agenda. What I need to do is fill out the fields "CPF" and "Data de Nascimento" in this site.
My issue is that the IDs for CPF ("ident-cpf") and Data de Nascimento ("ident-data-nascimento") are inside a "span" tag and a "div" with three diferent states. A few weeks ago, I solved a similar problem, but it was on my website, where I could pass these values through the url, like "'www.website.com/page.php?&id-name="."$name'", for example. I can't (I probably don't know) how to do that in the government website.
Right now, my code is pretty simple:
for($i = 0; $i < count($vet); $i++){
echo '<tr>';
for($j = 0; $j <count($colunas); $j++){
if ($j == 6 || $j == 9)
echo "<td><span class='hide'>".$vet [$i][$j]. "</span>".date("d/m/Y", strtotime($vet [$i][$j]))."</td> ";
elseif ($j == 11){
$abre = "'https://www2.dataprev.gov.br/sabiweb/relatorio/imprimirCRER.view?acao=imprimir_CRER&nuBeneficioRequerimento=".$vet[$i][11]."&dataNascimento=".$vet[$i][12]."&nomeRequerente=".$vet[$i][2]."&cpf=".$vet[$i][4]."'";
$abre2 = "'https://meu.inss.gov.br/central/index.html#/agenda'";
echo '<td><a data-placement="top" data-toggle="tooltip" title="Consultar"><button font-size:10px;" class="copiar btn btn-primary btn-xs " onClick="window.open(' . $abre2 . ')" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil">Meu INSS</span></button></a>
<a data-placement="top" data-toggle="tooltip" title="Consultar"><button font-size:10px;" class="copiar btn btn-primary btn-xs " onClick="window.open(' . $abre . ')" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil">Data Prev</span></button></a></td>';
$abre is ok, because I can get the data from the arrays and then pass to the other website through the URL.
With $abre2, I don't know how to do that, but the data would be pretty much the same.

MVC Patern structure (Where and How?)

I have been learning programming online for like 3 years. I have developed big project in this time, but I have a problem. I didn't know about MVC pattern and was how to say "Programming from scratch". Right now my code is a big mess, that no one can understand, but only me..
I found out about this MVC pattern and it's a excellent thing but right now I can't understand where and how to make couple of things. How I understand that no php code goes to view? And no html/css into model.
For example in which structure I have to implement my javascript and ajax code? (Is it view?)
Where and how to manage displaying if's? Like:
if($user_id == $me){
//display post with delete option
}else{
//display post
}
I have a functions with houndreds of lines and if's. For example one of my functions. I want to understand how to reproduce it in MVC pattern.
public function selectUserPosts(){
try{
require_once('Class.Users.php');
$user = new USER();
$id = $_GET['id'];
$stmt = $this->conn->prepare("SELECT * FROM fun_posts WHERE addedby=('$id') ORDER BY date DESC");
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $post){
?>
<div class="col-sm-4">
<div class="animated flipInY" id="panel_<?php echo $post['id'];?>">
<div class="thumbnail" style="height:300px;">
<a href="/Web/Pages/Fun/Fun_Post.php?action=select&image_id=<?php echo $post['id'];?>" target="_blank">
<img class="img" style="width: 100%; height:150px;" src="<?php echo $post['image']; ?>" alt="" />
</a>
<i class="fa fa-clock-o" aria-hidden="true"></i><?php echo $user->time_elapsed($post['date']); ?>
<div id="upvote_<?php echo $post['id'];?>" class="panel">
<i class="fa fa-arrow-circle-up" style="font-size:22px; margin-top:10px;"></i> <b id="upvote_panel_<?php echo $post['id'];?>"><?php echo $post['upvotes']; ?></b>
<button style="float:right; margin-top:5px; width:90px;" class="btn btn-sm btn-success" type="submit"><i class="fa fa-arrow-circle-up"></i> Upvote</button>
</div>
<div id="downvote_<?php echo $post['id'];?>" class="panel">
<i class="fa fa-arrow-circle-down" style="font-size:22px; margin-top:-5px;"></i> <b id="downvote_panel_<?php echo $post['id'];?>"><?php echo $post['downvotes']; ?></b>
<button style="float:right; margin-top:-10px; width:90px;" class="btn btn-sm btn-danger" type="submit"><i class="fa fa-arrow-circle-down"></i> Downvote</button>
</div>
<div id="comment_<?php echo $post['id'];?>" class="panel">
<i class="fa fa-comment" style="font-size:22px; margin-top:-10px;"></i> <b id="comment_panel_<?php echo $post['id'];?>"><?php echo $post['comments']; ?></b>
<a href="/Web/Pages/Fun/Fun_Post.php?action=select&image_id=<?php echo $post['id'];?>" target="_blank">
<button style="float:right; margin-top:-13px; width:90px;" class="btn btn-sm btn-primary" type="submit"><i class="fa fa-comment"></i> Comment</button>
</a>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
$("#upvote_<?php echo $post['id'];?>").click(function(){
$.ajax(
{ url: "Home.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>",
type: "get",
success: function(result){
$('#upvote_panel_<?php echo $post['id'];?>').load(document.URL + ' #upvote_panel_<?php echo $post['id'];?>');
$('#downvote_panel_<?php echo $post['id'];?>').load(document.URL + ' #downvote_panel_<?php echo $post['id'];?>');
$('#comment_panel_<?php echo $post['id'];?>').load(document.URL + ' #comment_panel_<?php echo $post['id'];?>');
document.getElementById('result-box').innerHTML += result;
}
});
});
$("#downvote_<?php echo $post['id'];?>").click(function(){
$.ajax(
{ url: "Home.php?downvote-btn=true?action=select&image_id=<?php echo $post['id'];?>",
type: "get",
success: function(result){
$('#upvote_panel_<?php echo $post['id'];?>').load(document.URL + ' #upvote_panel_<?php echo $post['id'];?>');
$('#downvote_panel_<?php echo $post['id'];?>').load(document.URL + ' #downvote_panel_<?php echo $post['id'];?>');
$('#comment_panel_<?php echo $post['id'];?>').load(document.URL + ' #comment_panel_<?php echo $post['id'];?>');
document.getElementById('result-box').innerHTML += result;
}
});
});
});
</script>
<?php
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
MVC - Model View Controller
1) In the Model you have to place all logic and work with databases and other services
2) In the View you have to place code, that will see user (you can't call logic methods or functions those use services like database in there)
3) And Controller have to connect Model and View together. And, of course, it have to be as route manager

jQuery Hide Div of associated PHP MySQL results in While Loop

Having an issue. I need to remove the associated element on the click of a button from a list of results provided by a MySQL query. Only the first image is being hidden on the click of the remove button. The rest of the images returned do nothing.
Here is my code :
PHP:
<?php
while ($image_row = mysqli_fetch_array($image_result)) { ?>
<span class="listing_image_preview" id="image_<?php echo $image_row['id']; ?>">
<img src="<?php echo $image_row['image_thumb']; ?>" style="border:6px solid #EEE; margin:6px;" />
<button id="remove_image" class="btn btn-default btn-xs" imageId="<?php echo $image_row['id']; ?>">Remove</button>
</span>
<?php
}
?>
jQuery:
$(document).ready(function() {
$("#remove_image").click(function() {
var image_id = $(this).attr('imageId');
$('#image_'+image_id).hide();
})
});
All your buttons have the same id:
<button id="remove_image"
And your jquery script will only find one element with the following selector:
$("#remove_image")
Here's one way to solve it:
Add remove_on_click to the button's class (I also made the id's unique)
<?php
while ($image_row = mysqli_fetch_array($image_result)) { ?>
<span class="listing_image_preview" id="image_<?php echo $image_row['id']; ?>">
<img src="<?php echo $image_row['image_thumb']; ?>" style="border:6px solid #EEE; margin:6px;" />
<button id="remove_image_<?php echo $image_row['id']; ?>" class="btn btn-default btn-xs remove_on_click" imageId="<?php echo $image_row['id']; ?>">Remove</button>
</span>
<?php
}
?>
In your jquery script select on class remove_on_click:
$(document).ready(function() {
$(".remove_on_click").click(function() {
var image_id = $(this).attr('imageId');
$('#image_'+image_id).hide();
})
});

Name change from one element to another and value store

i need to get the name and value from li element and display it after selection as the button value, what i need more is for that single value to be stored in a php var for latter submit, i got this far but now i am stuck and keep getting 1 size only
CODE
<button id="changename" class="btn dropdown-toggle size-selector-btn" type="button" data-toggle="dropdown">Select your size <span class="caret" style="display: none;"></span>
</button>
<ul class="dropdown-menu size-list" role="menu">
$productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) {
foreach ($productAttribute['values'] as $attribute) {
$attributeOptions[$productAttribute['label']][$attribute['value_index']] = $attribute['store_label'];
}
}
$key = "Size";
foreach($attributeOptions[$key] as $size){ ?>
<li id="<?php echo $size; ?>" onclick="changeName()"><?php echo $size; ?></li>
<?php }
} ?>
</ul>
</div>
<script>
function changeName() {
document.getElementById("changename").innerHTML = "<?php echo $size; ?>";
}
</script>
OK, well there are 2 issues i can see. 1st that your third foreach loop looks like it should be nested within the others, but its not.
The second issue is that that you are missunderstanding how php and js work. Php is ran on the server before the page is rendered, so the value of $size in your js function will be whatever the LAST value of was.
To fix this, 1st nest the foreach correctly (when using php inline with html, i find its best to use the template syntax for blocks - eg if: endif;, foreach: endforeach; to aid readability), then adjust your js function to take a parameter, and pass that parameter in the onclick event by grabing the clicked elements id:
<button id="changename" class="btn dropdown-toggle size-selector-btn" type="button" data-toggle="dropdown">Select your size <span class="caret" style="display: none;"></span>
</button>
<ul class="dropdown-menu size-list" role="menu">
<?php
$productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) :
foreach ($productAttribute['values'] as $attribute) :
$attributeOptions[$productAttribute['label']][$attribute['value_index']] = $attribute['store_label'];
$key = "Size";
foreach($attributeOptions[$key] as $size):?>
<li id="<?php echo $size; ?>" onclick="changeName(this.id);"><?php echo $size; ?></li>
<?php endforeach;
endforeach;
endforeach;
?>
</ul>
</div>
<script>
function changeName(size) {
document.getElementById("changename").innerHTML = size;
}
</script>

Categories