I've got a wall/social system (much like facebook) where there's statuses, but I want to be able to like, dislike and comment on a status without the page reloading, with the form below how could I complete this?
if(empty($_GET['action'])){
postupdate();
if(isset($_POST['sComment'])){
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$comment = mysqli_real_escape_string($dbc, trim($_POST['comment']));
$sid = mysqli_real_escape_string($dbc, trim($_POST['sID']));
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query = "INSERT INTO comments (`user`, `post`, `time`, `content`) VALUES ('".$_SESSION['user_id']."', '$sid', NOW(), '$comment')";
$data = mysqli_query($dbc, $query);
}
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query = "SELECT posts.*, user.* FROM posts JOIN user ON user.user_id = posts.user_id JOIN friends ON friends.user = ".$userinfo['id']." AND friends.with = posts.user_id ORDER BY posts.post_id DESC";
$data = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($data)){
echo'<div class="shadowbar">
<div class="postedBy"><b> Posted by '. $row['firstname'] .' '. $row['lastname'] .' On '. date('M j Y g:i A', strtotime($row['postdate'])) .'</b></div>';
$parsed = $parser->parse($row['post']);
echo '<pre>'.$parsed.'</pre>
<hr>
<form method="post" action="index.php" class="commentForm">
<fieldset>
<div class="input-group">
<textarea cols="150" rows="1" style="resize: none;" placeholder="Comment..." class="form-control" type="text" id="commentBox" name="comment"></textarea>
</div>
<input type="hidden" value="'.$row['post_id'].'" name="sID">
</fieldset>
<input class="Link LButton" type="submit" value="Add comment" name="sComment" />
</form>
</div>';
}
echo '</div>';
}
the form can be changed to fit the code. I'm assuming it's JavaScript that I will need to use.
Here's some code to get you started.
First of all, add an ID or class in order to easily identify the form(s):
<form method="post" action="index.php?action=comment" class='commentForm'>
Since you tagged jQuery, I shall use that:
$(document).on('submit', '.commentForm', function(e) {
e.preventDefault(); // Prevents the default page reload after form submission
$.ajax({
type: $(this).prop('method'),
url: $(this).prop('action'),
data: $(this).serialize()
}).done(function() {
// Do something after it submits
alert('Thanks for the comment!');
}).fail(function() {
// There was an error
alert('An error occurred');
});
});
You can read more about jQuery.ajax in the jQuery documentation.
Yes, you'll need to use JavaScript to send a POST request to the server. There are several jQuery plugins, but none of them are perfectly fit to your needs, so I recommend that you write your own.
The workflow should be like this:
Initiate an XMLHttpRequest object
Set the target equal to the form's action= attribute (extra points if you can get this information from the DOM without typing it manually again)
Grab the data you want to submit from the form (again, using DOM)
Send a POST request with the data you got from the form, to the target page.
Target page should return a response of some sort, to tell the client that the submission went smoothly
Client reads that response and displays a success message to the user.
Here is something that should be useful for you.
http://www.9lessons.info/2009/11/facebook-style-application-with-jquery.html
In short you need to use ajax to post request to your form's action url. you can use jQuery for that.
http://api.jquery.com/jquery.ajax/
Use ajax to send and receive data. Use the code below
<form method="post" action="index.php?action=comment" id="Form">
<fieldset>
<legend>Status Update</legend>
<div class="input-group">
<textarea cols="150" rows="5" style="resize: none;" placeholder="Comment..." class="form-control" type="text" id="text" name="comment"></textarea>
</div>
<input type="hidden" id="hidden" value="$statusID" name="sID">
</fieldset>
<input class="Link LButton" type="submit" value="Add comment" name="submit" />
</form><div class="container"></div>
<script>
$(document).ready(function(){
$('#Form').submit(function(e) {
e.preventDefault(); // This will prevent the form to be submitted
var hidden=$("#hidden").val();
var comment=$("#text").val();
$.post(
"index.php", {
comment: comment,
sID:hidden
},
function (data) {
$('#check').html(data);
});
});
</script>
Your PHP file should look like this
<?php
$comment=$_REQUEST['comment'];
$sID=$_REQUEST['sID'];
echo $comment."<Br>".$sID;
?>
Hope this helps you
Related
I have a form that I use to send data to image.php from my home.php page.
<form class="d-flex" action="" method="post">
<input class="rounded-0 form-control" type="text" name = "name" placeholder="Explore. . ." aria-label="Search">
<button class="border searchfeature" id= "show" type="submit"><i class="fa fa-search"></i></button>
</form>
When I put action = "image.php" the page takes me to image.php page and displays what I want which is the image I type in the search form. However what I want is the action to remain action="home.php" on the same page but get the image back and display it in the home.php page after the form is submitted.
I hear Sessions are a good way to solve this but I have no idea how to display it back in the same page once the form is submitted. I know one way to solve this is to put the image.php code in the home.php page but I am keeping the codes separate to keep it cleaner.
Thanks!
Form View:-
make a id="createForm" in your <form>
and id = "name" in input field.
<form id="createForm" class="d-flex" action="" method="post">
<input class="rounded-0 form-control" type="text" name = "name" id = "name" placeholder="Explore. . ." aria-label="Search">
<button class="border searchfeature" id= "show" type="submit"><i class="fa fa-search"></i></button>
</form>
Jquery Ajax Code:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#createForm').on('submit', function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
type: "POST",
url: "data.php",
data: {name: name},
success: function(data){
$("#createForm")[0].reset();
$('#table1').html(data);
}
});
});
});
</script>
In your HTML
<div id="table1">
//Let jQuery AJAX Change This Text
</div>
data.php Page
<?php
//data.php
if(isset($_POST["name"]))
{
$name = $_POST["name"];
// select query with where clause name condition
echo $output;
}
?>
You can do this in several ways it all depends on what is going on on the 2nd file - are we staying there or just coming back with a response to the 1st one? because you can:
1st file:
<?php
if(isset($_GET['response'])){
echo 'The response: ' . $_GET['response'];
} else {
?>
<form id="createForm" class="d-flex" action="2nd.php" method="post">
<input class="rounded-0 form-control" type="text" name = "name" id = "name" placeholder="Explore. . ." aria-label="Search">
<button class="border searchfeature" id= "show" type="submit"><i class="fa fa-search">go</i></button>
</form>
<?php
}
2nd file:
<?php
$name = $_POST['name'] . " - Received!!!";
header("Location: 1st.php?response=$name");
The response will be in 1st.php:
The response: SomeNameValue - Received!!!
This is a very very simplified way - using header and $_GET method in the first file when the $_GET['response'] exists it shows the response and skips the form...
If you are planning on displaying something in the 2nd.php file than header is available for you but you can either create another form and send the response in a hidden input or use Javascript to window.location.assign("1st.php?response=") where $name variable is the $_POST['name'] after we processed it in 2nd.php.
But the first example is just form and PHP.
I decided to switch from a WordPress website to a self-made with HTML, CSS and JS, aiming to improve performance. So far, relying on tutorials, I've managed to deal with almost every issue, but I just can't get the contact form work the way it worked in WP. So far it redirects me to another page that shows the success message, which is just ugly.
Basically, I want the submit button to do 3 things: 1. Not to redirect me to another page. 2. Reset the form. 3. Display a success message.
Read many similar questions here, but as I am completely unfamiliar with AJAX, finally decided to post this question. Here's my code:
Index.html:
<div>
<form method="post" action="form.php" name="myForm">
<input name="name" placeholder="Nombre" required>
<input name="email" type="email" placeholder="Correo Electrónico" required>
<textarea rows="10" name="message" placeholder="Mensaje" required></textarea>
<input id="submit" name="submit" type="submit" value="Enviar Mensaje" class="boton-rojo">
</form>
</div>
and in form.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="De: $name \n Mensaje: $message";
$recipient = "contacto#mydomainname.cl";
$subject = "Mensaje desde el sitio web";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Tu consulta fue recibida";
?>
Any help would be much appreciated.
Thanks.
Put an ID to your form
<form id='myForm'>
....
</form>
Use jQuery (For easy code)
....
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</body>
Use $.ajax
$('#myForm').submit(function(e) {
e.preventDefault(); // prevent from submitting form directly
$.ajax({
url: 'form.php',
method: 'post',
data: $("#myForm").serializeArray() // convert all form data to array (key:value)
})
.done(function(response){
alert(response); // show the response
$("#myForm").reset(); // reset the form
})
.fail(function(error){
alert(error); // show the error.
});
})
I am building a basic contact form (three fields) for my site. I have the form built in HTML and CSS; all I had to do was build the PHP to make the form responses send to my email. I found a tutorial and built the PHP file (which worked), but wanted the form to submit in the background and not leave the original page. I found an online tutorial to do that using Ajax, and after some tweaking, I got it mostly to work. The only issue I'm having now is that when I receive the email with the response, the message field is coming back as "undefined."
I have a good grasp on HTML and CSS, but PHP and JS are new to me (just started learning them for this project), so any help on how to fix this issue and possibly correct any wrong code would be a huge help. I've included the form HTML, PHP, and JS below (PHP and JS are both named 'contact.[filetype]'.
HTML
<div id="contact_form">
<form name="contact" action="">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" required/>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" required/>
</div>
<div class="field">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="3"></textarea>
</div>
<ul class="actions">
<li><input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" /></li>
</ul>
</form>
</div>
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$formcontent="From: $name \n Message: $comments \n";
$recipient = "alltheladsmedia#gmail.com";
$subject = "Message From Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' target='_blank' style='text-decoration:none;color:#505050;'> Return Home</a>";
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name === "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email === "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("input#message").val();
if (message === "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
$.ajax({
type: "POST",
url: "contact.php",
data: {name:name,email:email,message:message},
success: function() {
$('#contact_form').html("<div id='success'></div>");
$('#success').html("<h2>Your message was successfully submitted!</h2>")
.append("<p>We will get back to you within 24-48 hours.</p>")
.hide()
.fadeIn(1500, function() {
$('#success');
});
}
});
return false;
});
});
In your markup the field's id is "comments" but you are looking for "message" in your JS and PHP.
you have print your mail result
if(#mail($recipient, $subject, $formcontent, $mailheader))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
Make few changes if you are using jquery 3.
Change this
$(".button").on("click", function() {
// Validation here
// Put ajax outside this block
});
Edit html form like this code.
Check the dev. tools if the action attribute is added correctly by the php.
<form id="contact" name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" >
And ajax call into this
$("#contact").on("submit", function(e) {
e.preventDefault(); // Now the page won't redirect
var url = $(this).attr("action");
// Check console if contact is printed after the form is submitted
// If contact is printed the url is right
console.log(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialiseArray(), // Found a typo here fixed
success: function() {
// Your stuffs
}
});
});
Don't put the ajax call inside the input field verification.
Let me know if you find any issue so I can fix my code.
I want to have server side validation. Is there a way how can I have the alert like this image whenever the user input the data like email that exist in my database, the alert will appear when I hit the sumbit button. Thanks in advance. :D
Here's my create_acc.html
<form action="create_acc.php" method="POST" id="fieldform">
<dl>
<p><dt>Email Address:</dt>
<dd>
<input type="text" name="e-mail" id="e-mail" class="text" placeholder="Your Email will be your log in" autocomplete="off">
</dd>
</p>
<p><dt>Create Password:</dt>
<dd>
<input type="password" name="password" id="password" class="text" placeholder="Remember your password" autocomplete="off">
</p>
<p>
<p><dt>Your Complete name:</dt>
<dd>
<input type="text" name="name" id="name" class="text" placeholder="Your Complete name" autocomplete="off">
</p>
<p>
<dt>
<input type="submit" value="Submit">
</dt>
</p>
</dl>
</form>
Here's my create_acc.php
<?php
session_start();
$email = $_POST['e-mail'];
$name = $_POST['name'];
$pass = $_POST['password'];
$hash = hash('sha256',$pass);
function createSalt(){
$text = md5(uniqid(rand(), true));
return substr($text,0,3);
}
$salt = createSalt();
$pass = hash('sha256',$salt.$hash);
$conn = mysqli_connect('localhost','root','','mydb');
$email = mysqli_real_escape_string($conn,$email);
$query = "INSERT INTO customers(Email,Password,Name,salt) VALUES('$email','$pass','$name','$salt')";
mysqli_query($conn,$query);
mysqli_close($conn);
header('Location: index.php');
?>
You could use ajax to do this. When the user submits the form you would send an ajax request with the form data to your php script, the script will then respond with a value that you use to deside if you should display an alert or not, here is a basic example using jquery:
$(document).ready(function() {
// catch submit events for your form
$('#your-form-id').submit(function() {
// make an ajax request to your validation script
$.ajax{(
url:'create_acc.php',
type:'POST',
data:$(this).serialize(),
dataType:'json',
success:function(response) {
if(!response.success) {
alert('Something went wrong!');
}
}
});
return false;
});
});
Then in your php script you return a code telling the client how it went:
// create_acc.php
// I assume the form only has one value 'email'
$success = false;
if(isset($_POST['email'])) {
// here you would check if the email already
// exists in the database
$query = "SELECT * FROM <table> WHERE email = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('s', $_POST['email']);
// execute the query and check if a row was returned
}
// if everything went fine you should change success to true
// return json response to client
$response = array('success' => $success);
print json_encode($response);
exit;
I have a script that I would like to have run using jQuery and PHP. After a user logs in, they fill out a form and hit the 'save' button. The jQuery attaches a click event which runs the PHP script. I've got console logs at certain break points and I'm showing that my script is actually stopping at a certain point, however, I have no idea why.
TABLE CREATION AND DATABASE CONNECTION
$create_table_scenarios = "CREATE TABLE IF NOT EXISTS $scenarios(id VARCHAR(25), PRIMARY KEY(id))";
mysqli_query($connect, $create_table_scenarios);
I know that the connection is being made and the table is being created because it shows up in the database.
THE FORM
<form id="scenario_builder" method="post" action"../php/processing.php">
<div id="form_general" class="form_view">
<h3>General Info</h3>
<div class="half">
<fieldset for="center_menu">
<label>Center:</label>
<div class="select" name="center_menu" id="center_menu">
<div class="arrow"></div>
<div class="option-menu">
<div class="option"></div>
<?php
$query = "SELECT * FROM $centers";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$center_name = "{$row['center']}";
echo "<div class='option'><input type='hidden' name='center' id='center' value='" .$center_name ."' />" .$center_name ."</div>";
}
?>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<input type="submit" name="save" id="save" class="button" value="Save" />
</form>
PROCESSOR
ob_start();
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$center = $_POST["center"];
$query = "INSERT INTO `$scenarios`(`id`) VALUES('" .$center ."')";
mysqli_query($connect, $query);
}
ob_clean();
echo json_encode(array("success" => 1));
jQUERY
$("input[id='save']").on("click", function(){
console.log("Save clicked");
$.post("..php/processing.php", {}, function(response){
if(response.success == "1"){
console.log("Data entered.");
}
else{
console.log("Data not entered.");
}
}, "json");
})
The only console message I'm getting is the "Save clicked" one. So, for some reason, the $.post function isn't running. Can someone show me why based on the code I've provided? On a different note, yes, I understand that my queries are vulnerable to injection, I'm just trying to get the basics to work right now.
From what i see you are double submitting the form. You once submit the form due to the form's submit button push and the second time you submit the form with the AJAX request due to the event handler you added to the button. You either let the form submit with a regular POST, or on the submit button press you prevent the event's default behavior and submit the data by AJAX.