On a web page there is a table with a few rows. In each line there is a button that triggers a Javascript function:
PHP/HTML:
echo "<form action='' method='post'>";
echo "<button type='submit' name='test' value=".$row[4]." class='attest btn btn-info btn-round btn-icon btn-icon-mini btn-neutral' data-original-title='Test'><i class='now-ui-icons files_single-copy-04'></i></button>";
echo "</form>";
PHP:
if(isset($_POST['test']))
{
$file="/files/".$_POST['test'].".jpg";
$caption="Image: ".$_POST['test'];
if (file_exists($_SERVER['DOCUMENT_ROOT'].$file))
{
echo"<body onload='showtest()'>";
}
else
{
echo"<body onload='notest()'>";
}
}
JS:
function showtest()
{
swal({
title: 'Image',
text: <?php echo json_encode($caption); ?>,
imageUrl: <?php echo json_encode($file); ?>,
imageWidth: 400,
imageAlt: 'Image',
})
}
function noattest()
{
swal({
title: 'Image',
text: "There is no image.",
icon: 'warning',
})
}
A dialog is then displayed using Sweetalert2. The problem is that the table contains so many records that the web page must be scrolled. As a result, the alert is displayed correctly, but the web page "scrolls up again"/reloads. This is very annoying, because you have to search for the right row in the table again.
Is there a solution so that the web page does not jump to the top?
Related
I am working on Get Instagram Stories and show them on website project. So I have done getting stories with API from facebook. I also have an javascript code to show these stories just like instagram does. But here is my question >
How can I put my php variables inside the javascript?
How javascript adds or removes stories. I mean I need some kind of "for each loop"
My php variable codes;
<?php foreach ( $stories as $story ) : // loop over each story element ?>
<?php if ( 'VIDEO' == $story['media_info']['media_type'] ) : // story media is a video ?>
<div>
<video controls poster="<?php echo $story['media_info']['thumbnail_url']; ?>" style="max-width:300px">
<source src="<?php echo $story['media_info']['media_url']; ?>" />
</video>
</div>
<?php elseif ( 'IMAGE' == $story['media_info']['media_type'] ) : // story media is an image ?>
<div>
<img src="<?php echo $story['media_info']['media_url']; ?>" style="max-width:300px" />
</div>
<?php endif; ?>
<div>
<b>
<?php echo $story['media_info']['username']; ?>
</b>
</div>
<a href="<?php echo $story['media_info']['permalink']; ?>" target="_blank">
View on Instagram
</a>
<?php endforeach; ?>
My javascript code;
stories: [
Zuck.buildTimelineItem(
"ramon",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/users/1.jpg",
"Ramon",
"https://ramon.codes",
timestamp(),
[
[
"ramon-1",
"photo",
3,
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/1.jpg",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/1.jpg",
"",
false,
false,
timestamp()
],
[
"ramon-2",
"video",
0,
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/2.mp4",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/2.jpg",
"",
false,
false,
timestamp()
],
[
"ramon-3",
"photo",
3,
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/3.png",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/3.png",
"https://ramon.codes",
"Visit my Portfolio",
false,
timestamp()
]
]
)
]
Just use PHP as a proxy and pass the JSON to the JS
Otherwise you have to do something like this
{
id: "storyid", // story id
photo: "..", // story photo (or user photo)
link: "", // story link (useless on story generated by script)
lastUpdated: "", // last updated date in unix time format
seen: false, // set true if user has opened
items: [ // array of items
// story item example
<?php
$cnt = 0;
foreach ( $stories as $story ) : // loop over each story element
?> {
id: "item<$cnt++ ?>", // item id
type: "<?= $story['media_info']['media_type'] ?>", // photo or video
length: 10, // photo timeout or video length in seconds - uses 3 seconds timeout for images if not set
src: "<?= $story['media_info']['media_url']; ?>", // photo or video src
preview: "", // optional - item thumbnail to show in the story carousel instead of the story defined image
link: "<?= $story['media_info']['permalink'];?>", // a link to click on story
linkText: "", // link text
time: "", // optional a date to display with the story item. unix timestamp are converted to "time ago" format
seen: false // set true if current user was read,
[customKey]: "", // custom-value
[anotherCustomKey]: "" // another-custom-value
}
<?php endforeach; ?>
]
}
I have function delete on my table ( using datatables) this delete is work normally but i want to add some pop up alert like "onclick" on my delete , but its didnt work on my button
public function indexDataTables_pns()
{
$pns = Data_pns::with('users','master_golongan','master_jabatan')->get();
return Datatables::of($pns)->addIndexColumn()
->addColumn('Nama', function ($pns) {
return ''.$pns->users->nama.'';
})
->editColumn('edit', function ($pns) {
return '<i class="glyphicon glyphicon-edit"></i>';
})
->editColumn('hapus', function ($pns) {
$c = csrf_field();
$m = method_field('DELETE');
return "<form action='/delete/$pns->id' method='POST')>
$c
$m
<button style='margin-left:10px; width: 30px;' type='submit'
class='btn btn-xs btn-danger delete' onclick='return
confirm('do you want to delete this data ?')'>
<i class='glyphicon glyphicon-remove-circle'></i>
</button>
</form>";
})
->rawColumns(['Nama' => 'Nama','hapus' => 'hapus','action' => 'action','edit'=>'edit'])
->make(true);
}
its didnt work
i trying adding class
<form action='/delete/$pns->id' method='POST' class='delete-form'>
and add this script
<script>
$('.delete-form').submit(function(event){
if(!confirm('Anda yakin mau menghapus item ini ?')){
event.preventDefault();
}
});
but still didnt work . i put this on under my view .
i try to add onsubmit like this
<form onsubmit='return confirm('Anda yakin mau menghapus item ini ?')'>
still didnt work , iam from this thread this link , but i didnt find the answer ..
look this image
can someone help me ?
UPDATE
i tryng add this form class
return "<form action='/delete/$pns->id' method='POST' class='delete-form')>
this pop up is showing after i click this delete button but this message is null/empty ,
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: '{!! route('d_pns') !!}',
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false,searchable: false},
{ data: 'Nama', name: 'Nama'},
{ data: 'NIP_lama', name: 'NIP_lama'},
{ data: 'NIP_baru', name: 'NIP_baru'},
{ data: 'TMT_CPNS', name: 'TMT_CPNS'},
{ data: 'TMT_PNS', name: 'TMT_PNS'},
{ data: 'TMT_gol_ruang', name: 'TMT_gol_ruang'},
{ data: 'master_golongan.golongan', name: 'master_golongan.golongan'},
{ data: 'master_jabatan.nama_jabatan', name: 'master_jabatan.nama_jabatan'},
{ data: 'edit', name: 'edit', orderable: false, searchable: false},
{ data: 'hapus', name: 'hapus', orderable: false, searchable: false},
],
});
})
$('.delete-form').submit(function(event){
if(!confirm('Anda yakin mau menghapus item ini ?')){
event.preventDefault();
}
});
</script>
#endpush
why this message on confirm is empty ?
Your 1st attempt issue looks to be escaping the quotes " and '. try putting your message inside double quotes " ". This should resolve your problem
<button style='margin-left:10px; width: 30px;' type='submit'
class='btn btn-xs btn-danger delete' onclick='return
confirm("do you want to delete this data ?")'>
<i class='glyphicon glyphicon-remove-circle'></i>
</button>
SOLVED
Need to add
<script type="text/javascript">
function confirm_delete() {
return confirm('Apakah anda yakin untuk menghapus data ini ? ');
}
</script>
and add onclick return confirm_delete()
I will be dropping this for anyone that need to know how to use onclick from laravel yajra serverside.
$datatable = datatables()->collection($data)
->addColumn('action', function($data){
$button = '
<button type="button" data-security="'.$data->security.'" class="btn btn-warning btn-sm" onclick="OrderTicket(\''.$data->security.'\')">Sell
</button>
<button type="button" data-security="'.$data->security.'" class="btn btn-info btn-sm" onclick="createRequest(\''.$data->security.'\')">Buy
</button>
';
return $button;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
return $datatable;
All you have to do is to escape the strings onclick="OrderTicket(\''.$data->security.'\')"
I implemented jQuery Full Calendar, as a separate module...That time it worked good. Now I want to show events after user logged in...User Login done... But issue with loading events only, events are added into Database.. But they won't be loaded into Calendar view
To redirect load.php, I used echo site_url('controller/method'),redirect('controller/method'). When I used redirect method it gives me 'json' data(the data which returned from load.php)
**views/calendar_view.php:**
<script>
$(document).ready(function(){
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events:'<?php echo site_url('Home/load'); ?>', /* redirect('Home/load');//<?php //$this->load->view('load')?>*/
selectable:true,
selectHelper:true,
**views/load.php:**
if($conn==false)
{
echo "Failed to connect to the Database | <br/>";
die(print_r(sqlsrv_errors(),true));
}
$timezone = new DateTimeZone("UTC");
$sql = "select * from events";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false)
{
die(print_r(sqlsrv_errors(),true));
}
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$data[] = array(
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start_event']->format("Y-m-d H:i:s"),
'end' => $row['end_event']->format("Y-m-d H:i:s")
);
}
I want to show events, after employee logged in successfully
It looks like views/load.php does not return anything, the jquery plugin expects a json object, so add the following to load.php
echo json_encode($data);
Furthermore as I remember the events in the plugin does not allow url's directly.
Therefore you will need to load the data from the url. Did not test it, but should be something like below.
$.get('<?php echo site_url('Home/load'); ?>', function(data) {
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events:data.parseJSON(),
selectable:true,
selectHelper:true,
});
You can check in your browser developer tools if the data was loaded correctly:
F.e. Chrome: https://developers.google.com/web/tools/chrome-devtools/network/reference
I was wondering if someone could explain me to the best way to go about this situation.
I have a sidebar that is populated with Li Elements from a foreach loop, that works fine.
Each element has an link that when clicked triggers a Jquery UI Dialog in which there is a text field to add a note and press Submit or cancel, this opens fine, submits fine.
I can't figure out how to retrieve say the link tag's id value and the dialogs
textarea value to submit them to the DB, so the DB is getting populated with 0's, from within the $.ajax Function, I'm sure it can be done and I'm sure I could hack it working but I want to know the right way to do it. Below is my attempt.
The JS
<script>
$(document).ready(function(){
var note;
$("#dialog").dialog({ autoOpen: false,
buttons:{"Add Note": function() {
$.ajax({
url:"<?php echo base_url();?>PropertyAdmin/addNoteToProperty",
data: {name: '20', value: note},
success:function(result){
alert("added");
},
error: function(result){
alert("fail");
},
cache : false
});
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
});
$(".clickable").click(function (e) {
// open and move the dialog
$("#dialog").dialog('option', 'position',[e.clientX+100,e.clientY]).dialog("open");
var element = $(this).find("#prop_note");
note = element.attr("value");
var myTag = $(this).attr('name');
return false;
})
})
</script>
The Dialog
<div id="dialog" title="Add Note">
<div>
<?php $attributes = array('role' => 'form'); echo form_open('PropertyAdmin/addProperty', $attributes); ?>
<div class="form-group">
<label for="prop_note" class="control-label">Note :</label>
<textarea id="prop_note" class="form-control" rows="3" name="prop_note"></textarea>
</div>
</form>
</div>
</div>
The CONTROLLER Function
function addNoteToProperty(){
$id = $this->input->post('name');
$note = $this->input->post('value');
$this->load->model('PropertyModel');
$this->PropertyModel->addNoteToProperty($id,$note);
}
The Model
function addNoteToProperty($propid, $note){
$data = array('prop_note'=> $note, 'prop_id' => $propid, 'prop_note_date' => now());
$this->db->insert('property_notes', $data);
}
One of my unparsed Li's
<li>Investment Properties
<ul>
<?php foreach($property as $row){ if($row['type_id'] != 1) { } else{ ?>
<li style="color: white" class="investmentitems inactive"><a id="<?php echo $row['id']; ?>" href="#"><?php echo $row['property_name'] ." ".$row['property_address1']; ?></a><?php echo anchor("FinancialInput/listproperty/".$row['id'],"Edit" ); ?><a class="clickable" href="" name="<?php echo $row['id']; ?>">Add Note</a></li>
<?php }} ?>
</ul>
</li>
Errors
PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for PropertyAdmin::addNoteToProperty()
Filename: controllers/PropertyAdmin.php
Line Number: 44
A PHP Error was encountered
Severity: Warning
Message: Missing argument 2 for PropertyAdmin::addNoteToProperty()
Filename: controllers/PropertyAdmin.php
Line Number: 44
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: id
Filename: controllers/PropertyAdmin.php
Line Number: 49
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: note
Filename: controllers/PropertyAdmin.php
Line Number: 49
A Database Error Occurred
Error Number: 1048
Column 'prop_note' cannot be null
INSERT INTO `property_notes` (`prop_note`, `prop_id`, `prop_note_date`) VALUES (NULL, NULL, 1396465225)
Filename: E:\wamp\www\oak\system\database\DB_driver.php
I believe getting the name value of the a just involves defining your variable outside of the click
<script>
$(document).ready(function(){
var note;
var name; //ADDED HERE
$("#dialog").dialog({ autoOpen: false,
buttons:{"Add Note": function() {
$.ajax({
url:"<?php echo base_url();?>PropertyAdmin/addNoteToProperty",
data: {name: name, value: $(prop_note).val()},
success:function(result){
alert("added");
},
error: function(result){
alert("fail");
},
cache : false
});
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
});
$(".clickable").click(function (e) {
// open and move the dialog
e.preventDefault();
$("#dialog").dialog('option', 'position',[e.clientX+100,e.clientY]).dialog("open");
name = $(this).attr('name'); //Changing the Value here
return false;
})
})
</script>
There you are defining the variable before the click event and changing it to the ID of the clickable link before sending it to the PHP controller in the AJAX request
I am trying to get Stripe's Checkout Custom Button to charge a credit card but all it does is minimize after I enter the credit card details. I am using the code found in the documentation but I can't get it to work. The simple button is easy to use and I figured it would be as easy as just customizing that one but it's very different.
Here's the code:
Payment Page
<form action="charge.php" method="post">
<script src="https://checkout.stripe.com/checkout.js"></script>
<input type="submit" value="Pay with card" id="customButton"/>
<?php require_once('./config.php'); ?>
<script>
var handler = StripeCheckout.configure({
key: '<?php echo $stripe['publishable_key']; ?>',
image: 'favicon.png',
token: function(token, args) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'Imprintnation',
description: 'Decals',
amount: <?php echo $stripeTotal; ?>
});
e.preventDefault();
});
</script>
</form>
Charge Page(charge.php)
<?php
require_once(dirname(__FILE__) . '/config.php');
$token = $_POST['stripeToken'];
$customer = Stripe_Customer::create(array(
'email' => 'customer#example.com',
'card' => $token
));
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => 5000,
'currency' => 'usd'
));
echo '<h1>Successfully charged $5!</h1>';
?>
Configuration Page(config.php)
<?php
require_once('./lib/Stripe.php');
$stripe = array(
secret_key => 'sk_test_************************',
publishable_key => 'pk_test_************************'
);
Stripe::setApiKey($stripe['secret_key']);
?>
What am I missing here? I can't even get it to retrieve a token.
How can I retrieve a token and charge a card?
Finally got it to work. Had to change a bunch of it. Here is the code:
Payment page
<form action="charge.php" method="post">
<script src="https://checkout.stripe.com/checkout.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<button id="customButton">Pay with Card</button>
<style>
#customButton{
width:300px;
height:50px;
background-color:orange;
color:white;
border:2px solid green;
}
</style>
<script>
$('#customButton').click(function(){
var token = function(res){
var $input = $('<input type=hidden name=stripeToken />').val(res.id);
$('form').append($input).submit();
};
StripeCheckout.open({
key: '<?php echo $stripe['publishable_key']; ?>',
address: false,
amount: '<?php echo $price; ?>',
currency: 'usd',
name: 'test',
description: '<?php echo $desc; ?>',
panelLabel: 'Checkout',
token: token
});
return false;
});
</script>
<input type="hidden" name="desc" value="<?php echo $desc; ?>"/>
<input type="hidden" name="totalPrice" value="<?php echo $price; ?>"/>
</form>
charge.php
<?php
require_once(dirname(__FILE__) . '/config.php');
$token = $_POST['stripeToken'];
$amount = $_POST['totalPrice'];
$desc = $_POST['desc'];
$percent = "0.01";
$realAmount = $amount * $percent;
try {
$charge = Stripe_Charge::create(array(
'card' => $token,
'amount' => $amount,
'currency' => 'usd',
'description' => $desc
));
} catch(Stripe_CardError $e) {
// The card has been declined
}
echo "<h1>Successfully charged $$realAmount!</h1>";
?>
I wish Stripe's documentation was more straightforward but this code handles the charge and it logs it on your dashboard.
#BlueSix is right, why do you have:
<input type="hidden" name="totalPrice" value="<?php echo $price; ?>"/>
Just because the value is hidden, does not mean it cannot be edited by the end user.
It would be much better to set $amount = $price directly, passing the variable through your application backend.