Sorry to ask it again, but I checked almost all the q&a's on the topic and still couldn't solve it. Here is my form.php and creditform.php
Edit1.Changed the .get to .post
Edit2.I'm getting errors of undefined variable "name" "email" "address" "income" etc (in short for all of them) in creditform.php
What I want to do is just insert all the inputs into the table in db.
HTML
<!-- End crumbs-->
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="php/creditform.php" method="post">
<input type="text" placeholder="Name" name="name" required>
<input type="email" placeholder="Email" name="email" required>
<input type="text" placeholder="Address" name="address" required>
<input type="number" placeholder="Monthly income before taxes" name="income" required>
<input type="number" placeholder="Amount Needed" name="amount_needed" required>
<input type="number" placeholder="Phone" name="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button"></div></div>
<div id="result"></div>
</form>
</div>
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>
FORM.PHP
<?php
include('db.config.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $email = $address = $income = $amount_needed = $phone = '';
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// check form fields
if(empty($name)){
$error .= 'Enter name <br />';
}
if(empty($email)){
$error .= 'Enter email <br />';
}
// check if errors exist
if(!empty($error)){
echo $error;
} else {
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
}
}
}
print_r($_POST);
?>
CREDITFORM.PHP
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$income = $_POST['income'];
$amount_needed = $_POST['amount_needed'];
$phone = $_POST['phone'];
}
print_r($_POST);
?>
It's obvious that I'm missing something, please correct me...
Thanks for your time
You need to send a POST request for the $_POST array to have anything in it.
$.get(url, datos, function(resultado) {
$('#result').html(resultado);
});
This sends a GET request (check $_GET). You want to use $.post here instead.
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
Here is a simple Ajax call to a Php File by an event : Click on a button.
In your example you must use POST method because you use :
$_POST['something'];
Javascript client side :
$("body").on("click", "#mybutton", function() {
var mydata = $("#form").serialize();
$.ajax({
type: "POST",
url: "/api/api.php",
data: {data : mydata},
timeout: 6e3,
error: function(a, b) {
if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
$("#err-state").slideDown("slow");
$("#err-state").html("An error occurred: " + b);
}
},
success: function(a) {
var e = $.parseJSON(a);
if (true == e["success"]) {
$("#result").html(e['message']);
// here is what you want, callback Php response content in Html DOM
}
}
});
return false;
});
Next in your Php code simply do after any success function :
if ($result) {
echo json_encode(array(
'success' => true,
'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
));
}
Okay, I practiced more on ajax - json - php and in the end this was my solution and my latest code.
Thanks for all answers and suggestions. Hope this also helps to someone.
Still open to any kind of advice to improve.
<?php
include('db.config.php');
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
die();
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="creditapp.php" method="post">
<input type="text" placeholder="Name" name="name" id="name" required>
<input type="email" placeholder="Email" name="email" id="email" required>
<input type="text" placeholder="Address" name="address" id="address" required>
<input type="text" placeholder="Monthly income before taxes" id="income" name="income" required>
<input type="text" placeholder="Amount Needed" name="amount_needed" id="amount_needed" required>
<input type="text" placeholder="Phone" name="phone" id="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button sub"></div>
</div>
</form>
</div>
<script>
$(document).ready(function() {
$('.sub').click(function(e){
e.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
address = $('#address').val(),
income = $('#income').val(),
amount_needed = $('#amount_needed').val(),
phone = $('#phone').val();
$.ajax({
url: "creditapp.php",
type: "POST",
data: {
name: name,
email: email,
address: address,
income: income,
amount_needed: amount_needed,
phone: phone,
submit: "submit"
}
}).done(function(msg){
$('.right-info').html('<pre>' + msg + '</pre>');
})
})
});
</script>
The problem you are having is with your javascript. You wait for the submit and than you do an ajax GET request, you need a POST.
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>
Related
I'm working on a form validation with jQuery and PHP, currently using the AJAX jquery method. PHP file doesn't show up in the Networks tab in the browser developer console. I debugged my code and couldn't see where it went wrong.
Can you guys please give me a few pointers to where I missed out in my code?
HTML
<form action="process.php" method="POST">
<h1 class="display-4 form-heading col-md-9">Now's the time to adopt a <span class="highlight">better</span> email security solution</h1>
<p class="form-copy col-md-9">Let us help you migrate and enhance your email security.</p>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputFirstName">First Name:</label>
<input type="text" class="form-control" id="inputFirstName" name="FirstName" placeholder="333333" required>
</div>
<div class="form-group col-md-6">
<label for="inputLastName">Last Name:</label>
<input type="text" class="form-control" id="inputLastName" name="LastName" placeholder="Last Name" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail">Email Address:</label>
<input type="email" class="form-control" id="inputEmail" name="Email" placeholder="aaa" required>
<div class="form-valid-feedback" id="email-error"></div>
</div>
</form>
Javascript
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
//beginning AJAX
function checkEmail(email){
var re = /\S+#\S+\.\S+/;
return re.test(email);
}
function checkPhoneNumber(phone){
var phonePattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
return phonePattern.test(phone);
}
var FirstName = $("#inputFirstName").val();
var LastName = $("#nputLastName").val();
var email = $("#inputEmail").val();
var companyName = $("#inputCompanyName").val();
var phone = $("#inputPhone").val();
var submit = $("#inputsubmit").val();
var formData = {
FirstName : $("#inputFirstName").val(),
LastName : $("#nputLastName").val(),
email : $("#inputEmail").val(),
companyName : $("#inputCompanyName").val(),
phone : $("#inputPhone").val(),
submit: $("#inputsubmit").val()
};
$.ajax({
type: 'POST',
url : 'process.php',
data:formData
})
if(!data.success){
if(data.errors.firstName){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.firstName);
}
if(data.errors.LastName){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.LastName);
}
if(data.errors.email){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.email);
}
if(data.errors.CompanyName){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.CompanyName);
}
if(data.errors.Phone){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.Phone);
}
}
else if(!checkEmail(email)){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html('Please enter a vlid email address: example#example.com');
}
else if (!checkPhoneNumber(phone)){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html('Please enter a vlid Phone Number: 333-333-3333');
}
else{
$('form').append('<div class="alert alert-success" id="success">' + data.message + '</div>');
}
})
.fail(function(data){
console.log(data)
});
});
//end of submit event handling
});
PHP
<?php
$errors = array();
$data = array();
//starting the validation of variables
if (empty($_POST['FirstName']))
$errors['FirstName'] = "First Name is required.";
if (empty($_POST['LastName']))
$errors['LastName'] = "Last Name is required.";
if (empty($_POST['Email']))
$errors['Email'] = 'Email is required.';
if (empty($_POST['CompanyName']))
$errors['CompanyName'] = 'Company Name is required.';
if (empty($_POST['Phone']))
$errors['Phone'] = 'Phone Number is required.';
if(! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
}
else{
//when everything is free of errors
$data['success'] = true;
$data['message'] = 'Success!';
}
echo json_encode($data);
?>
Whenever I hit submit button my first name, last name and email are empty even when they are filled up properly so they return red color fonts.
Here is the PHP code:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$college = mysqli_real_escape_string($conn, $_POST['college']);
$pwd = mysqli_real_escape_string($conn, $_POST['password']);
// Error handlers
$errorfirst=false;
$erroremail=false;
$errorlast=false;
$errorpwd=false;
// Check for empty fields
if (empty($first) || empty($email) || empty($pwd)) {
echo "
<span class='form-error'>*Please check one of the fields before submitting<br></span>
<span class='form-error'>*Please check first name <br></span>
<span class='form-error'>*Please check last name <br></span>
<span class='form-error'>*Please check email <br></span>
";
$errorfirst=true;
$erroremail=true;
} else {
// Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
echo "<span class='form-error'>*write properly</span>";
$errorfirst=true;
$errorlast=true;
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>*write a proper email</span>";
} else {
$sql = "SELECT * FROM name WHERE user_email='$email'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
echo "<span class='form-error'>This E-mail ID is already existed</span>";
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
// Insert the user into the database
$sql = "INSERT INTO name (id,user_first, user_last, user_email, user_uid, user_pwd) VALUES (NULL,'$first', '$last', '$email', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
}
}
}
}
} else {
header("Location: ../signupform.php");
exit();
}
?>
<script type="text/javascript">
$('.first-input,.last-input,.email-input').removeClass('input-error');
var errorfirst="<?php echo '$errorfirst'; ?>";
var errorlast="<?php echo '$errorlast'; ?>";
var erroremail="<?php echo '$erroremail'; ?>";
if (errorfirst==true) {
$('.first-input').addClass('input-error');
}
if (errorlast==true) {
$('.last-input').addClass('input-error');
}
if (erroremail==true) {
$('.email-input').addClass('input-error');
}
if (erroremail==false && errorfirst==false && errorlast==false) {
$('.first-input,last-input,.email-input').val('');
}
</script>
It is not sending any value to the database. I used jQuery to validate form without refreshing but I think because of jQuery my form is not working
Here is my jQuery code
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$(".first-input").val();
var last=$(".last-input").val();
var email=$(".email-input").val();
var college=$(".college-input").val();
var password=$(".password-input").val();
var submit=$(".signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>
And here is my HTML form
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button type="submit" name="button">sign-up</button>
</div>
</form>
Help me over this issue and I also don't know about security in PHP forms so you can aslo suggest me some tips over that, I will really appreciate because I am want to be a professional back-end developer and now I am a newbie
Your jQuery uses $(".first-input").val(), but you have class="first-input" on the DIV, not the input.
Either move the class attribute to the inputs, or change the selector to $(".first-input input").val() (and similarly for all the other inputs).
You need to grab the input, not the container
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input id="first-input" type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input id="last-input" type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input id="email-input" type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input id="college-input" type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input id="password-input" type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button id="signup-btn" type="submit" name="button">sign-up</button>
</div>
</form>
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$("#first-input").val();
var last=$("#last-input").val();
var email=$("#email-input").val();
var college=$("#college-input").val();
var password=$("#password-input").val();
var submit=$("#signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>
I am trying to make a simple incentive calculator.
PROBLEMS:
When I am submitting the form the values of the fields and field names are showing are showing up in the address bar.
eg: "http://localhost/incentive%20tracker/?jQueryDatePicker1=09%2F05%2F2015&pid=n&qty=1&memo=&remarks=&add=Add"
When I try to submit the values in the first attempt just after the first load of the page, the values are not getting inserted in the database. After the first attempt, the values do get inserted.
On success in insertion of data in the database, jQuery doesn't show me any message in spite of having the success function.
I am not being able to display an error message if the qty field is negative.
I am not sure what I am doing wrong.
HTML
<form id="saleDetail">
<input type="text" id="jQueryDatePicker1" name="jQueryDatePicker1" value="06/05/2015">
<input type="text" name="pid" id="pid" required placeholder="Enter a product code">
<datalist id="products">
<?php
$sql="SELECT * FROM products";
$result = mysqli_query($db, $sql);
while($fetch_options=mysqli_fetch_array($result)){
?>
<option value="<?php echo $fetch_options['pid']; ?>"><?php echo $fetch_options['pid']; ?></option>
<?php
}
?>
</datalist>
<input type="number" id="qty" name="qty" value="" autocomplete="off" required placeholder="Enter the Quantity">
<input type="text" id="memo" name="memo" value="" autocomplete="off" placeholder="Enter the Cash memo number">
<textarea name="remarks" id="remarks" rows="2" cols="27" placeholder="Any remarks"></textarea>
<input type="submit" id="add" name="add" value="Add">
<div id="message"></div>
</form>
JQuery
<script>
$(document).ready(function()
{
var jQueryDatePicker1Opts =
{
dateFormat: 'dd/mm/yy',
changeMonth: false,
changeYear: false,
showButtonPanel: false,
showAnim: 'slideDown'
};
$("#jQueryDatePicker1").datepicker(jQueryDatePicker1Opts);
$("#jQueryDatePicker1").datepicker("setDate", "new Date()");
$("#PanelMenu1").panel({animate: true, animationDuration: 200, animationEasing: 'swing', dismissible: true, display: 'push', position: 'right'});
$('#add').click(function()
{
var date=$('#jQueryDatePicker1').val();
var pid=$('#pid').val();
var qty=$('#qty').val();
var remarks=$('#remarks').val();
var memo=$('#memo').val();
if(pid==="" || qty==="" || qty<0){
$("#message").html("<span style='color:#cc0000'>Please fill in the required fields!");
}
else{
var dataString='date='+date+'&pid='+pid+'&qty='+qty+'&remarks='+remarks+'&memo='+memo;
$.ajax({
type:"POST",
data: dataString,
url: "add.php",
cache:false,
success: function(html){
$("#message").html("Data Added successfully! ");
}
});
}
});
return false;
});
</script>
PHP
<?php
include 'connect.php';
$error_message = "";
$mysql_table = "sales";
//if ($_SERVER['REQUEST_METHOD'] == 'POST')
if (isset($_POST['pid']) && isset($_POST['qty']))
{
$newdate =$_POST['date'];
$newpid = $_POST['pid'];
$newqty = $_POST['qty'];
$newremarks = $_POST['remarks'];
$newmemo = $_POST['memo'];
$newpid = mysqli_real_escape_string($db, $newpid);
$newqty = mysqli_real_escape_string($db, $newqty);
$newremarks = mysqli_real_escape_string($db, $newremarks);
$newmemo = mysqli_real_escape_string($db, $newmemo);
$sql = "SELECT incentive FROM products WHERE pid = '$newpid'";
$result = mysqli_query($db, $sql);
$rate=mysqli_fetch_array($result);
$amt = $rate['incentive'] * $newqty;
$sql = "INSERT `".$mysql_table."` (`date`, `pid`, `qty`, `amt`, `memo`, `remarks`) VALUES ('$newdate', '$newpid', '$newqty', '$amt', '$newmemo', '$newremarks')";
$results = mysqli_query($db, $sql);
echo "Success";
mysqli_close($db);
}
?>
My code given below. Please help me correct the code. Iam confused with syntax. Also I do not know where exactly to put error message alert if there is any database issue and how to close the database. Please help
<form id="ContactForm" name="form1" method="post" onsubmit="submitdata()">
<div>
<div class="formwrap"><span>Your Name:</span><input name="fname" type="text" class="input" ></div>
<div class="formwrap"><span>Your E-mail:</span><input type="text" name="femail" class="input" ></div>
<div class="formwrap"><span>Your Mobile:</span><input type="text" name="fmobile" class="input" ></div>
<div class="formwrap"><span>Your City:</span><input type="text" name="fcity" class="input" ></div>
<div class="textarea_box"><span>Your Message:</span><textarea name="fmessage" cols="1" rows="1"></textarea></div>
<a class="button" onClick="document.getElementById('ContactForm').submit()"><span class="shadow"></span>Send</a>
<a class="button" onClick="document.getElementById('ContactForm').reset()"><span class="shadow"></span>Clear</a>
</div>
</form>
<?php
function submitdata(){
include "config/connection.php";
$fdname = $_POST['fname']);
$fdemail = $_POST['femail']);
$fdmobile = $_POST['fmobile']);
$fdcity = $_POST['fcity']);
$fdmessage = $_POST['fmessage']);
$sql="INSERT INTO users (name, email, mobile, city, message)
VALUES ('$fdname', '$fdemail', '$fdmobile', '$fdcity', '$fdmessage')";
}
?>
Thank you
I changed the action on your html form and created the php script that will handle and store your data into the database,take a look and do some further reading on prepared statements.
<form id="ContactForm" name="form1" action="insert.php" method="post">
<div>
<div class="formwrap"><span>Your Name:</span><input name="fname" type="text" class="input" ></div>
<div class="formwrap"><span>Your E-mail:</span><input type="text" name="femail" class="input" ></div>
<div class="formwrap"><span>Your Mobile:</span><input type="text" name="fmobile" class="input" ></div>
<div class="formwrap"><span>Your City:</span><input type="text" name="fcity" class="input" ></div>
<div class="textarea_box"><span>Your Message:</span><textarea name="fmessage" cols="1" rows="1"></textarea></div>
<a class="button" onClick="document.getElementById('ContactForm').submit()"><span class="shadow"></span>Send</a>
<a class="button" onClick="document.getElementById('ContactForm').reset()"><span class="shadow"></span>Clear</a>
</div>
</form>
insert.php
<?php
if($_POST){
$db = new mysqli("address","id","password","DBname");
if (mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$stmt = $db->prepare("INSERT INTO users (name, email, mobile, city, message) VALUES (?, ?, ?, ?, ?)");
$stmt -> bind_param('sssss', $fname, $femail, $fmobile, $fcity, $fmessage);
$fname = $_POST['fname'];
$femail = $_POST['femail'];
$fmobile = $_POST['fmobile'];
$fcity = $_POST['fcity'];
$fmessage = $_POST['fmessage'];
$stmt -> execute();
$stmt -> close();
$db -> close();
}
?>
You can use something like this (if you have jQuery included):
<script>
$(document).ready(function () {
$('form[name=form1]').submit(function () {
var fname = $('input[name=fname]').val();
var femail = $('input[name=femail]').val();
var fmobile = $('input[name=fmobile]').val();
var fcity = $('input[name=fcity]').val();
var fmessage = $('textarea[name=fmessage]').val();
$.post("/ajax/insert.php", {
'fname': fname,
'femail': femail,
'fmobile': fmobile,
'fcity': fcity,
'fmessage': fmessage
}, function (data) {
if (data == 1) {
alert("Success");
} else {
alert("Error");
}
});
});
});
</script>
Then make folder "ajax" in the root of website and make there a script called insert.php (if you want different name, edit line 9 in the js code). Content of the insert.php will be something like this:
<?php
include "config/connection.php";
$fdname = $_POST['fname'];
$fdemail = $_POST['femail'];
$fdmobile = $_POST['fmobile'];
$fdcity = $_POST['fcity'];
$fdmessage = $_POST['fmessage'];
$sql="INSERT INTO users (name, email, mobile, city, message)
VALUES ('$fdname', '$fdemail', '$fdmobile', '$fdcity', '$fdmessage')";
mysql_query($sql);
if(mysql_error()) {
echo 0;
} else {
echo 1;
}
?>
For onsubmit attribute JS function or codes is required not PHP function. But you provided a PHP function in onsubmit. I suggest you to use AJAX or action in form.
An Example for you
<form id="ContactForm" name="form1" >
<div>
<div class="formwrap"><span>Your Name:</span><input name="fname" type="text" class="input" ></div>
<div class="formwrap"><span>Your E-mail:</span><input type="text" name="femail" class="input" ></div>
<div class="formwrap"><span>Your Mobile:</span><input type="text" name="fmobile" class="input" ></div>
<div class="formwrap"><span>Your City:</span><input type="text" name="fcity" class="input" ></div>
<div class="textarea_box"><span>Your Message:</span><textarea name="fmessage" cols="1" rows="1"></textarea></div>
<a class="button" id="submit"><span class="shadow"></span>Send</a>
<a class="button" onClick="document.getElementById('ContactForm').reset()"><span class="shadow"></span>Clear</a>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$('#submit').click(function(){
$.ajax({
url: 'test.php',
data: $('#ContactForm').serialize(),
type: 'post',
success: function(data){
if(data == 'inserted'){
alert('Inserted');
}else{
console.log(data);
}
}
});
});
</script>
In test.php
include "config/connection.php";
$fdname = $_POST['fname'];
$fdemail = $_POST['femail'];
$fdmobile = $_POST['fmobile'];
$fdcity = $_POST['fcity'];
$fdmessage = $_POST['fmessage'];
$sql="INSERT INTO users (name, email, mobile, city, message)
VALUES ('$fdname', '$fdemail', '$fdmobile', '$fdcity', '$fdmessage')";
// if you use mysql connection
$result = mysql_query($sql);
if($result) {
echo 'inserted';
} else {
die(mysql_error());
}
You also fix some syntax error. Remove ) after each $_POST.
I want to post json output to a new window. How could I achieve this? Thank You!
Here is my code:
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#callAjaxForm").serialize();
$.ajax({
type: "POST",
url: "callajax.php",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
<form id="callAjaxForm">
<div data-role="fieldcontain">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" value="" />
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" value="" />
<button data-theme="b" id="submit" type="submit">Submit</button>
</div>
</form>
and below is callajax.php (I want to show the json information on this page)
<?php
$fName = $_POST['firstName'];
$lName = $_POST['lastName'];
echo("First Name: " . $firstName . " Last Name: " . $lastName);
?>
if you want to make a JSON representation of the data you are sending from the form use:
<?php
$fName = $_POST['firstName'];
$lName = $_POST['lastName'];
$resp = array('first_name'=>$fName,'last_name'=>$lName);
echo json_encode($resp);
?>