Ajax Post with PHP and MySQL - php

Im trying to post data to mysql by using PHP and Ajax, the only thing problem that data does not enter into database it so the problem seems in the javascript which i think ajax please help me.
Please there some one can fix it if there any error on code?
FORM:
<form id="contactForm" action="ajax.php" method="post">
<input name="name" id="name" type="text"/>
<input name="email" id="email" type="text"/>
<input type="button" value="Send" name="submit" id="submit" />
<span id="error" class="warning">Message</span></p>
</form>
<p id="sent-form-msg" class="success">Thanks for your comments.We will update you within 24 hours. </p>
JS:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
// on submit...
$("#contactForm #submit").click(function() {
$("#error").hide();
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email;
$.ajax({
type:"POST",
data: dataString,
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
return false;
});
AJAX.php
$con=mysqli_connect("localhost","admin","admin","test");
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO test (name, email) VALUES ('$name', '$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Thank you in Advance.

You must include the URL you want to POST to in the AJAX call.
$.ajax({
url: "ajax.php",
type:"POST",
data: dataString,
success: success()
});

Here is what I suggest doing:
HTML:
<input name="name" id="name" type="text"/>
<input name="email" id="email" type="text"/>
<input type="button" value="Send" onclick="validate();" id="submit" />
<span id="error" class="warning">Message</span></p>
<p id="sent-form-msg" class="success">Thanks for your comments.We will update you within 24 hours. </p>
Javascript:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
}
// on submit...
function validate()
{
$("#error").hide();
var name = $("#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
}
var email = $("#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
// var dataString = 'name=' + name + '&email=' + email;
$.ajax({
url: "phpScript.php"
type:"POST",
data: {name:name, email:email},
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
}
PHP:
$con = mysqli_connect("localhost","admin","admin","test");
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO test (name, email) VALUES ('$name', '$email')";
//I like to do it like this:
$result = mysql_query($query, $connect);
/*if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}*/
echo "1 record added";
mysqli_close($con);
I give credit also to the other answer by mattmemo. The thing he corrected was definitely a mistake. I think there may have been other mistakes in MARGELANI's script so I chose to post my answer as well. If this script doesn't work let my know and I will recode it. Good luck! :D

Related

Receiving success response but the button still disabled using ajax

I am checking email id is available or not in the database using ajax which is working.I have one submit button and that is disabled on page load.I have to enable that button when the user enters the right email address which is available on the database. If email is available in the database the button will enable otherwise button will be disabled.There is some issue in if condition. I tried button still the same issue. Would you help me in this?
$("input[type='submit']").removeAttr("disabled");
$("input[type='submit']").prop('disabled', false);
If I used CSS for button then disable is not working.
Html
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="id" type="submit" name="next" value="submit" >
Ajax
$(document).ready(function()
{
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == 1) {
$('input[type="submit"]').attr('disabled' , false);
}
else{
$("#email-validation-error").html(data);
$('input[type="submit"]').attr('disabled', true);
}
},
});
});
});
//Disable the button on page load
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
});
Process.php
include('db/connection.php');
if(isset($_POST['email'])){
$email=$_POST['email'];
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record == 0) {
echo "Email does not exist, please sign up to use our services";
}
}
Try this-
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == "ok") {
$(elem).attr('disabled' , false); //here pass elem
}
else{
$("#email-validation-error").html('Email not available');
$(elem).attr('disabled', true); //here pass elem
}
},
});
});
});
Process.php
include('db/connection.php');
if(isset($_POST['email'])){
$email=$_POST['email'];
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record == 0) {
echo "ok";
}
}
You should check and verify your response:
Process.php
if ($search_record == 0) {
echo "Email does not exist, please sign up to use our services";
}
else{
echo "success";
}
Ajax
if (data == "success") {
$("#submitYesNo").prop('disabled', false);
}
else{
$("#email-validation-error").html(data);
$("#submitYesNo").prop('disabled', true);
}
html
<input id="submitYesNo" type="submit" name="next" value="submit" >
Try This Code .
Hope it will work properly
success:function(data)
{
if (data == 1)
{
$('input[type="submit"]').removeAttr("disabled", "disabled");
}
else
{
$("#email-validation-error").html(data);
$('input[type="submit"]').attr("disabled", "disabled");
}
Finally, I found my answer with the help of Mr.Ahmed Ginani
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form >
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="id" type="submit" name="next" value="submit" disabled>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$(elem).attr('disabled', true);
$("input[name='email']").bind('change',function() // Changes from key press to change and bind
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == 'success') { // getting success name from process.php page
$("#id").attr('disabled' , false);
$("#email-validation-error").html(''); //Change here for hiding the error message
}
else{
$("#email-validation-error").html(data);
$('#id').attr('disabled', true);
}
},
});
});
});
</script>
</body>
</html>
Process.php
if(isset($_POST['email'])){
$email=$_POST['email'];
$_SESSION['username']=$email;
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record > 0) {
echo "success";
}
else{
echo "Email does not exist, please sign up to use our services";
}
}

jQuery(AJAX) post to php issue when I try to insert data into DB

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 ;
?>

How to check if jquery ajax send POST request or not?

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.

AJAX > PHP Log in not working

I'm trying to create a log in form using html > ajax > php, the problem is the php is not working, I don't know where is the problem, I think the ajax cannot execute my php file. I need help. Thanks in advance.
Here is my HTML code: my form and inputs are below
<form id="loginForm">
<input type="text" data-clear-btn="true" name="username" id="username" value="" placeholder="Username / ID No.">
<input type="password" data-clear-btn="true" name="password" id="password" value="" placeholder="Password">
<input type="checkbox" name="rem_user" id="rem_user" data-mini="true">
<label for="rem_user">Remember me</label>
<input type="submit" name="login" id="login" value="Log in" class="ui-btn" />
</form>
<div class="err" id="add_err"></div>
AJAX script that sends request on my php file
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is in database.
var dataString = 'username=' + username + '&password=' + password;
if (username == '' || password == ''){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: dataString,
success: function(result){
window.location="#report_page";
}
});
}
return false;
});
});
</script>
PHP File
<?php
require "includes/connection.php";
include "includes/function.php";
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = sanitize($username);
$password = sanitize($password);
$pass2 = md5($password);
$salt = "sometext";
$validateHash = $salt.$pass2;
$pass = hash("sha512", $validateHash);
$sql = "SELECT * FROM user_login WHERE username='".$username."' and password='".$password."'";
$result = mysqli_query($con,$sql) or die("Error: ". mysqli_error($con));
$count=mysqli_num_rows($result);
while($row=mysqli_fetch_array($result))
{
$id = $row['user_id'];
$username = $row['username'];
$name = "".$row['firstname']." ".$row['lastname']."";
$acc_type = $row['Acc_Type'];
}
if($count==1){
if($acc_type == 'user') {
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["name"] = $name;
echo 'true';
}
else {
echo 'false';
}
}
}
?>
as Cattla mentioned in comments.
Your PHP is looking for $_POST['login'], and your $.ajax call didn't pass that in.
so here is the answer
var dataString = 'login=login&username=' + username + '&password=' + password;
Debug tips
Did ajax send all required inputs to PHP (you can inspect this from browser developer tool)
Did php receive all required inputs (you could var_dump($_POST)
Did php connect to mysql successfully
Did ajax receive data from PHP (use alert or console.log)
try this, and if you get error state what it is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
if (username == ' ' || password == ' '){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: $(this).serialize(),
success: function(result){
alert('sucess'); //window.location="#report_page";
}
});
}
return false;
});
});
</script>

Issue with using ajax to update without refresh

I have this code here which is supposed to help me update a phone number.
It doesn't do it though, well, i get the successfully changed message but no insertion on the database.
Here is my code:
index.php
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var phone = $("#phone").val();
var dataString = 'phone='+ phone ;
if(phone=='') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "update-phone.php",
data: dataString,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<div class="modal" style="display: none;">
<?php
if (empty($phone)) {
?>
<form method="post" name="form">
<input id="phone" name="phone" type="text" />
<div>
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
update-phone.php
<?php
require_once('db.php');
if($_POST) {
$phone = $_POST['phone'];
mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
}else {}
?>
What am i missing?
Thanks
Try this..
<?php
require_once('db.php');
if($_POST) {
$phone = $_POST['phone'];
mysql_query("UPDATE `users` SET `phone` = '$phone' WHERE `ID` = 5884 ");
}else {}
?>
Have you tried inspecting the ajax request with firebug/developer tools/etc?
Try adding echo mysql_error(); right after your mysql_query.
Not 100% sure but it could be the if ($_POST) should be replaced with if (isset($_POST['phone']))
Try the following php:
<?php
require_once('db.hp');
if (isset($_POST['phone']))
{
$phone = $_POST['phone'];
mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
echo mysql_error();
}
else
{
echo "Failed";
}
?>
EDIT: Have you confirmed if it actually updates the DB?
Also you should also sanitise your input and consider rolling with mysqli instead of mysql_*

Categories