submitting a simple contact form using ajax.
EDITED CODE
now trying to insert the data to database.
html form
<form align="left" method="post" class="subscribe_form" action='subscribe.php'>
Your Name:<br>
<input type="text" name="name" value="" required><br>
Your E-Mail:<br>
<input type="email" name="email" value="" required><br><br>
Gender:
<p> <input name="gender" value="male" type="radio" id="male" />
<label for="male">Male</label>
<input name="gender" value="female" type="radio" id="female" />
<label for="female">Female</label>
</p>
<br>
Company Name:
<input type="text" name="cname" value="" required><br><br>
<input type="submit" name="send" value="Subscribe" id="subscribe"> <span class="output_result"></span>
</form>
this is my ajax code :
<script>
$(document).ready(function() {
$('.subscribe_form').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_result').text('Sending...');
var form = $(this);
$.ajax({
type:'post',
url:'subscribe.php',
dataType: "text",
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_result').text('thank you!');
} else {
$('.output_result').text('Error!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
subscribe.php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rm";
$name = $_POST['name'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$cname = $_POST['cname'];
$sub_date = date("Y-m-d");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "insert into rmsubscribe (name, gender, email, cname, sub_date) values ('$name', '$gender','$email','$cname','$sub_date')";
$result = (mysqli_query($conn, $sql));
echo ($result) ? 'success' : 'error'; */
mysqli_close($conn);
this code give me 'error message'.
if i use without ajax code like this,
at form ,
without the 'class="subscribe_form"..
and in subscribe.php
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
instead of this
$result = (mysqli_query($conn, $sql));
echo ($result) ? 'success' : 'error';
it works fine. 'New record created successfully' data inserted into table.
Please help me on ajax code. i am not familiar with ajax. how to make this work using ajax?
I think you need to add datatype to your ajax request. Actually your ajax request is expecting json and you are returning text - "Success" that is not json that's why when it gets unexpected data returned it is sending ajax response to error function. Update you code to below ajax request -
As you are returning Text as response to your ajax request so your ajax request datatype must be text as below line of code in ajax request -
dataType: "text"
Example of your expected Ajax Request
$.ajax({
type:'post',
url:'email.php',
dataType: "text",
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent Successfully!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
Related
when I echo the php variable it work properly , but when I try to insert the data into database it doesn't work , what is the solution please I get stuck
I got this error on console
POST http://localhost/validate.php 500 (Internal Server Error)
send # jquery-3.1.1.min.js:4
ajax # jquery-3.1.1.min.js:4
(anonymous) # jquery.PHP:26
dispatch # jquery-3.1.1.min.js:3
q.handle # jquery-3.1.1.min.js:3
HTML/JQUERY
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var age = $('#age').val();
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
</script>
PHP
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
mysqldb.php
<?php
$conn = mysql_connect('localhost', 'root', 'password' , 'datab');
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
Please add the details of the error message you get.
Make little changes to your code so that it can show the query error if any
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "INSERT INTO `uss` (`first`, `last`) VALUES('{$name}','{$age}')";
if($conn->query($sql))
{
echo "Record inserted";
}
else
{
echo $conn->error;
}
?>
Sugesstions: Your query have the chances of the SQL Injection. Make it secure.
if you are using ajax , try the following,
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit" id="submit">
</form>
<div id="result"></div>
$("#submit").click(function(){
var name = $('#name').val(); // getting name
var age = $('#age').val();
$.ajax({
url : "validate.php",
type: "POST",
data: {name:name, age:age},
success: function(data)
{
$("#result").html(data);
}
});
});
in your controller function,echo the result
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('$name','$age')";
$result = $conn->query($sql);
echo $result;
?>
jQuery Ajax
Form with id myFrom
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
jQuery Ajax section
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val(); // getting name
var age = $('#age').val(); // getting age
/* Ajax section */
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
validate.php
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="button" value="Submit" onclick="postdata();">
</form>
<div id="result"></div>
<script type="text/javascript">
function postdata() {
alert("ashad");
var name = $('#name').val();
var age = $('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data){
$('#result').html(data);
});
}
</script>
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else
{
$sql = "insert into uss(first, last) values('$name','$age')";
$result = $conn->query($sql);
}
echo $result ;
?>
I have created a html form which sends certain variables to a php file, the file is saved in the database and returns the success through json back to the javascript. But the problem is am not able to save the data and get the response back to the javascript file. I donno what is the reason. So can some help me with this. Thank you
my form is
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script>
<script src="scriptj.js"></script>
</head>
<body>
<form action="http://localhost/donotdel/process.php" method="POST">
<div id="name-group" class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="name">
</div>
<div id="email-group" class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="email">
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
</body>
</html>
my javascript file is
$(document).ready(function () {
$('form').submit(function (event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
};
$.ajax({
type: 'POST',
url: 'http://localhost/donotdel/process.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
if (!data.success) {
if (data.errors.name) {
$('#name-group').addClass('has-error');
$('#name-group').append('<div class="help-block">' + data.errors.name + '</div>');
}
if (data.errors.email) {
$('#email-group').addClass('has-error');
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>');
}
}
else {
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
}
}).fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
and my php file is
<?php
$errors = array();
$data = array();
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
}
header ('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode($data);
?>
now from the above php file i want to enter the name and email into the database. but i donno how to do it. So can someone help me out with the code. and after entering i want to send the above json response back to the javascript
thank you
What you need to do is establish a database connection and use that database connection to insert a new row in the users table. If the sql errors out return the error, if it works return the json data. Make sure to close the connection to the database when you are done.
Start by building a dbconfig.php file
This is used to establish the connection to your database.
This is what a simple one looks like.
<?php
$servername = "localhost";
$username = "root";
$password = "temppass";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Include the dbcong.php in your file
include ('dbconfig.php');
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}else{
//if it make a connection insert code here!
$qry = "INSERT ..."; //build your insert string here!
$conn->query($qry); // run your insert here!
//Don't forget to CLOSE YOUR CONNECTION!
$conn->close();
}
I have created a simple Login Register program using PHP.
Now I am trying to validate if username already exists or not using jquery ajax. The jquery code runs but keeps on showing 'Checking Availability'.
Here is the code I have used. Please ignore the vulnerability and other errors in my PHP code ( which may not affect jquery ajax process ) as I am new to this. I'm working for improving those things.
Register.php
<?php
include('config.php');
if(isset($login_session))
{
header("Location: login.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$username = mysqli_real_escape_string($obj->conn,$_POST['username']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$name = mysqli_real_escape_string($obj->conn,$_POST['name']);
$email = mysqli_real_escape_string($obj->conn,$_POST['email']);
$password = md5($password);
$sql ="SELECT uid from users WHERE username = '$username' or email = '$email'";
$register_user = mysqli_query($obj->conn,$sql) or die(mysqli_error($sql));
$no_rows = mysqli_num_rows($register_user);
if($no_rows == 0)
{
$sql2 = "INSERT INTO users(username, password, name, email) values ('$username', '$password', '$name', '$email')";
$result = mysqli_query($obj->conn, $sql2) or die(mysqli_error($sql2));
echo "Registration Successfull!";
}
else{
echo "Registration Failed.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/username.js"></script>
</head>
<body>
<form action="register.php" method="post">
<label>UserName:</label>
<input type="text" id="username" name="username" required/>
<span id="status"></span><br />
<label>Password :</label>
<input type="password" name="password" required/><br/>
<label>Full Name :</label>
<input type="text" name="name" required/><br/>
<label>Email :</label>
<input type="email" name="email" required/><br/>
<input type="submit" value=" Submit "/><br />
</form>
</body>
</html>
username.js
$(document).ready(function()
{
$("#username").change(function()
{
var username = $("#username").val();
var msgbox = $("#status");
if(username.length > 3)
{
$("#status").html('<img src="img/loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "php/username-check.php",
data: "username="+ username,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK')
{
msgbox.html('<img src="img/yes.png" align="absmiddle"> <font color="Green"> Available </font> ');
}
else
{
$("#username").removeClass("green");
$("#username").addClass("red");
msgbox.html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="#cc0000">Enter valid User Name</font>');
}
return false;
});
});
username-check.php
<?php
include("config.php");
if(isSet($_POST['username']))
{
$username = $_POST['username'];
$username = mysqli_real_escape_string($obj->conn,$username);
$sql = "SELECT username FROM users WHERE username='$username'";
$sql_check = mysqli_query($obj->conn,$sql);
if (!$sql_check)))
{
echo 'could not complete query: ' . mysqli_error($obj->conn,$sql_check);
}else{
echo 'query successful!';
}
if(mysqli_num_rows($obj->conn,$sql_check))
{
echo '<font color="#cc0000"><b>'.$username.'</b> is already in use.</font>';
}
else
{
echo 'OK';
}
}
?>
and I want to know if there is a way to check if jQuery Ajax sent the POST request to that file or not?
You are confusing ajax functions...Syntax will be like this
$.ajax({
url: url,
data: data,
type: "POST",
beforeSend: function () {
},
success: function (returnData) {
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function () {
}
});
Examine the request using a browser utility
- Launch the chrome browser
- Right click and select inspect element menu
- click on Network tab
- Load your URL
- Perform the Ajax request
- You can see the request here (new request will be last in the list).
- Click on it
- Right side window shows you request and response data
You did correct.Easy way to check them is use firebug tool on your browser...I recommend firefox with firebug.install it first and then open it before you post your form.then goto console log and send your form...Check it out,best software.
I'm echoing a message ('ok') from a PHP script to a JQuery ajax call.
I'm echoing out the correct message, and its showing up in the console when i log it, but the appropriate jquery function is not firing - according to the code i should get an Your password has been changed successfully" message, but I only get a "there was a problem" message - can anyone suggest a reason why?
here is the code first the PHP:
if(isset($_POST['oldpass'])){
$oldpass = mysql_real_escape_string($_POST['oldpass']);
$newpass = mysql_real_escape_string($_POST['newpass']);
$sql = "SELECT password, salt FROM users WHERE email='$log_email' AND id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$current_salt = $row["salt"];
$db_pass = $row["password"];
}
$old_pass_hash = crypt($oldpass, $current_salt);
if ($old_pass_hash != $db_pass){
echo "problem";
exit();
}
}
$s = "$2a$10$";
$random = randStrGen(20);
$salt = $s.$random;
$p_crypt = crypt($newpass, $salt);
$sql = "UPDATE users SET password='$p_crypt', salt='$salt' WHERE email='$log_email' AND id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
if ($query == true){
$_SESSION['password'] = $p_crypt;
echo 'ok';
exit();
}
}
?>
This is the javascript/JQuery
function change_password(){
var oldpass = $('#old_pass').val();
var newpass = $('#new_pass').val();
var newpass_conf = $('#confirm_new_pass').val();
if(newpass != newpass_conf){
$('#status').html("Your passwords do not match");
} else if(newpass=="" || oldpass==""){
$('#status').html("You have not entered anything");
}
$.ajax({
type: 'POST',
url: "changePassword.php",
dataType: 'text',
data: {
"oldpass": oldpass,
"newpass": newpass_conf },
success:function(data){
if(data == "ok"){
$('#change_password_form').html("<h2> Success</h2><div class='noerror'><p> Your password has been changed successfully.</p> <p> You may now close this window.</p></div>");
} else {
$('#status').html("There was a problem");
}
}
});
}
$(document).ready(function(){
$(document).on('click','#change_password', function(){
change_password();
});
});
</script>
and finally the html
<div> <h1>Change your password</h1></div><hr>
<form id="change_password_form" class="input" onsubmit="return false;">
<div> <label for="old_pass">Current Password:</label>
<input id="old_pass" type="text" class="searchbox" onfocus="emptyElement('status')" maxlength="88" value=""></div>
<div> <label for="new_pass">New Password:</label>
<input id="new_pass" class="searchbox" type="text" onfocus="emptyElement('status')" maxlength="88" value=""> </div>
<div><label for="confirm_new_pass">Confirm New Password:</label>
<input id="confirm_new_pass" class="searchbox" type="text" onfocus="emptyElement('status')" maxlength="88" value=""><div>
<input type="button" style="position:relative;top:10px; float:right;" id="change_password" value="Change Password"></form>
<span id="status" class="statuserror"></span>
</body>
</html>
change the dataType: "json" in your ajax call
then in your php code return json data
json_encode(array('response'=>'ok'));
your ajax success function should look like this,
success: function (data) {
var resultObject = jQuery.parseJSON(data);
if(rersultObject['response']=='ok') {
$('#change_password_form').html("<h2> Success</h2><div class='noerror'><p> Your password has been changed successfully.</p> <p> You may now close this window.</p></div>");
} else {
$('#status').html("There was a problem");
}
}
}`
here parseJSON is used to convert JSON string to javascript object.
I got this problem a while ago and could never figure it out, although different scenario. What I did was to change the data type to json like so:
$.ajax({
type: 'POST',
url: url,
data: 'data=data&other=other'
dataType: 'json',
//if everything goes out as planned
success: function(response) {
alert(response['data']);
}
});
and in the php
$respond = array("data" => 'ok',
"other" => 'whatever else'
);
echo json_encode($respond); //send a response back to javascript
exit();
I'm having a problem with my ajax call. I'm submitting some info via php to mySQL, the submission part works perfectly, it's adding the data to the database, but the ajax function isn't loading that php in the background, it's loading it in the window and showing the php file results.
Here's the HTML code.
<form action="upload.php" class="addItem" method="post">
Firstname:<br><input type="text" class="firstname" name="firstname" /><br>
Lastname:<br><input type="text" class="lastname" name="lastname" /><br>
Age:<br><input type="text" class="age" name="age" /><br>
Photo:<br><input type="file" name="image" accept="image/jpeg" /><br><br>
<input type="submit" class="submitItem" value="Add Row" />
</form>
Logout
</div>
<script>
$(document).ready(function(){
$(".submitItem").click(function(){
// Start AJAX send
jQuery.ajax({
// Enter below the full path to your "send" php file
url: "upload.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
// If form submission is successful
if ( html == 1 ) {
$('.successMessage').show(200);
$('.successMessage').delay(2000).hide();
}
// Double check if maths question is correct
else {
$('.errorMessage').show(200);
$('.errorMessage').delay(2000).hide();
}
}
});
});
});
</script>
Here's the PHP code
<?php
$name = $_POST['firstname'];
$surname = $_POST['lastname'];
$age = $_POST['age'];
if(($name === "") || ($surname === "") || ($age === "")){
echo "please fill in all fields";
} else {
$con = mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
if ($sql) { echo "1"; }
else{echo "error";}
}
mysql_close($con);
?>
Your handler needs to return false; to instruct the browser not to do its regular submission action.
(Also, you should really consider using the submit event of the form, rather than the click event of the button.)
<script type="text/javascript">
$(function(){
$("form.addItem").submit(function(){
// Start AJAX send
jQuery.ajax({
// ... your parameters ...
});
return false;
});
});
</script>