A sample of my code :
<form action="test.php" method="GET">
<input type="text" name="Delete_This" value="<?php if (isset($_GET['Delete_This'])) echo $_GET['Delete_This']?>">
<input type="submit" name="Deleting" value="Delete this">
<?php
// If the deleting button is pressed
if (isset($_GET['Deleting']))
{
$DeleteThis = $_GET['Delete_This'];
?>
<script type='text/javascript'>
if (confirm('Are you sure you want to delete <?php echo $DeleteThis ?> ?'))
alert('<?php echo $DeleteThis ?> deleted');
<?php
$sql_delete="DELETE FROM table WHERE Name like '".$DeleteThis ."'";
mysqli_query($db,$sql_delete);
?>
else
alert('Not deleted');
</script>
<?php } ?>
</form>
The confirm box opens proprely. My problem is that wether i click on OK or Cancel, $sql_delet is executed.
I know I should use Javascript on the top <head> of my document but if i do that I can't execute the Delete query and I must warn the user what he's going to delete. {$DeleteThis} works fine. I also used the onclick function on the input but I can't use {$DeleteThis}.
To synthesize : I want, if the confirm box is canceled, the query not to be executed and I must use php variable in the confirm and alert.
You may want to read up on the difference between server-side and client-side languages.
Everything you put in php code is executed before the html and javascript code is even sent to the user's browser.
In contrast, everything you put in javascript code can no longer affect the php code.
So what happens in your code is that php first checks whether there is a $_GET['Deleting'] variable. If there is one, it finds some html and javascript, and remembers that it should output that to the browser later. It then executes the delete query. And once it's done, it sends the following javascript (plus any surrounding html) to the browser:
<script type='text/javascript'>
if (confirm('Are you sure you want to delete your-deletion-value ? \nHey'))
alert('your-deletion-value deleted');
else
alert('Not deleted');
</script>
So hopefully, you see the disconnection between the two.
you could put confirmation in
if (isset($_GET['Deleting']))
{
$DeleteThis = $_GET['Delete_This'];
if(!isset($_GET['ConfirmDelete'])//if confirmation has not been initiated yet
{
?>
<script type='text/javascript'>
function deleteOrNot(formEle)
{
if (confirm('Are you sure you want to delete <?php echo $DeleteThis ?> ?'))
window.location += '&ConfirmDelete=yes';//casue a postback with ConfirmDelete attribute in $_GET
else
alert('Not deleted');
</script>
<?php }
else if($_GET['ConfirmDelete'] == 'yes')
{
$sql_delete="DELETE FROM table WHERE Name like '".$DeleteThis ."'";
mysqli_query($db,$sql_delete);
}
} ?>
Or you could use a a checkbox in your form with a required attribute then set the submit button to set the value of the checkbox before submitting with an onclick.
<input type="checkbox" name='ConfirmDelete'
required <?php if(isset($_GET['ConfirmDelete']))
echo 'checked=' . $_GET['ConfirmDelete']; ?> >
<input type="submit" name="Deleting" onclick=
'this.form.ConfirmDelete.checked = deleteOrNot(this.form)' value="Delete this">
and change your script like this
<script type='text/javascript'>
function deleteOrNot(formEle)
{
if(typeof formEle == 'undefined')
{
formEle = forms[0];
}
var result = confirm('Are you sure you want to delete' + formEle.Delete_This.value + ' ? \nHey');
if (result)
alert(formEle.Delete_This.value + ' will be deleted');
else
alert('Not deleted');
return result;
}
</script>
Note: I added the form as an argument to the deleteOrNot function and use that to get the value of the text box. The required on the checkbox will prevent form submission if it is not checked
onclick="return confirm('Are you sure you want to delete?');"
Related
I have a page with two submit buttons using if ($_POST['action'] == 'Test SMS') to executed code for my "Test SMS" button. I need to execute code from a PHP script then give an alert box while not leaving the page.
index.html
<form action="updateUserConfig.php" method="post">
<input type='submit' name='action' value='Test SMS' class='btn-test'>
<input type="submit" name="action" value="Save" class="btn btn-primary">
</form>
updateUserConfig.php
if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
//grab ntid and phone from header
if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
if(isset($_POST['phone'])) $phone = $_POST['phone'];
//using the notify_sms_users funtion from send_notification.php
require 'send_notification.php';
notify_sms_users(array($ntid), "", 4);
//alert user that there message has been sent
$alert = "Your message has been sent to " . $phone;
echo '<script type="text/javascript">alert("'.$alert.'");';
echo '</script>';
header('Location: index.php');
} else {-----action for other submit button------}
I asked a similar question that was marked a duplicate at Alert after executing php script while not leaving current page but was able to come up with a solution so I wanted to share.
I was able to accomplish this by adding a URL query string in my header('location: index.php?text=success) function then using JS I was able to use an if statement to look for the query string and alert if so.
index.html
<form action="updateUserConfig.php" method="post">
<input type='submit' name='action' value='Test SMS' class='btn-test'>
<input type="submit" name="action" value="Save" class="btn btn-primary">
</form>
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("settings=success") > -1) {
alert("Your settings have been saved");
}
else if(window.location.href.indexOf("text=success") > -1) {
alert("A SMS has been sent!");
}
});
</script>
updateUserConfig.php
if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
//grab ntid and phone from header
if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
if(isset($_POST['phone'])) $phone = $_POST['phone'];
//using the notify_sms_users funtion from send_notification.php
require 'send_notification.php';
notify_sms_users(array($ntid), "", 4);
header('Location: index.php?text=success');
} else {-----action for other submit button------}
header('Location: index.php?settings=success');
The only downside to this solution is that I don't have easy access to my PHP $phone variable to tell the user what number the message was sent to.
AJAX is the method most suited to this job, because what you are trying to achieve is a frontend interaction. Php is a server side language.
AJAX will transmit form data to the backend php script. Once the the php script has handled the data on the server, it can return the data you require to the AJAX script. This is done sometimes using JSON, especially as you have multiple variables.
$formdata = array(
'ntid' => $_POST['ntid'],
'phone' => $_POST['phone']
);
return json_encode($formdata);
The returned JSON code will look something like:
{"ntid":"NT ID","phone":"Phone number"}
Tutorials similar to this are very useful:
[http://www.yourwebskills.com/ajaxintro.php][1]
I have found that taking a break from your main project and investing a little time in learning the mechanics behind what your trying to achieve, enables you to solve your problem faster.
I already have a php validation and form setup with PHP. So if someone forgets a username, the validation will add to the errors array and display it on the page when submitted. Now, instead of displaying some text for the error (Username can't be blank) I just want the input box highlighted in red, which I know needs JavaScript. I am having some trouble running this JavaScript function properly. Below is the code.
JavaScript:
<script type="text/javascript">
function myFunction() {
document.getElementById("usernameformitem").className = "formerror";
}
</script>
PHP:
if (isset($_POST['submit'])) {
$required_fields = array("username");
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
//the $value is now the un/pw without whitespaces
$value = trim($_POST[$field]);
//if the value does not exist/is blank
if (!has_presence($value)) {
//remember field is really un or pw
$errors[$field] = fieldname_as_text($field) . " can't be blank";
echo "<script>";
echo "myFunction();";
echo "</script>";
}
}
}
validate_presences($required_fields);
HTML:
<form action="new_user4.php" method="post">
<div id="usernameformitem">
<p>Username:
<input type="text" name="username" value="" />
</p>
</div>
<input type="submit" name="submit" value="Create User" />
</form>
Thanks in advance!
make sure the div exists before calling the function, for example echo the script after the div or use
window.onload=function() { if (myFunction) myFunction(); }
FIDDLE
But why even submit the form?
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
if (this.username.value="") {
myFunction();
return false; // stop submission
}
return true;
}
<?PHP if (!has_presence($value)) { .... ?>
if (myFunction) myFunction();
<?PHP } ?>
}
PS: NEVER call a form element name="submit" - it will block you from ever submitting by script
Right under the if submit area of php, I echoed
echo "<script type=\"text/javascript\">";
echo "function myFunction() {";
echo "document.getElementById(\"usernameformitem\").className = \"formerror2\";";
echo "}";
echo "</script>";
Then, in the HTML under the div that I am trying to affect, I entered:
<script>
window.onload=function() { if (myFunction) myFunction(); }
</script>
Only problem I ran into was that style had to be internally set. I'm not sure how to have it pull from my external css yet.
Big thanks to mplungjan!
I want to check a text field in form that if username exists in database or not.i want it without refreshing page and i am using Wordpress.I know it is possible through ajax but i have tried ajax in Wordpress and any ajax code didn't run on it. Kindly provide any piece of code or any helpful link. Last time i have tried this but didn't work:
<?php
if(!empty($user_name)){
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}?>
<label for="user_name" id="user_name">Username: </label>
<input type="text" name="user_name" id="user_name" required/>
<span id="user-result" ></span>
<script type="text/javascript">
jQuery("#user_name").keyup(function (e) { //user types username on inputfiled
var user_name = jQuery(this).val(); //get the string typed by user
jQuery.post('teacher_form.php', {'user_name':user_name}, function(data) {
jQuery("#user-result").html(data); //dump the data received from PHP page
});
});
</script>
use
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
to be
<?php
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}
?>
but keyup event will call the ajax each keyup .. you can use **.blur()** instead of **.keyup()**
I'm trying to upgrade my like-system to something more practical.
Currently I have it like Like then in the PHP have something like: if $_GET['like'] is set, then grab the user's ID and the post ID and call a function called like_status($post_id,$user_id);
However, I've been working on something like this:
The main part that shows on the statuses:
<script src="https://mysite/stuff/jquery.min.js"></script>
<script src="https://mysite/stuff/js/global.js"></script>
<input type="hidden" id="postid" value="<? echo $postid; ?>">
<input type="hidden" id="userid" value="<? echo $session_user_id; ?>">
<span id="like-button" style="color:red;">Like</span>
The Javascript/jQuery:
$('span#like-button').on('click', function(){
var postid = $('input#postid').val();
var userid = $('input#userid').val();
if (postid != ''){
$.post('https://mysite/stuff/ajax/like.php', {postid: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = data;
});
}
});
and finally,
My like.php script:
<?php
if(isset($_POST['postid']) === true && empty($_POST['userid']) === false){
include $_SERVER['DOCUMENT_ROOT'].'/stuff/init.php';
if(is_liked($_POST['postid'],$_POST['userid']) === true){
unlike_status($_POST['postid'],$_POST['userid']);
echo 'Like';
} else {
like_status($_POST['postid'],$_POST['userid']);
echo 'Unlike';
}
}
?>
My unlike/like functions work fine. I have a working like system now, but it makes the user refresh and everything every time, and it's very inconvenient. I'd like to use this method to automatically update the like button without having to refresh the page or anything. This way, users can like multiple things on the page, and not have to refresh the page every time. I also think it's more secure since the $_GET['like'] can be changed to any id, even if user's aren't friends with other users, or the status doesn't exist.
My issue:
Okay, so whenever I click the like button, nothing happens. I tried this in a separate page as well (changing the type from hidden to text, and manually inputting the data) and it didn't work either. It seems the javascript doesn't execute. I've opened up console in google chrome, and when I click the button, nothing happens. The like doesn't get posted to the database, and the button doesn't get updated.
Can anyone explain what I'm doing wrong? Possibly point me in the right direction to fixing this?
UPDATE
I tried combining the Javascript/HTML in one page to have dynamic variables.
This is what shows up for each status:
<script src="https://mysite/stuff/jquery.min.js"></script>
<script type="Javascript">
$(document.body).on('click','#like-button', function(
var postid<? echo $status_id; ?> = $('input#postid<? echo $status_id; ?>').val();
var userid<? echo $status_id; ?> = $('input#userid<? echo $status_id; ?>').val();
$.post('https://mysite/stuff/ajax/like.php', {postid: postid<? echo $status_id; ?>, userid: userid<? echo $status_id; ?>}, function(data){
document.getElementById('like-button').innerHTML = data;
});
));
</script>
<input type="hidden" id="postid<? echo $status_id; ?>" value="<? echo $status_id; ?>">
<input type="hidden" id="userid<? echo $status_id; ?>" value="<? echo $session_user_id; ?>">
<span id="like-button" style="color:red;"><? if(isliked($status_id,$session_user_id) === true){ ?>Unlike<? } else { ?>Like<?}?></span>
I still can't get it to execute the script.
You can always just use $('#fomrm_id').serialize(), to get all the form fields at once in POST data. It refreshes page because you have to add return false; to the end of jQuery.click event.
If those elements are being created dynamically (or as in your case script is being executed before they are created), you need to set proper .on event, this one is not good, as it binds to the element that may not be there.
Should be rather:
$(document.body).on('click','#like-button', function(){..}); - that will bind it to document body, that is always there, but will check for selector in second argument if it matches.
It's not exactly what I wanted to do, but it's good enough. I managed to get the like button to work/update without refreshing and such. Thanks to everyone for the help if it wasn't for your suggestions I would've never found this out.
<input type="hidden" id="postid" value="<? echo $status_id; ?>"><br>
<input type="hidden" id="userid" value="<? echo $session_user_id; ?>"><br>
<span id="like-button" style="color:red;"><? if(isliked($status_id,$session_user_id) === true){ ?>Unlike<? } else { ?>Like<? } ?></span>
<script>
$('span#like-button').on('click', function(){
var postid = $('input#postid').val();
var userid = $('input#userid').val();
<? if(isliked($status_id,$session_user_id) === true){ ?>
$.get('https://mysite/dash', {unlike: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = 'Like';
});
<? } else { ?>
$.get('https://mysite/dash', {like: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = 'Unike';
});
<? } ?>
});
</script>
i have a form like this (already add jquery latest)
echo '<form name="chat" id="chat" action="/pages/guicsdl.php" method="post">';
echo bbcode::auto_bb('chat', 'text');
echo '<textarea rows="3" name="text" id="text"></textarea><br/>';
echo '<input type="hidden" name="trave" value="'.$trave.'" /><input type="submit" name="submit" value="Gửi" /></form>';
and the js
$(document).ready(function() {
$("chat").submit(function(){
$.post('/pages/guicsdl.php', $("#chat").serialize() );
});
});
and the file guicsdl.php
if(isset($_POST['submit'])) {
$noidung = functions::check($_POST['text']);
mysql_query("INSERT INTO `status` SET `user_id`='".$user_id."', `text`='".$noidung."', `time`='".time()."'");
mysql_query("UPDATE `users` SET `tongchat`= tongchat+1 WHERE id = '".$user_id."' ");
$trave = isset($_POST['trave']) ? base64_decode($_POST['trave']) : '';
header("Location: $trave");
}
i only want when i submit the form, the page doesn't refresh, the data insert to database. can any one help me fix? pls, and thanks. sorry for bad english.
You have to add return false; so that the browser 'understands' that it should not submit the form directly.
$(document).ready(function(){
$("#chat").submit(function(){
$.post('/pages/guicsdl.php', $("#chat").serialize() );
return false;
});
});
Another way (which I myself prefer) is to tell the event to not do it's default behavior.
$(document).ready(function(){
$("#chat").submit(function(ev){ // note the extra parameter
ev.preventDefault();
$.post('/pages/guicsdl.php', $("#chat").serialize() );
});
});
Wilmer also noticed that you had forgotten to put a # for the jQuery identifier when selecting the chat form.