ajax doesn't load my php file in the background - php

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>

Related

form submit using ajax php

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;
});

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 Post with PHP and MySQL

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

don't submit form if form is empty

this is my first post and i'm rather new to php + ajax.
I have most of my coding set up only problem now is that when i press the submit button an notification shows up that only should show up when the text fields aren't empty.
This is my code:
<head><script>
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
alert("Thank you for subscribing to SHCA");
document.forms["ContactForm"].reset();
});
});
</script> </head>
followed by some php coding:
<?php
if(strlen($_POST['name']) > 0 AND strlen($_POST['email']) > 0)
{
if(isset($_POST['submit']))
{
$hostdb = '';
$namedb = '';
$userdb = '';
$passdb = '';
$conn = mysqli_connect($hostdb , $userdb, $passdb ,$namedb);
$sql = "INSERT INTO subscribers (name, email) VALUES('$_POST[name]', '$_POST[email]')";
if (!mysqli_query($conn, $sql))
{
die('Error: ' .mysql_error($conn));
}
if (!mysqli_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysqli_close($conn);
}}
else
{
?>
<form id="ContactForm" action="" method="post">
<label for="author">Name:</label> <input type="text" id="name" name="name" class="required input_field float_r" />
</br>
</br>
<label for="email">Email:</label> <input type="text" id="email" name="email" class="validate-email required input_field float_r" />
<div class="cleaner h10"></div>
<input type="submit" value="Subscribe" id="submit" name="submit" class="submit_btn float_l" />
</form>
<?php } ?>
hope anyone here is able to tell me what i should do to only show the "Thank you for subscribing to SHCA" message when the textfields aren't empty
final anwser Dereck forgot the '' in the objects so shout out to dereck for helping me!
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$('#name').val()) {
alert("please enter your name");
}
if(!$('#email').val()) {
alert("plese enter your email adress");
}
else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});
You need to check the contents of the fields before submitting to the server, a simple script method can check before you submit. If the fields are empty then display an error messge and don't submit the form.
function SubmitDetails()
{
if(window.ContactForm.name.value == "")
{
window.alert("Please enter a name");
return;
}if(window.ContactForm.email.value == "")
{
window.alert("Please enter an email" );
return;
}
window.ContactForm.submit();
}
This should do it without having to do a refresh
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$(#name).val() || !$(#email).val()) {
//don't display
}else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});

Categories