Submit form without reload using jQuery AJAX in PHP MySQL - php

I have a basic signup/ login page that submits the data to the SQL database with php. However, I would like the page not to redirect on submission with help of jQuery AJAX (either successful or not).
This is what I currently have and it is not working. It doesn't show any error messages.
HTML - signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Signup</title>
<meta charset="utf-8">
</head>
<body>
<form>
<table>
<tbody>
<tr>
<td>
<input type="text" name="first" placeholder="First Name" id="first">
</td>
</tr>
<tr>
<td>
<input type="text" name="last" placeholder="Last Name" id="last">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Signup" id="signup">
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
JavaScript - signup.js
function submit() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
},
error: function() {
console.log("Signup was unsuccessful");
}
});
});
}
$(document).ready(function() {
submit();
});
PHP - signup.php
<?php
include_once "db_connect.php";
$post_FirstName = $_POST['first'];
$post_LastName = $_POST['last'];
$addData = "INSERT INTO details (firstname, lastname) VALUES ('$post_FirstName', '$post_LastName')";
if ($conn->query($addData) === TRUE) {
echo "Working";
} else {
echo "Not working";
}
?>
Here is the JSFiddle.
I hope you guys can help. Thanks in advance :)

If you are using ajax no need to use input type as submit use button.
$(document).ready(function() {
$("#signup").click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize()
success: function() {
console.log("Signup was successful");
}
error: function() {
console.log("Signup was unsuccessful");
}
});
});
Also change here
$post_FirstName = $_POST['first']; // name is `first` not `firstname`

You have some brakes and parentheses not properly closed
function submit() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
},//here
error: function() {
console.log("Signup was unsuccessful");
}
});});//here
}
$(document).ready(function() {
submit();
});

No need to call submit function. Just this will do, (you missed comma and closing tag):
<script>
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
}, //You missed this
error: function() {
console.log("Signup was unsuccessful");
}
});
}); //You missed this
</script>

Related

How to post data (form) without page refresh PHP, jQuery, Ajax

Please help me how to submit form (comments) without page refresh for
HTML markup:
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="submit" id="comq"name="compost" class="butn2">post comment</button>
</form>
PHP code (pnf.php):
if(isset($_POST["compost"]))
{
$comment=$_POST['comments'];
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if($stmt)
{
echo "hello world";
}
}
jQuery and Ajax:
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
I have tried many times and don't know what mistake I made, Ajax and jQuery are not working, please anyone help - thanks in advance
You have made couple of mistakes.
First:: You should put button type="button" in your HTML form code
Second:: You have made a syntax error. $("#comment").vol(); should be replaced with $("#comment").val(); in your jQuery AJAX
As you mentioned that you have to send request without refreshing page I modified your JS-code with preventing default submitting form:
$(document).ready(function () {
$("#commentf").submit(function (e) {
e.preventDefault();
var comment = $("#comment").val();
$.ajax({
type: "POST",
url: "pnf.php",
data: {
"done": 1,
"comments": comment
},
success: function (data) {
}
})
});
});
Javascript
$('form').on('submit', function(event){
event.preventDefault();
event.stopPropagination();
var dataSet = {
comment: $('#comment').val();
}
$.ajax({
url: "link.to.your.api/action=compost",
data: dataSet,
method: 'post',
success: function(data){
console.log('request in success');
console.log(data);
},
error: function(jqXHR) {
console.error('request in error');
console.log(jqXHR.responseText');
}
});
});
PHP
$action = filter_input(INPUT_GET, 'action');
swicht($action){
case 'compost':
$comment = filter_input(INPUT_POST, 'comment');
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if(!$stmt)
{
http_response_code(400);
echo 'internal error';
}
echo 'your data will be saved';
break;
default:
http_response_code(404);
echo 'unknown action';
}
you have to prevent the submit on the form (look in javascript).
after that you send the request to the server and wait for success or error.
in php try to do it with a switch case. and try to not touch super globals directly, use filter_input function.
hope this helps
Modified JQuery Code...
$( document ).ready(function() {
console.log( "ready!" );
$("#comq").click(function() {
var comment=$("#comment").val();
console.log('comment : '+comment);
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
HTML Code
<form id="commentf" method="post">
<textarea class="textinput" id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<input type="button" id="comq" name="compost" class="butn2" value="Post Comment">
</form> </div>
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="button" id="comq"name="compost" class="butn2">post comment</button>
</form>
script
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
PHP code (pnf.php):
comment=$_POST['comments'];
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
if($stmt)
{
echo "hello world";
}
if you are using jquery make sure to include jquery libraries before your script file.
latest jquery cdn minified version
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
example
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="yourjsfile.js" type="text/javascript"></script>

not able to pass data to controller using Ajax with jquery ,CodeIgniter (PHP framework)

passing data to controller using AJAX
this is script i have written to pass data to controller but data is not passed to the controller
this is the input data i want to pass
<div class="form-group">
<table class="table table-striped b-t b-light text-sm">
<thead>
<tr>
<th>ID</th>
<th>Question</th>
<th>answer</th>
</tr>
</thead>
<tbody>
<?php foreach ($quet as $row) { ?>
<tr>
<td ><?php echo $row['id']; ?></td>
<td>
<?php echo $row['question']; ?>
</td>
<td><input type='text' name='name' required="required" class="form-control" placeholder='Enter Your Answer'></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" id ="next" type="button" >Next</button>
and the script
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("name").val()
$.ajax({
type: "POST",
datatype:"json",
url: BASE_URL+"/student/add",
data: 'data='+array,
contentType:'application/json',
processData: false,
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
and the student controller
function add(){
if($this->student_model->add($this->input->post()))
{
$response['success'] = TRUE;
}
else
{
$response['success'] = FALSE;
}
echo json_encode($response);
}
Try this. Your data may be in wrong format
data: {'data':array}
EDIT
<input type='text' name='answer' id='answer' required="required" class="form-control" placeholder='Enter Your Answer' />
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("#answer").val() // see the change name to id, see the html also
$.ajax({
type: "POST",
url: BASE_URL+"/student/add",
data:{'data':array},
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
});
});
</script>
Also check the array is received properly in you JS
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("#id").val()
$.ajax({
type: "POST",
datatype:"json",
url: BASE_URL+"/student/add",
data: {
'data':array
},
contentType:'application/json',
processData: false,
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
In your controller you should change $this->input->post() to$this->input->post('data')
From your mentioned code, you need to check these points :
1) As you are using contentType:'application/json', so use the data format as data: {'data':array}
2) Finally check whether the url url: BASE_URL+"/student/add", is accessible or not.
Hope this helps :)
You need to change following in your code.
In the Script
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("input[name]").val();
$.ajax({
type: "POST",
url: BASE_URL+"/student/add",
data: {'data':array},
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
},
datatype:"json"
});
return false;
});
});
</script>
In the Student Controller
function add(){
if($this->student_model->add($this->input->post('data')))
{
$response['success'] = TRUE;
}
else
{
$response['success'] = FALSE;
}
echo json_encode($response);
}
I hope this help.

Trying to update a database via AJAX and Jquery

I'm trying to achieve something basic, where you submit a form with a weight and it updates my database via ajax.
I've been looking through some of the answered questions for guidance but I just can't figure out why the below code doesn't work.
looking in chrome developer tools it look like it's not even submitting the form properly, so I don't think its the php script that's the issue (although it may have other issues once I fix the first problem).
Any help with fixing this would be much appreciated.
Here's the form and Ajax code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$("#weight_tracker_form").submit(function() {
$.ajax({
type: "POST",
url: "../weight_tracker_process.php",
data: {
weight: $("#weight").attr("value"),
},
success: function(){
alert("success");
},
error: function(){
alert("error");
}
});
return false;
});
</script>
<h2>Weight Tracker</h2>
<form id="weight_tracker_form" method="post">
Date: <input autofocus id="date" name="date" type="date"/>
Weight: <input id="weight" name="weight" type="text"/> Kg
<input type="submit" value="Submit Weight">
</form>
And here's the script weight_tracker_process.php
<?php
// configuration
require("includes/config.php");
if ($_POST["weight"] == NULL)
{
apologize("Please enter an email");
}
$weight = mysql_real_escape_string($_POST["weight"]);
$date = mysql_real_escape_string($_POST["date"]);
if (query("INSERT INTO weight (user_id, weight_measurement) VALUES (?, ?)", $_SESSION["id"], $weight); == false){
echo "Update Error";
}
else {
echo "Success";
}
?>
Thanks!
If this is your exact code, then what's probably happening is the handler isn't being attached to the form element. The JavaScript code is before the form, so when it runs the form doesn't exist yet. So this selector returns an empty array:
$("#weight_tracker_form")
You'll want to wait until the DOM is finished loading before assigning the event handler:
$(function () {
$("#weight_tracker_form").submit(function() {
$.ajax({
type: "POST",
url: "../weight_tracker_process.php",
data: {
weight: $("#weight").attr("value"),
},
success: function(){
alert("success");
},
error: function(){
alert("error");
}
});
return false;
});
});
Wrapping it in the jQuery function like this will cause it to wait until the document's ready event fires.
Try switch this:
weight: $("#weight").attr("value");
For this:
weight: $("#weight").val();
Also, you put the code on in document.ready. Like this:
$(document).ready(function({
$("#weight_tracker_form").submit(function() {
$.ajax({
type: "POST",
url: "../weight_tracker_process.php",
data: {
weight: $("#weight").attr("value"),
},
success: function(){
alert("success");
},
error: function(){
alert("error");
}
});
return false;
});
}));
Thanks guys, initial problem was as you suggested with me forgetting to wait for the dom to load before executing the script.
Second problem was some small bracket and syntax errors in the script.
Final code is below
HTML / Jquery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#weight_tracker_form").submit(function() {
$.ajax({
type: "POST",
url: "weight_tracker_process.php",
data: {
weight: $("#weight").val()
},
success: function(){
alert("success");
},
error: function(){
alert("error");
}
});
return false;
});
});
</script>
<h2>Weight Tracker</h2>
<form id="weight_tracker_form" method="post">
Date: <input autofocus id="date" name="date" type="date"/>
Weight: <input id="weight" name="weight" type="text"/> Kg
<input type="submit" value="Submit Weight">
</form>
Log Out
PHP
<?php
// configuration
require("includes/config.php");
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if ($_POST["weight"] == NULL)
{
echo "Error";
}
$weight = mysql_real_escape_string($_POST["weight"]);
if (query("INSERT INTO weight (user_id, weight_measurement) VALUES(?, ?)", $_SESSION["id"], $weight) == false){
echo "Update Error";
}
else {
echo "Success";
}
}
else
{
// else render form
printf("error");
}
?>
I also suggest to use jQuery.serialize() method to post all the fields from broser to the server.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#weight_tracker_form").submit(function() {
$.ajax({
type: "POST",
url: "../weight_tracker_process.php",
data: $("#weight_tracker_form").serialize(),
success: function(){
alert("success");
},
error: function(){
alert("error");
}
});
debugger;
return false;
});
});
</script>
</head>
<body>
<h2>Weight Tracker</h2>
<form id="weight_tracker_form" method="post">
Date: <input autofocus id="date" name="date" type="date"/>
Weight: <input id="weight" name="weight" type="text"/> Kg
<input type="submit" value="Submit Weight">
</form>
</body>
</html>

jquery post form

I have this code for send simple data using jquery , but no works , all time reload de page and no load contents i send by post
My code it´s this :
<script>
$(document).ready(function() {
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "indexer_adm.php?send_order2=ok",
success: function(data){
$("#load_order").html(data);
}
});
return false;
});
</script>
<form name="forma" id="form_order" method="post" action="">
<table width="100%" border="1">
<tr>
<td height="30" align="center" valign="middle">
<select name="select_order">
<option value="articles">Articles</option>
<option value="blogs">Blogs</option>
<option value="products">Products</option>
</select>
<input type="submit" name="Submit" value="Acceder">
<input type="hidden" name="send_order2" value="ok">
<input type="hidden" name="action_load" value="<?php echo $_REQUEST['action_load'];?>">
</td>
</tr>
<tr>
<td height="30" align="center" valign="middle"> </td>
</tr>
</table>
</form>
<div id="load_order"></div>
In the div called load_order , it must load the result of this send by post from the form , but the page reload and no works , i see the code many times but i don´t understand what happen
Thank´s for All
There is a syntax error in your code, you haven't closed the submit handler.
$(document).ready(function() {
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "indexer_adm.php?send_order2=ok",
success: function(data){
$("#load_order").html(data);
}
});
return false;
}); // <---
});
Try returning false inside of the submit block, rather than of the ready block.
You may have a syntax error since return false should stop the form from refreshing. I would use the post function instead:
<script>
$(function() {
$("#form_order").submit( function () {
$.post('indexer_adm.php?send_order2=ok', $(this).serialize(), function(data) {
$("#load_order").html(data);
});
return false;
});
</script>
Ok !!! , Thank´s everybody
The Right code :
<script>
$(document).ready(function() {
/*
$("#load_order").show(1000);
$("#load_order").load("<?php print "".$ruta_path_adm."".$ruta_modulos."/mod_order/indexer_adm.php?send_order2=ok";?>");
*/
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "<?php print "".$ruta_path_adm."".$ruta_modulos."/mod_order/indexer_adm.php?send_order2=ok";?>",
success: function(data){
$("#load_order").html(data);
}
});
return false;
});
});
</script>
Thank´s for the help i put bad the script and no see this , thank´s

Using jQuery's .get() to retrieve PHP data

I'm using jQuery's .ajax() to post to a PHP file called process.php. Process.php has a lot of code in it, but for simplicity's sake, let's just say it contains <?php echo 'hello'; ?>.
Is this the proper jQuery to insert process.php's results into div.results? :
$.get('process.php', function(data) {
$('.results').html(data);
});
So far it doesn't seem to be working.
Here's the HTML/Javascript file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#form").submit(function() {
var username = $('#username').attr('value');
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
return false;
});
});
</script>
</head>
<body id="body">
<form id="form" method="post">
<p>Your username: <input type="text" value="" name="username" id="username" /></p>
<input type="submit" id="submit" value="Submit" />
</form>
<div class="results"></div>
</body>
</html>
Here's process.php (greatly simplified):
<?php
/* get info from ajax post */
$username = htmlspecialchars(trim($_POST['username']));
echo $username;
?>
If you simply want to place the resulting string back into an element, use load().
$('.results').load('process.php');
However, looking at your code...
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
...shows you have misunderstood something. The correct anonymous function to assign to the success callback would be...
function(data) {
$('form#form').hide()
$('.results').html(data);
}
You could try something like this.
function ajax_login() {
if ($("#username").val()) {
$.post("/process.php", { username : $("#username").val() }, function(data) {
if (data.length) {
$("#login_form").hide();
$("#login_result").html(data);
}
})
} else {
$("#login_result").hide();
}
Then in process.php just echo out some text if the post sucesses.
process.php =>
if (isset($_POST['username'])
{
echo 'hello '.$_POST['username'];
}

Categories