I got a problem maybe is simple but dont know how to load jquery_post.php when I send the data for jquery_send.php I resume I send information from jquery_send.php to jquery_post.php and I want that after send the page jquery_post.php load with the data
This is what I have in jquery_send.php:
<html>
<head>
<link href='http://fonts.googleapis.com/css?
family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val();
var vemail = $("#email").val();
if(vname=='' && vemail=='')
{
alert("Please fill out the form");
}
else if(vname=='' && vemail!==''){alert('Name field is required')}
else if(vemail=='' && vname!==''){alert('Email field is required')}
else{
$.post("jquery_post.php",
{
name:vname,
email:vemail
},
function(response,status){
alert("*----Received Data----*nnResponse : " + response+"nnStatus : " + status);
$("#form")[0].reset();
});
}
});
});
</script>
</head>
<body>
<div id="main">
<h2>jQuery Ajax $.post() Method</h2>
<hr>
<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Email</label>
<input type="text" name="email" id="email" placeholder="Email"/></div>
</form>
<button id="btn">Send Data</button>
</div>
</body>
</html>
and in jquery_post.php I have this:
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Welcome ". $name ."!";
?>
It works just fine, but you have a syntax error in you jquery_post.php
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Welcome ". $name ."!";
} // you missed this
?>
it was returning Parse error: syntax error, unexpected end of file
Please try, this may help
<html>
<head>
<link href='http://fonts.googleapis.com/css?
family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val();
var vemail = $("#email").val();
if(vname=='' && vemail=='')
{
alert("Please fill out the form");
}
else if(vname=='' && vemail!==''){alert('Name field is required')}
else if(vemail=='' && vname!==''){alert('Email field is required')}
else{
$.post("post.php",
{
name:vname,
email:vemail
},
function(response,status){
alert("*----Received Data----*nnResponse : " + response+"nnStatus : " + status);
$("#form")[0].reset();
window.location.href = 'post.php';
});
}
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="main">
<h2>jQuery Ajax $.post() Method</h2>
<hr>
<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Email</label>
<input type="text" name="email" id="email" placeholder="Email"/></div>
</form>
<button id="btn">Send Data</button>
</div>
</body>
</html>
And in jquery_post.php I have made some changes When you post data to jquery_post.php it will create a session named "user" you can retrieve name any time from the session as I did.
<?php
session_start();
if(isset($_POST["name"]))
{
$_SESSION['user'] = $_POST["name"];
$name = $_POST["name"];
$email = $_POST["email"];
}
echo "Welcome ". $_SESSION['user'] ."!";
?>
Related
I have created a registration form, but the js file cannot call the php.
Are there anyone can give me some advise?
My question is when I click the submit button, there is no reaction. Do I have any mistakes? Thanks
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="noindex, nofollow">
<title>Tittle</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script type="text/javascript" src="js/registration.js"></script>
<link href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css"
rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"
type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"
type="text/javascript"></script>
<script type="text/javascript" src="js/registration1.js"></script>
<script type="text/javascript">
$(document).on("mobileinit", function() {
$.extend( $.mobile , {
pageLoadErrorMessage: 'Either the page cannot be found or it cannot
be loaded.'
});
});
$(document).on("pageinit","#page", function() {
alert("pageinit is bound!");
});
</script>
</head>
<body>
<div class="container">
<div class="main">
<div data-role="header">
<h1>Register</h1>
</div>
<form class="form" method="post" action="#">
<label>Name :</label>
<input type="text" name="dname" id="name">
<label>Email :</label>
<input type="text" name="demail" id="email">
<label>Password :</label>
<input type="password" name="password" id="password">
<label>Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword">
<button type="button" name="register" id="register"
class="btn">Submit</button>
</form>
</div>
</div>
<div data-role="footer">
<h4>Footer</h4>
</div>
</body>
</html>
Below is the JS
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
Below is the PHP
$hostname = "127.0.0.1";
$username = "root";
$password = "123456";
$connection = mysql_connect($hostname, $username, $password) or die("Could
not open connection to database");
$db = mysql_select_db("mydb", $connection); // Selecting Database.
$name=$_POST['name1'];
$email=$_POST['email1'];
$password= sha1($_POST['password1']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Invalid Email.......";
}
else{
$result = mysql_query("SELECT * FROM registration WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into registration(name, email, password) values
('$name', '$email', '$password')"); // Insert query
if($query){
echo "Successfully Registered";
}
else
{
echo "Error";
}
}
else{
echo "This email is already registered. Please try again";
}
}
mysql_close ($connection);
?>
Your form action is empty try changing action="#" to action="register.php"
I have 22.php that both form and PHP script reside.
Problems;
1) when I submit, result shows below. But duplicates the form.
2) Further entering in the top (above) form, changes the result accordingly.
3) When I enter in the bottom form, then also the result changes accordingly and disappear the bottom from.
What I have tried so far as solutions;
1) removed totally - url: '',
2) replaced to the same page - url: '22.php',
3) replaced to this - var yourData = $(this).serialize();
4) Placed the PHP script just soon after body tag
None of above solve! Please help!
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
Just place PHP code top and put exit();. Here is your full code:
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
exit;
}
?>
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
I'm new to web development, especially PHP, jQuery, AJAX...
I'm trying to make the user enter a name, then the index.html sends it to a php file, the php file saves it to a file of names and changes a div element with the id of status on the website.
I can't figure out the problem, the div element's inner HTML stays "processing..."
index.html
<html>
<head>
<script>
function ajax_post(){
document.getElementById("status").innerHTML = "processing...";
$.post("server.php", { username: $("#userName").val() }, function(data) {
$("#status").html(data);
})
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Username: <input id="userName" name="userName" type="text"> <br><br>
<input name="myBtn" type="submit" value="Check" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>
server.php
<?php
if(!empty($_POST['username'])){
$data = $_POST['username'];
echo 'You are now registered,' . $data;
$fname = "save.text";
$file = fopen($fname, 'a');
fwrite($file, $data . "\n");
fclose($file);
}
?>
I'm assuming my $.post syntax is wrong, but I don't really understand it.
Try this I have executed this code and it worked for me.
Index.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function ajax_post(){
document.getElementById("status").innerHTML = "processing...";
console.log($("#userName").val());
$.post("server.php", { username: $("#userName").val() }, function(data) {
$("#status").html(data);
})
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Username: <input id="userName" name="userName" type="text"> <br><br>
<input name="myBtn" type="submit" value="Check" onclick="ajax_post()"> <br><br>
<div id="status"></div>
</body>
</html>
Server.php
<?php
if(!empty($_POST['username'])){
$data = $_POST['username'];
echo 'You are now registered,' . $data;
$fname = "save.text";
$file = fopen($fname, 'a');
fwrite($file, $data . "\n");
fclose($file);
}
?>
Need quick help, if anyone can...
I have a quite simple html one page with form
and I'm trying to validate it with php (check blanks and verify email)
for some reason something going wrong and it doesn't show me anything
on action form
anyone have any idea? will really help me a lot.
the icons present the obvious (the text is hebrew)
(if someone knows how to validate phone, bless you as well)
the html:
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
<title>Safari Company</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="js/script.js"></script>
</head>
<body>
<div id="top-wrapper">
<div id="top-background">
<p class="image-text">.אפריקה. נקודת מבט חדשה</p>
<p class="credit-english">Ziv Koren</p>
</div>
</div>
<div id="costumer-wrapper">
<div id="info-for-client">
<p class="secondary-text">הדרך לאפריקה מתחילה בטיסה ישירה לטנזניה</p>
<p class="offer-text">פסח 2015 <span>|</span> 9 ימים מלאים</p>
<p class="ratz-border-above">ספארי קומפני בטיסת (סאנדור) אל-על ישירה לטנזניה וחזרה ישירות מזנזיבר. מבחר תוכניות ספארי מותאמות באופן אישי.</p>
<p class="strong">תמיד אמרתם שפעם תעשו את זה. עכשיו זה הזמן</p>
<p class="secondary-text">למידע נוסף, התאמת ספארי אישי </br> והזמנות 03-5617021</p>
</div>
<form method="post" action="confirmation.php" name="myForm" onsubmit="return validate();">
<input type="text" class="name" name="Name" placeholder="שם">
<input type="text" class="email" name="Email" placeholder="דוא״ל" >
<input type="text" class="phone" name="Phone" placeholder="טלפון" >
<textarea placeholder="הערות"></textarea>
<input type="checkbox" > ארצה לקבל עדכונים וחדשות
<button type="submit"> שלח</button>
</form>
<p class="hebrew-credit">זהות ושפה - מוסנזון פורת</p>
</div>
<div id="bottom-background">
<div id="bottom-image"> </div>
<p class="credit-english"></p>
</div>
<div id="footer-wrapper">
<footer>
<p>ספארי, בשפה הסווהילית, פירושו מסע, בשפה שלנו, מסע פירושו יציאה לדרך של גילויים חדשים, מראות, ריחות, טעמים.</br>
תחושה שאין דומה לה. לגלות את אפריקה, בכל פעם מחדש, כבר 20 שנה. נשמח להיות הדרך שלכם לאפריקה.</p>
<p class="adress-border-above"> סעדיה גאון 24, תל אביב טל. 03-5617021 פקס. 15335468614 <span> | www.safaricompany.co.il | info#safaricompany.co.il</span></p>
<img src="images/logo.png">
</footer>
</div>
</body>
<script>
function validate(){
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.Email.value == "" )
{
alert( "Please provide your Email" );
document.myForm.Email.focus() ;
return false;
}
if( document.myForm.Phone.value == "" )
{
alert( "Please provide your Phone" );
document.myForm.Phone.focus() ;
return false;
}
return true;
}
</script>
</html>
the php:(confirmation.php)
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$name = trim($_POST["Name"]);
$email = trim($_POST["Email"]);
$phone = trim($_POST["Phone"]);
if( $name == "" || $email=="" || $phone==""){
echo "Please fill name, email and phone";
exit;
}
require_once("Inc/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
if(!$mail -> ValidateAddress($email)){
echo "You must specify a valid email.";
exit;
}
?>
<html>
<body>
Welcome <?php echo $_POST["Name"]; ?><br>
Your email address is: <?php echo $_POST["Email"]; ?>
</body>
</html>
It probably is overkill to use a custom library just to verify an email address. You could use https://secure.php.net/filter_var with the FILTER_VALIDATE_EMAIL filter. As far as I know, there is no real way of validating phone numbers.
That being said, your PHP error is that you do not close the if statement started on line 2. That causes an unexpected end, as the compiler still wants a closing accolade for your if statement.
EDIT: There is a very good SO answer for validating phone numbers.
There are a few things going on with the approach to your script.
Here is what I came up with that works on the script page.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["Name"]);
$email = trim($_POST["Email"]);
$phone = trim($_POST["Phone"]);
if( $name == "" || $email=="" || $phone==""){
$error = "Please fill name, email and phone";
}
}
else {
$error = "ERROR if someone came here directly";
}
?>
<html>
<body>
<?php if(isset($error)): ?>
<p><?php echo $error; ?></p>
<?php else: ?>
Welcome <?php echo $_POST["Name"]; ?><br>
Your email address is: <?php echo $_POST["Email"]; ?>
<?php endif; ?>
</body>
</html>
EDIT: To address the email validation you would use this to check if true or false:
This method checks if the email is NOT valid.
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid email";
}
The following contact form is not validating when submitting from an iphone...
It can be previewed here: loaistudio.com/contact
When I tried to submit the form without felling the fields, it opened a new blank page showing number 1 only on the top left side "which is not suppose to do at all" and actually sent the form empty... It does not do that on desktop.
I played around with the code trying to find the issue but no idea where is the problem! please help.
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['message'])
&& isset($_POST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "EMAIL GOES HERE";
$subject = "New Message From: $name";
$message = "$message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = ( mail($to, $subject, $message, $headers) );
if( isset($_POST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<title>Contact us | Website</title>
</head>
<body>
<div class="wrapper" id="contactPage">
<div class="content">
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<!--Contact Form-->
<form action="contact.php" id="contactForm" method="post" name="contactForm">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" placeholder="Enter Name" required="" type="text">
</div>
<div class="email">
<p>Email Address</p>
<input name="email" placeholder="Enter Email" required="" type="email">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" required=""></textarea>
</div>
<button id="submit" type="submit">Send</button>
</form>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
</body>
</html>
you are adding jquery at the end of the html but you are using jquery before that, so javascript breaks with Uncaught ReferenceError: $ is not defined.
try moving this line to header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
This is code You have added AND THEN INCLUDED JQUERY, :) SO USE JQUERY IN HEADER !