I have a submit button"Certificate copy" when i clicked the button it should show a popup.
The below one is my html code.
print "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>";
print "<form action='details.php' name='copy' method='POST' target='_blank'>";
print "<input type='hidden' name='certificate_name' value='$certificate_name'>";
print "<input type='hidden' name='certificate_id' value='$certificate_id'>";
print "<input type='submit' name='certificatecopy' id='certificate' value='Certificate Copy'>";
print "</form>" ;
and my code for popup is
print "<script> $(document).on('click','#certificate',function(){val = confirm('Do you want to create a new certificate?');
alert(val);
if(val)
{
alert('proceed ');
return true;
}
else
{
alert('Dont proceed');
return false;
}
});</script>";
My problem is, when i click the button at first time the popup box doesn't appear. but when the button clicked second time, the popup box is appear. what is the problem. I need the popup when the button clicked first time. please help.
Instead of adding in $_SESSION['pop_up'] just echo it:
if(isset($_POST['certificatecopy'])){
echo "<script>
.....................
.....................
</script>";
You need to do this in client side on button click event .
Confirm will return the Boolean value true or false . Based on user click.
$(document).on('click','#certificate',function(){
val = confirm('This will create a new certificate with all properties and links from the original certificate. A certificate user may edit the new certificate properties, but may not delete the certificate. Do you want to create a new certificate?');
alert(val);
if(val)
{
alert('proceed ');
return true;
}
else
{
alert('Dont proceed');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='details.php' name='copy' method='POST' target='_blank'>
<input type='hidden' name='certificate_name' value='$certificate_name'>
<input type='hidden' name='certificate_id' value='$certificate_id'>
<input type='submit' name='certificatecopy' id="certificate" value='Certificate Copy'>
</form>
Update 1 :
<?php
print "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>";
print "<form action='details.php' name='copy' method='POST' target='_blank'>";
print "<input type='hidden' name='certificate_name' value='$certificate_name'>";
print "<input type='hidden' name='certificate_id' value='$certificate_id'>";
print "<input type='submit' name='certificatecopy' id='certificate' value='Certificate Copy'>";
print "</form>" ;
print "<script> $(document).on('click','#certificate',function(){val = confirm('Do you want to create a new certificate?');
alert(val);
if(val)
{
alert('proceed ');
return true;
}
else
{
alert('Dont proceed');
return false;
}
});</script>";
?>
You want to ask for the confirmation Client side before sending a request to the server?
If you use Bootstrap, you can try a little jQuery plugin I made, https://github.com/delboy1978uk/bs-delete-confirm. It doesn't need to be used solely for deletion, it's only named that since it's the most used case.
All you do is add a CSS class to your link:
Do stuff!
And the javascript:
$(document).ready(function(){
$('.confirm').deleteConfirm();
});
Now when you click the link, the JS intercepts it, launches a bootstrap modal window, and upon confirming, follows your hyperlink.
You can pass options in to the deleteConfirm() method too:
{
heading: "Please confirm",
body: "Are you sure you wish to perform this action?",
ok_text: "Proceed",
cancel_text: "Back",
log: false
}
Hope this helps! If you don't use Bootstrap, it's well worth addingto your project! Here's a link to the modal functionality:
https://getbootstrap.com/docs/3.3/javascript/#modals
Related
what the bellow code does is making sure the user isn't allowed to submit a comment unless he's signed in by using $_SESSION['login_user'] supervariable. But it's giving me an error. I think the problem is because I'm calling a javascript function in onsumbit="return(checkUser())". There's something wrong there but I don't know why.
I have the following code:
<script type="text/javascript">
// notice the quotes around the ?php tag
function checkUser() {
<?php
if(isset($_SESSION['login_user'])){
$isExist = true;
}
?>
else{
$isExist= false;
alert( "Please register first!" );
}
var htmlString="<?php echo $isExist; ?>";
return isExist;
}
</script>
...
...
<?php
echo "<form method='POST' onsubmit="return(checkUser());" action='".setComments($connection, $res['post_id'])."'>
//echo "<form method='POST' action='".setComments($connection, $res['post_id'])."'>
<input type='hidden' name='uid' value='".$_SESSION['login_user']."'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'> </textarea><br>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
getComments($connection, $res['post_id']);
?>
....
If this is not the right method to stop the user from submitting a comment, then what could be another method?
In addition to what #RonaldT said, you need to understand that the PHP code is executed on the server before being sent to the browser. So checking for $_SESSION['login_user'] inside a Javascript function is kind of silly, since it will always be the same until the user refreshes the page (only then will PHP re-check the value).
So your function can be simplified like this:
<script type="text/javascript">
// on page load, define a global variable using PHP
var isLoggedIn = <?php echo isset($_SESSION['login_user']) ? "true" : "false"; ?>;
function checkUser() {
// check that global variable every time checkUser() is called in Javascript
if (!isLoggedIn) {
alert( "Please register first!" );
}
return isLoggedIn;
}
</script>
Keep in mind that this kind of "security" is extremely easy to fool (any user can just open their browser console, type isLoggedIn = true; and voila), so be sure to check on the server as well when the form is submitted.
Or better yet: if a user is not allowed to do something, don't give them the opportunity. Why display the form at all if the user will not be allowed to submit it anyway?
<?php
if (!isset($_SESSION['login_user'])) {
echo "Please register to add a comment";
} else {
echo "<form [...everything else...] /form>";
}
getComments($connection, $res['post_id']);
?>
i'm developing a PHP web application.
On Categories page which shows all categories i would like to put an edit submit button which on click event will open a prompt button with the category name to change it if the user wants.
I would also like to have some validations on prompt box (min-length='5') and if the user clicks on cancel button to return false(returns null now) and not submit the form else if validation is ok and clicks ok to submit the form with the category id and the new category name (prompt value) to update the data.
Sample of code:
echo "<table>";
$strCats=$con->query("SELECT * FROM categories ORDER BY catName");
$CatsRows=$strCats->rowCount();
if ($CatsRows==0) {
echo "NO DATA FOUND";
}else{
while($CatsRow = $strCats->fetch()){
echo "<tr><td>$CatsRow[catName]</td>
<td><button type='submit' name='btnEditCategory' value='$CatsRow[catId]' onclick='return prompt(\"Rename category\",\"$CatsRow[catName]\");'>EDIT</button></td></tr>";
}
}
echo "</table>";
You will need to use a javascript function which runs on button click and submit the value via ajax.
<script type="text/javascript">
function btnEditCategory(catID){
//edit function with ajax call to edit category
}
</script>
<input type="submit" onclick="return btnEditCategory('1');" value="Edit">
Pass the category ID to edit in the edit function
Finally i solve it.
if(isset("cmdEditCategory")){
$catName = str_replace('"',"`",str_replace("'","`",$_POST['txtCatName']));
$catId = $_POST['cmdEditCategory'];
$sqlEditCategory=$con->prepare("UPDATE categories SET catName=? WHERE catId=?");
$sqlEditCategory->bindParam(1, $catName, PDO::PARAM_STR, 25);
$sqlEditCategory->bindParam(2, $catId, PDO::PARAM_INT, 11);
if ($sqlEditCategory->execute()) {
echo "<script type='text/javascript'>notif('success','". MSG_SUCCESS ."','". MSG_UPDATED ."');</script>";
}else{
echo "<script type='text/javascript'>notif('error','". MSG_WARNING ."','". MSG_ERROR ."');</script>";
}
}
$strCats=$con->query("SELECT * FROM categories ORDER BY catName");
$CatsRows=$strCats->rowCount();
if ($CatsRows==0) {
echo "<div class='alert alert-danger'>". MSG_NO_DATA_FOUND ."</div>";
}else{
echo "<form action='/..$_SERVER[REQUEST_URI]' method='post'>
<table>";
while($CatsRow = $strCats->fetch()){
echo "<tr><td>$CatsRow[catName]</td>
<td>
<button type='submit' name='cmdEditCategory' value='$CatsRow[catId]' onclick='return editCategory(\"$CatsRow[catName]\");'>". EDIT ."</button>
</td>
</tr>";
}
echo "</table>
<div style='display:none'>
<input type='text' id='txtCatName' name='txtCatName' />
</div>
</form>
<script type='text/javascript'>
function editCategory(catName){
var msg = prompt('Rename category',catName);
if(msg != null){
document.getElementById('txtCatName').value=msg;
return true;
}else{
return false;
}
}
</script>";
}
If there is another better solution please reply.
I'm avoiding using a database for my latest project and so I am using files and folders. I list folders of a directory as buttons and each one loads a screen with a list of files within it. I'm now trying to load in the file's contents dynamically without refresh to avoid loosing the menu (list of files shown on screen as buttons). I'm trying to use ajax but because the file buttons are created using a foreach php loop, the value I pass to javascript/ajax when I click one of the file buttons is incorrect as it always wants to pass the first button's value in the list!
Here is the PHP code:
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' ID='selectBtn' value='$filePathTrimmed' onclick='return displayData();'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And this is the JS:
<script>
function displayData()
{
var btnData = document.getElementByID('selectBtn').value;
alert("The currently selected button is "+btnData);
});
}
</script>
As you can see the PHP loops and creates a form for each button plus hidden fields. The JS just tries to grap the value of the button clicked and alert it. Problem is that the value is always the first file in the list.
What am I doing wrong please? If I use a class on the button instead of an ID then I will need to state the number in the array:
var btnData = document.getElementsByClassName('selectBtn')[0].value;
But this means I'd need to know the place within the array and make using the value pretty pointless.
I'm pretty stuck - or thick!
Thanks.
You need to use this inside onclick='return displayData(); and then use it in your function like below:-
Working snippet:-
function displayData(ele){
var btnData = ele.value;
alert("The currently selected button is "+btnData);
return false;
}
<form method='POST'>
<input type='submit' value='hi' onclick='return displayData(this);'/>
<input type='hidden' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>
You are setting the same id value for each separate form. You should ensure that all the id attribute values are unique for all html elements as a rule of thumb to avoid unpredictable behaviours in the dom.
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $idx => $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' id='selectBtn-{$idx}' value='$filePathTrimmed' onclick='return displayData(this.id);'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And javascript:
<script>
function displayData(clicked_id)
{
var btnData = document.getElementByID(clicked_id).value;
alert("The currently selected button is "+btnData);
return false;
}
</script>
Solution: I used 'return false' at the end of the javascript/ajax code block, and 'this' in the php code to pass current data held in 'value' - thanks Alive to Die.
I also I made use of the 'name' attribute to store and access further data data.
PHP:
echo "<form method='POST'>
<input type='submit' id='selectBtn' name='$file' value='$filePathTrimmed' onclick='return displayData(this);'/>
</form>";
JS:
<script>
function displayData(fileName)
{
var btnData =fileName.name;
var name = fileName.value;
$.ajax({
type : "POST",
url : "DisplayFileContents.php",
data : {"data": btnData, "name": name},
success : function(result) {
$('.page-content').html(result);
$('body').animate({scrollTop: 0}, 200);
}
});
return false;
};
DisplayFileContents.php:
<?php
$filename=$_POST['data'];
$title = $_POST['name'];
echo "<h2>".$title."</h2>";
echo "<pre>";
Include $filename;
echo "</pre>";
?>
I want to submit a form using an href tag and load that submitted form inside a pop-up.
<form method='post' action='" . $paymentURL . "' id='frmPaymentDtl' onsubmit='target_popup(this)'>
<a id=\"submit_full_payment\" onclick=\"target_popup(get_form(this).submit())\">Make Full Payment</a>
<input type='hidden' name='customer_id' value='" . $customer_id . "'/>
<input type='hidden' name='account_id' value='" . $account_id . "'/>
<input type='hidden' name='invoice_number' value='" . $invoice_model[0]->number . "'/>
<input type='hidden' name='detail_id' value='" . $bean->id . "'/>
<input type='hidden' name='header_id' value='" . $_GET['record'] . "'/>
<input type='hidden' name='detail_number' value='" . $bean->detail_id . "'/>
<input type='hidden' name='amount' value='" . number_format($bean->amount,2) . "'/>
<input type='hidden' name='description' value='" . $paymentSchedule->description . "'/>
<input type='hidden' name='invoice_id' value='" . $invoice_model[0]->id . "'/>
<input type='submit' name='submit_btn' class=\"listViewTdToolsS1\" value='Submit Bank/Credit Payment'/>
</form>
<script type='text/javascript'>
function get_form( element )
{
while( element )
{
element = element.parentNode
if( element.tagName.toLowerCase() == \"form\" )
{
//alert( element ) //debug/test
return element
}
}
return 0; //error: no form found in ancestors
}
function target_popup(form) {
window.open('', 'formpopup', 'width=800,height=600,resizeable,scrollbars');
form.target = 'formpopup';
}
</script>
What happens here is that the pop-up is displayed but the form is loaded on the main page, when I want it to be loaded inside the pop-up page. Also, I can only use link here to access the form as the submit buttons are not allowed.
You are submitting the form and then passing the return value of calling submit() to target_popup().
You need to first call target_popup() and pass it the form, then you need to submit the form.
onclick="var frm = get_form(this); target_popup(frm); frm.submit()">
That said, you would be better off using a regular submit button and applying CSS to make it look the way you want.
Ajax code to submit details and get result:
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
$('#submit_full_payment').click(function () {
var url = 'YOUR_URL';
$.ajax({
type: 'POST',
url: url,//url to post data
data: "customer_id=" + $('name=customer_id').val() + "&account_id=" + $('name=account_id').val(),//add other form fields here
success: function (data) {//process data here
alert(data);
},
error: function (data) {
alert(data);
}
});
});
step2: Use the Dialog to display the form and link. refer link this will hide the form on main page and use ajax as given above to process form and retain in the pop-up only. If you do not want to remain in pop-up above step can be ignored.
You need to use Ajax. Here is the list what you need to do:
Stop Form's submit event (which you can use e.preventDefault();)
Send data's with ajax and then
Do what ever you want ajax's success or error callbacks..
Please let me know if you need any further help :)
This was my previous answer and i get a mines for this so let me explain it..
1-) You dont need to use window.open()for a pop-up page. You can simply create a modal(which is a bootstrap element : http://getbootstrap.com/javascript/#modals) and display whatever you want in modal. Which in your case it will be your form element again if i understand your question correctly.
2-) If you want to stop page's reload on submit use this:
$('#frmPaymentDtl').submit(function(e)
{
e.preventDefault();
//Take form's all data with this
var data = $('#frmPaymentDtl').serialize();
//Or you can assign all id's to a new variable if you'd like that way.
//After this open your modal which you have a form inside that.
//then write all data into input's from "data" variable.
});
I know this one is kinda different but i know this will work for you as well.
One more thing. If you want to send this "data" variable to another page you need use Ajax.
If you don't know how check this: jQuery AJAX submit form
Oww by the way if you will try to use my way please delete your form's onclick event. :)
Here's my scenario:
I have a form, main_play.php, where its a list of all playlist then when I click the radio button it will pop up a confirmation message then after that it will proceed to the form of play_delete...Proceeding in the next page is working...
But in the play_delete.php all variables there are already empty... But, when I'm not using the confirmation message it can be deleted and also the variables are transferred in play_delete...
Here's my variable:
$get_ID = $_POST['deletePlaylist'];
Here's my code for PHP:
<input type="radio" name="deletePlaylist[]" class="chk_boxes1" value="<?php echo $row['id']; ?>"<?php echo ($_POST['deletePlaylist[]'] == $row['id'] ? 'checked=" checked"' : ''); ?> onclick='confirmation()'>
Here's my javascript:
<script>
function confirmation() {
var answer = confirm("Are you sure you want to delete?")
if (answer){
window.location = 'play_delete.php';
}
else{
alert("Thanks for sticking around!")
}
}
</script>
Is there a way to transfer the data in php to javascript then javascript to the next page??
Thanks in advance!
Replace
window.location = 'play_delete.php';
with
document.formname.action = 'play_delete.php';
document.formname.submit();
where formname is the name of the form on the page in which all the playlist radio buttons are appearing.
try this it will work
<script>
function confirmation(value) {
var answer = confirm("Are you sure you want to delete?")
if (answer){
window.location = 'play_delete.php?data='+value;
}
else{
alert("Thanks for sticking around!")
}
}
</script>
<body>
<input type="radio" name="radio" value="uniqvalue" id="name" onclick='confirmation(this.value);'/>
</body>
Have a look at this for transferring a PHP variable to a javascript variable:
How to access PHP variables in JavaScript or jQuery