This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 7 years ago.
I have a form that is responsible for inserting values in the database. It is working fine but when ever the values are submitted the page gets refreshed, I tried to take help from here, but it didn't worked in my case. can anyone please tell how I can submit the values without refreshing the page.
Code that I have for now is
<?
if($_POST['submit'])
{
$sender_id = mysqli_real_escape_string($con, $_POST['sender_id']);
$receiver_id = mysqli_real_escape_string($con, $_POST['receiver_id']);
$message = mysqli_real_escape_string($con, $_POST['message']);
// execute insert query here
}
?>
<form class="form-horizontal" enctype="multipart/form-data" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="hidden" name="sender_id" value="<? echo $recruiterid; ?>">
<input type="hidden" name="receiver_id" value="<? echo $recv_id; ?>">
<textarea name="message" class="form-control" ></textarea>
<button type="submit" value="submit" name="submit" class="btn btn-greensea btn-ef btn-ef-7 btn-ef-7b b-0 br-2"><i class="fa fa-envelope"></i> Send Message</button>
</form>
You need to use AJAX to submit forms without refreshing. Add this in your JavaScript:
$("form").submit(function (e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function () {
alert("Submitted!");
});
});
Related
Good day. There is a list of items with two different buttons in my laravel app. One is for updating while the other deletes. I'm using a form (with POST methods) for the two buttons. So, basically, I have two forms on the page. The "update" button works quite well. But the delete button keep on giving me the same ID when I "dd" the request. I am using javascript to submit the "Delete" form because I want to use sweet alert for the user to confirm delete. The code is shown below. Please what may be wrong with it. Also, I'll be glad if I can get a better way of doing it.
This are my forms
<form action="{{route('update.cart')}}" method="POST">
{{csrf_field()}}
<input type="hidden" name="id" value="{{$product->id}}">
<td class="product-quantity"><input type="number" name="quantity" value="{{$product->quantity}}"></td>
<td class="product-subtotal">₦{{$product->price * $product->quantity}}</td>
<td class="product-remove">
<input type="submit" class="login-btn" value="Update" style="width:90px!important;text-transform: none!important;">
</form>
<form style="display: inline!important;" action="{{route('remove.cart')}}" method="POST" name="myForm" id="myForm">
{{csrf_field()}}
<?php
$id = $product->id;
?>
<input type="hidden" name="cart_id" value="<?php echo $id?>">
<button href="#" id="remove" type="button" onclick="removeItem({{$product->id}})"><i class="fa fa-trash" aria-hidden="true"></i></button>
</form>
</td>
My Javascript Code To Submit The Form
function removeItem(clicked){
document.getElementById('myForm').submit();
}
Controller
This gives me the same id in my controller irrespective of the button clicked
$item = $request->cart_id;
dd($item);
}
You are using the id myForm for every delete form. A page is only allowed to have an id once, because you have it multiple times, it always submits the first one.
Either remove the javascript and let the form submit directly or add unique id's for every form.
You can use AJAX to send request to your controller and add sweetalert inside success function provided by ajax.
HTML FORM
<form style="display: inline!important;" action="{{route('remove.cart')}}" method="POST" name="myForm" id="myForm">
{{csrf_field()}}
<?php
$id = $product->id;
?>
<input type="hidden" name="cart_id" value="<?php echo $id?>">
<button href="#" id="remove" type="button" onclick="removeItem({{$product->id}})"><i class="fa fa-trash" aria-hidden="true"></i></button>
</form>
JQUERY
var id = $('cart_id').value();
$('#myForm').onSubmit(function(e){
e.preventDefault();
$.ajax({
method:'POST',
url:"your link",
data:{
id
},
success: function(result)
{
sweetalert();
}
error: function(err) {}
})
})
}
Thanks all.
Changed my form and javascript to reflect the adjustments.
Form
{{csrf_field()}}
<?php
$id = $product->id;
?>
<input type="hidden" name="cart_id" value="<?php echo $id?>">
<button href="#" type="button" onclick="removeItem({{$product->id}})"><i class="fa fa-trash" aria-hidden="true"></i></button>
</form>
And my JS
function removeItem(clicked){
document.getElementById('myForm'+clicked).submit();
}
</script>
I am facing an issue while validating the input fields inside the form using PHP and JavaScript. I am providing my code below.
<form autocomplete="off" action="<?php echo base_url() . $tourModule; ?>/search" method="GET" role="search" onSubmit="return checkform();">
<input type="text" data-module="<?php echo $module; ?>" class="hotelsearch locationlist<?php echo $tourModule; ?>" placeholder="Tourist Destination" value="<?php echo $_GET['txtSearch']; ?>">
<input type="hidden" id="txtsearch" name="txtSearch" value="<?php echo $_GET['txtSearch']; ?>">
<div class="col-md-12 form-group go-right colspecing col-xs-12 submit text-center">
<button type="submit" class="btn btn-lg pfb0 loader">
<?php echo trans( '012'); ?> </button>
</div>
</form>
<script type="text/javascript">
function checkform(){
console.log('validate form');
var textname=document.getElementById('txtsearch');
if (textname.value=='' || textname.value==null) {
alret('Please select Tourist Destination.');
return false;
}else{
return true;
}
}
</script>
Here I need before submit the form the input field will validate but in my case when I am clicking on submit button checkform function is not executing at all. I need to check that validation.
There is a typo in your code. Change alret to alert
I have a php page. In the bottom there is a contact form. What I want to do is to hide the contact form when the mail is sent and instead show a thank you part. Means that when customer comes first time to the page the form show up. After submit the thank you part show up.
I have seen it done but have no clue how.
I have an idea that when the page loads it must check a variable to see if the mail was sent, but perhaps this is wrong.
When I need stuff like this, I usually name the submit button "submit" and checks if it is set...
<input type="submit" name="submit" value="Send form">
And the php (Use $_GET or $_POST accordingly)...
<?
if(isset($_POST['submit']))
{
// Show "Thank you"
}
else
{
// Show form
}
?>
When I do things like this I tend to add an button to my form and give it a name
<button type="submit" id="submit" name="submit">Submit</button>
Then in my PHP check if the form has been submitted
<?php
if(isset($_POST['submit'])) {
// Actions After Submit
}
else
{
// Load The Form
}
?>
It's rather quite simple; add exit("Message..."); after mail()
In your PHP where the mail(...) is located, you would do the following:
mail($to,$subject,$message,$headers);
exit("Thank you, your message has been sent. <a href='home.php'>Click here</a> to return to our Website.");
Here is a complete basic solution using pure PHP, since no code has been provided.
The following is meant to be run as everything inside the same file.
<?php
if(isset($_POST['send'])) {
// Prepare the email
$to = 'email#example.com';
$mail_from = $_POST['email'];
$subject = 'Message sent from website';
$message = $_POST['message'];
$name = $_POST['name'];
$header = "From: $name <$mail_from>";
// Send it
$sent = mail($to, $subject, $message, $header);
if($sent) {
exit("Thank you, your message has been sent. <a href='home.php'>Click here</a> to return to our Website.");
} else {
echo 'Sorry, your message could not be sent. The error has been logged.';
}
} // closing brace for if(isset($_POST['send']))
?>
<form method="post" action="">
<p>
<label for="name">Name</label>
<input type="text" id="name" name="name" />
</p>
<p>
<label for="email">Email</label>
<input type="text" id="email" name="email" />
</p>
<p>
<label for="message">Message</label>
<textarea id="message" name="message" rows="6" cols="30"></textarea>
</p>
<p>
<input type="submit" name="send" value="Send message" />
</p>
</form>
It's very simple, just if and else,sample form is below
<?php
if(isset($_POST['submit'])) { ?>
//write your other actions on form data
<h2>THANK YOU</h2>
<?php
} else { ?>
<form name="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label><h4>Username:</label>
<input type="text" name="username">
<input type="submit" name="submit" value="submit"/>
</form>
<?php }
?>
I have a search bar that uses a javascript function to submit the form when the user hits Enter (which is working) because it doesn't have a submit button, but I need to use php to handle the data in the textbox on post. The form is submitting, but on post it's not able to grab what was in the search textbox.
Here's the code:
<form id="siteWideSearch" name="siteSearch" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<input id="homeSearch" type="text" maxlength="100" onkeypress="startSiteSearch(event);" />
</form>
Javascript:
if (event.keyCode == 13) {
document.getElementById("siteWideSearch").submit();
}
PHP:
if($_SERVER["REQUEST_METHOD"] == "POST") {
echo "<script type=\"text/javascript\">window.alert(\"Post reached. Yay!!\");</script>";
echo "<script type=\"text/javascript\">window.alert(\"Search Criteria: ".trim($_POST['homeSearch'])."\");</script>";
}
I get the popup saying that post was reached, but the second popup just outputs "Search Criteria: " and nothing else.
You're missing the name attribute on your form input. Without it that value is not submitted.
<input id="homeSearch" type="text" maxlength="100" onkeypress="startSiteSearch(event);" />
should be:
<input name="homeSearch" id="homeSearch" type="text" maxlength="100" onkeypress="startSiteSearch(event);" />
So I have pop-up window where user need to enter name, after clicking submit button this window close.
You can test it here: http://eurokos.lt/under20/button.php (Click 21 button, then try to enter any value and see what happens)
For this pop-up box I've used function:
function popUp() {
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
This function is used for X button to close window:
function closeWindow() {
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none';
}
My button which open pop-up window looks like:
Echo "<input type='button' onclick='popUp();' value='".$i."' />";
And here is PHP_SELF and form:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "</br>You have entered: <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
`
What I need to do that posted result what entered and window not closed?
Maybe I need to use popUp() function again when submitting? But how to do that correctly? Thank you.
Try this:
html:
<form method="post" action="" onsubmit="return display()">
<div id="answer"></div>
<input type="text" name="name" id="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
javascript:
function display(){
var ans = document.getElementById("name").value
document.getElementById("answer").innerHTML="You have entered:"+ans;
return false;
}
Update:
function popUp(){
document.getElementById("answer").innerHTML=""; //Add these in your popup function
document.getElementById("name").value="";
}
First of all i suggest you to avoid PHP_SELF in the action it can be manipulated by people and it's not good.
at top of page try to do :
<?php
$thispage = $_SERVER['PHP_SELF'];
?>
<html>
.
.
.
<form method="post" action="<?=$thispage?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
</html>
Then, using the action for sending data to PHP, will reload the page so you are probabilly losing all the inline fix you did.
Try to get the input values after the submit, assign them to varibles and do, for example:
xmlhttp.open("POST","<?=$thispage?>",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=name");
with an asynchronous call you don't reload the page and you don't lost your changes