I am absolute begginner for the programming. Here I want to pass a argument to $('form').submit(function () {. Just I want to pass the email value to .submit() function, that has been created like this,
Here is the HTML code,
<div id="friends">
<?php
$query=$pdo->prepare("SELECT DISTINCT * FROM users as u
WHERE EXISTS (SELECT * FROM appointment as a
WHERE u.user_id = a.user_id AND
a.p_id= '".$_SESSION['p_id']."')");
$row=$query->execute();
$rs=$query->fetchAll(PDO::FETCH_OBJ);
foreach ($rs as $message){
$filename= $message->image;
$filepath="../../adminpanel/profile/blog/";
?>
<div class="friend">
<?php
printf(
'<img class="inline-block" src="data:image/png;base64, %s" alt="user" />',
base64_encode(file_get_contents($filepath.$filename ) )
);
?>
<p>
<strong> <?php echo $message->username ?></strong> <br>
<span id="email"><?php echo $message->email ?></span>
</p>
<div class="status available"></div>
</div>
<?php } ?>
Here is the HTML for submit button
<form class="" id="msgform" action="chat.php" method="post">
<div id="sendmessage">
<input type="text" placeholder="Send message..." class="textarea" name="message"/>
<button id="send" class="textarea" ></button>
</div>
</form>
Below is the javascript code, that how to set email to html to appear.
$(".friend").each(function(x){
$(this).click(function(){
var name = $(this).find("p strong").html();
var email = $(this).find("p span").html();
LoadChat(email);
$("#profile p").html(name);
$("#profile span").html(email);
});
});
I have passed this email variable to submit function, but always takes the email of last user. Here is the .submit function to sent data to server.
$('form').submit(function() {
const email = <?= json_encode($message->email) ?>
var message = $('.textarea').val();
if ($(".textarea").val()) {
$.post("handlers/messages.php", {
action: "sendMessage",
message: message,
email: email
}, function(response) {
if (response == 1) {
LoadChat();
document.getElementById('msgform').reset();
}
});
} else {
myFunction();
}
return false;
})
Just I want to pass the particular email value to submit function. Please help me may highly appreciated and thanks in advance.
$('form').submit(function() {
var email = $('#email').val();
var message = $('.textarea').val();
if ($(".textarea").val()) {
$.post("handlers/messages.php", {
action: "sendMessage",
message: message,
email: email
}, function(response) {
if (response == 1) {
LoadChat();
document.getElementById('msgform').reset();
}
});
} else {
myFunction();
}
return false;
})
You were getting the email which was printed by php (server side). You need to send what is on client or browser side.
var email = $('#email').val();
This will solve your issue
Related
Hi i am trying to update data in a database from a form on the same page as the php code without redirecting/reloading the page.
I tried this tutorial but that didn't work: http://www.formget.com/form-submit-without-page-refreshing-jquery-php/
Update code:
<?php
include "db.php";
session_start();
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
?>
Profilecomplete.js:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {
value: name
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
The form:
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate">
<label for="name">Value</label>
</div>
<button type="submit" id="submit" class="btn-flat">Update</button>
</form>
Use this, it's working already.
index.php
<form method="post">
<input type="text" id="name">
<input type="submit" id="submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var nameInput = $("#name").val();
var name = {
'name' : nameInput
}
if (nameInput == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {value: name}, function(data) {
alert(data);
//$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
profilecomplete.php
<?php
$_POST = array_shift($_POST); // array_shift is very important, it lets you use the posted data.
echo $_POST['name'];
?>
if you want a more simple way.
try to use $.ajax()
It looks like the issue, or at least, one of the issues, is on this line;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
You are opening and closing the single quotes twice, here
WHERE username='$_SESSION['user']'
Try using this instead;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='" . $_SESSION["user"] . "'");
How your click event can occur even if you are not preventing the default behavior of the form submit button. Make the submit input as a button or use event.preventDefault() to submit the form via ajax.
<?php
include "db.php";
session_start();
if(isset($_POST)) {
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='{$_SESSION['user']}'");
echo ($query) ? "Updated" : "Not Updated";
exit;
} else {
?>
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate" name="name">
<label for="name">Value</label>
</div>
<button type="button" id="submit" class="btn-flat">Update</button>
</form>
<?php } ?>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name === '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {name: name}, function(data) {
alert(data);
$('form')[0].reset(); // To reset form fields
});
}
});
});
</script>
Im all new to ajax and jquery so iam asking u guys for some help. I have to forms that one creates a new user and second logs the user in.
The functions work greate, but i want to create alert boxes for success or failure of the functions.
And i dont know how... Here is my code
HTML
<!-- Formular for signing up -->
<h4 class="form-headline"> Not a member? Sign up here </h4>
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" id="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" id="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" id="newclub">
</div>
<input type="button" id="btn-reg" class="btn btn-success" value="Sign up!">
</form>
Script
// -----------------Registration of new user----------------------
console.log('Script loaded...');
// Calling for the method - reg
$("#btn-reg").on("click", reg);
function reg(e) {
e.preventDefault();
console.log('Klick, klick...');
// Declaring variables
var newusername=$("#newusername").val();
var newpassword=$("#newpassword").val();
var newclub=$("#newclub").val();
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
console.log(data);
});
}
PHP
// Creating instance of the class userClass.php
var_dump($_POST);
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$user->newUsers($newusername, $hashpassword, $newclub);
} else {
}?>
OOP
// >>>>>>>>>>>>>>>> Function for saving new user to database
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
}
}
Just noticed that you are using function to create a new user, my bad again
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$status = $user->newUsers($newusername, $hashpassword, $newclub);
if($status) {
echo json_encode(array("status" : "success"));
}else {
echo json_encode(array("status" : "failed"));
}
}
Make a return from this function
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
return true;
}else {
return false
}
}
this will be the same
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
var object = JSON.parse(data);
alert(object.status);
// or you can add if else by using the status
});
}
You could just echo the script tag.
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
}
}
For the Script block.
var posting = $.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
});
posting.done(function( data ) {
alert( "Data Loaded Ok");
});
posting.fail(function( data ) {
alert( "Error loading data");
});
Hope this helps you.
In the following code, I have a contact form and in that form there is an email validation script. As a result of validation, I want the error message to be shown in a div called confirmation without reloading the page. Also, if the email is valid, the mail will be sent and I want the Thank you message to be shown in the same div confirmation. The problem is what can I do to prevent reloading the page and let the error message or the thanks message shows in the confirmation div?
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11#gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>
Thanks
<input type="text" name="from" id ="from">
Call example:
var request = $.ajax({
url: "file.php",
type: "POST",
data: { email : $('#from').val() }
});
request.done(function( msg ) {
//handle HTML
});
request.fail(function( jqXHR, textStatus ) {
//Handle problem at server side
});
PHP Side
<?php
$email = $_POST["email"]
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return 'valid';
} else {
return 'no_valid';
}
}
echo spamcheck($email);
There's no way you could do that with just PHP.
What you're looking at is commonly known as AJAX, and uses client-side language (Javascript)
It's very common, and widely used on the internet. You can find many examples and production-ready scripts by searching ajax on google.
More informations here : http://www.w3schools.com/ajax/
as title, I am a beginner about website design.
Please never mind if I ask a stupid question.
while i send the form, it didnt work.
here is html:
<form id="form1" name="form1" action="toSQL.php" method="POST" accept-charset="utf-8">
<input type="text" name="Cliname" id="textfield" maxlength = "10" />
<textarea name="message" id="message" rows="3" maxlength = "20" ></textarea>
<input type="submit" value="submit" id="submit" />
</form>
<div class="alert"></div>
and here is js:
<script type="text/javascript">
$(document).ready(function() {
var form = $(this) ;
var submited = $('#submit') ;
var alerted = $('.alert') ;
form.on( 'submit', this, (function(event) {
event.preventDefault();
if ( $.trim($form.find('input[name="Cliname"]').val()) == "" || $.trim($form.find('input[name="message"]').val()) == "" ) {
alert( "please enter!!" ) ;
return ;
}
else {
$.ajax({
url: 'toSQL.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alerted.fadeOut();
},
success: function(data) {
alerted.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
},
error: function(e) {
console.log(e)
}
});
}
}));
});
</script>
server side php:
<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['Cliname']) AND isset($_POST['message'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (send($name, $message)) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
function send( $name, $message ) {
$time = date("Y-m-d H:i:s");
$mysqlConnection=mysql_connect("localhost", 'root', '') or die("connect error!");
mysql_select_db('test') or die ("db error!");
$queryStr="INSERT INTO fortest (time, message, name)
VALUES ( '$time', '$message', '$name')";
mysql_query($queryStr,$mysqlConnection) or die(mysql_error());
return true ;
}
?>
here is the website i reference : http://www.w3bees.com/2013/08/submit-form-without-page-refresh-with.html
Did i miss something?
As a couple people have mentioned already, you are trying to serialize your entire dom object, which isn't going to work. Change it to var form = $("#form1") and it should work.
I recommend you open the webpage in chrome dev tools and click the network tab, click preserve log and then submit the form. When it is submitted you'll see the full headers that were sent to the server and can verify it works correctly to help narrow down the problem
I'm new to ajax concept. Here i'm trying to insert the user details(signup form) into the database. it inserted the datas into the db succesfully. But, ajax is my problem.
1) i didn't get any error message if form fields are empty. you can see my below codes i've done validation on post.php page. but, it doesn't return the error values. 2) it stores the empty values into database. 3) if datas stored successfully i want to get the success message & if datas failed to store in db i want to get the error message. How should i do these all things?
Ajax.js
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function(msg) {
if(msg=='error_n')
{
$("#e_name").html('Name required');
}
if(msg=='error_m')
{
$("#e_mobile").html('Mobile required');
}
//success and error alert
if(data="inserted")
{
alert("insertion success");
}
else
{
alert("falid to insert into database");
}
}
});
e.preventDefault();
});
});
Post.php
<?php
include_once('config.php');
$name = trim($_POST["name"]);
$mobile = trim($_POST["mobile"]);
if($name == "")
{
echo 'error_n';
}
if($mobile == "")
{
echo 'error_m';
}
try
{
$stmt = $conn->prepare("INSERT INTO sample ( Name, Mobile ) VALUES ( ?, ? )");
$conn->errorInfo();
$stmt->bindParam('1', $name, PDO::PARAM_STR);
$stmt->bindParam('2', $mobile, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database' .$e->getMEssage();
}
?>
Homepage.php
<p>register here</p>
<div id="light" class="white_content">
Close
<form>
<input type="hidden" name="form" value="values" />
name : <input name="name" id="name" type="text" /><span id="e_name"></span> <br />
mobile : <input name="mobile" id="mobile" type="text" /><span id="e_mobile"></span> <br />
<input type="submit" value="submit" />
</form>
</div>
<div id="fade" class="black_overlay"></div>
After your error messages are returned, you need to stop the script execution. Your current code still tries to add the values and hence overrides your custom error messages. Most probably then your PHP returns your exception message and which is not what your JavaScript is expecting.
if($name == "")
{
echo 'error_n';
die(); // Stop here
}
if($mobile == "")
{
echo 'error_m';
die(); // Stop here
}
Also add echo 'inserted'; when your database insert is successful.