How to delay an Ajax request? - php

I have a form that posts data to a server side page where the data is inserted into a mysql database and then a row count of the database is performed and the result returned to the form page where it is then displayed.
I am using an ajax to fetch the row count data and I'm wondering if it is possible to delay the Ajax call until the data has been inserted into the database so I can get an accurate row count that would include the data just submitted? The current code works but only shows a row count before the form has been submitted. I have to reload the page to get a true result.
Form.php
<form class="form-inline" action="" id="myform" form="" method="post">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name"></label>
<div class="col-md-8">
<input id="name" name="name" type="text" placeholder="name" class="form-control input-lg" required>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit1"></label>
<div class="col-md-4">
<button id="submitButtonId" name="submit1" class="btn btn-primary btn-xl">Submit</button>
</div>
</div>
</form>
<div id="count"></div>
</div>
The jquery
<script>
//Post data from form
$(document).ready(function(){
$("#submitButtonId").on("click",function(e){
e.preventDefault();
var formdata = $(this.form).serialize();
$.post('server.php', formdata,
function(data){
//Reset Form
$('#myform')[0].reset();
});
return false;
});
});
</script>
<script>
//Fetch Rowcount from server.php
$(document).ready(function(){
$.ajax({
url: 'data.php',
dataType: "json",
success: function (data) {
$("#count").html(data.count);
}
});
});
</script>
Server.php
<?php
//Connect to db
include_once("db_conx.php");
if( isset($_POST['name']) ){
$name= mysqli_real_escape_string($db_conx,$_POST['name']);
//Update Database
$stmt = $db_conx->prepare('INSERT INTO myTable set name=?');
$stmt->bind_param('s',$name);
$stmt->execute();
}
//Count Rows
$sql="SELECT name FROM myTable";
$query = mysqli_query($db_conx, $sql);
// Return the number of rows in result set
$rowcount=mysqli_num_rows($query);
// send output
$my_data=array(count=>"$rowcount");
echo json_encode($my_data,true);
?>

Call the ajax that fetches the row count inside the response of the first ajax post.
<script>
//Post data from form
$(document).ready(function(){
$("#submitButtonId").on("click",function(e){
e.preventDefault();
var formdata = $(this.form).serialize();
$.post('server.php', formdata,
function(data){
//Reset Form
$('#myform')[0].reset();
fetchRowCount();
});
return false;
});
});
function fetchRowCount() {
$.ajax({
url: 'data.php',
dataType: "json",
success: function (data) {
$("#count").html(data.count);
}
});
}
</script>

you can call the count row function after the post like this:
$.post('server.php', formdata,
function(data) {
//Reset Form
$('#myform')[0].reset();
$.ajax({
url: 'data.php',
dataType: "json",
success: function(data) {
$("#count").html(data.count);
});)
});

If I've understand correctly from the code, I see that the Fetch Rowcount is executed on $(document).ready.
It means that once (and everytime) the page is loaded, it is executed.
So it happens this:
1) the page is loaded
2) the Fetch rowcount is executed
3) You submit
4) you have to reload the page to go to point 2.
So the solution is to execute the row fetch as a callback function after the submit is executed, not on document ready.

Related

PHP and AJAX update data to database

I'm trying to update a simple string to the database with PHP and AJAX.
Here is the code:
HTML
<form id="phoneNumberForm" class="form-inline" method="post" enctype="multipart/form-data">
<div class="form-group mx-sm-3 mb-2 align-content-center">
<label for="phoneNumber" class="sr-only">Phone</label>
<input type="text" class="form-control" name="phoneNumber" id="phoneNumber" placeholder="Phone">
</div>
<button type="submit" name="phoneNumber_submit" id="phoneNumber_submit" class="btn btn-primary mb-2">Save</button>
<div id="phoneSuccess"></div>
</form>
PHP
if (isset($_POST['phoneNumber_submit'])) {
$phoneNumber = $_POST['phoneNumber'];
$profileEditAdmin = $db->query('UPDATE users SET user_phone = ? WHERE user_name = ?', $phoneNumber, $_SESSION['user_name']);
}
AJAX
$('#phoneNumberForm').submit(function(e) {
e.preventDefault();
let phoneNumber = $('#phoneNumber').val();
let $body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
$.ajax({
type: "POST",
data: {
phoneNumber:phoneNumber,
},
success: function() {
$('#phoneSuccess').html('<p>Saved.</p>');
setTimeout(function() {
$('#phoneSuccess').fadeOut();
}, 2000)
}
});
});
When I remove preventDefault() I get the entry in the database, but page is reloaded.
My goal is to have an entry in the database and to avoid page refreshing.
Here your PHP looks for a variable called phoneNumber_submit:
if (isset($_POST['phoneNumber_submit'])) {
But here your AJAX sends only a variable called phoneNumber:
data: {
phoneNumber:phoneNumber,
}
Clearly these two names do not match, so the if statement will never be true and the query will never run. It works when you submit the form without AJAX because you have name="phoneNumber_submit" on your submit button, so this value is sent to the server.
So you can either:
1) hard-code this value into your data parameter:
data: {
"phoneNumber": phoneNumber,
"phoneNumber_submit": true
}
OR
2) just let jQuery do the work for you and use the serialize function to get all the values and names you've already defined in your HTML and send them directly to the server, without you needing to specify each one again:
data: $(this).serialize()
Note: this in the above code will be your <form> element since you're handling the form's "submit" event.

How yo post to a database without a form php mysql html

I want to post the fields price and plateId to a database table without using any form, when the user clicks the Order button. Would it be possible? Otherwise, could you suggest an other solution?
<div class="menu">
<img src="/images/wings.png" />
<div>
<span id="price">Price:$40.00</span>
<div class="description">
<span id="plateId">HOT WINGS</span>
</div>
</div>
<button id="btn">Order</button>
</div>
<div class="menu">
<img src="/images/chicken.png" />
<div>
<span id="price">Price:$70.00</span>
<div class="description">
<span>Cooked Chicken</span>
</div>
</div>
<button id="btn">Order</button>
</div>
You need to call AJAX first and in your case you should collect information about plateId and price and return the data to AJAX so it can store in your database.
$('#btn').click(function () {
var orderInformation = {
var price = $(#price).text();
var plateId = $(#plateId).text();
};
$.ajax({
type: 'POST',
url: 'post-information-in-your-db.php',
dataType: "json",
data:(orderInformation),
success: function (data) {
alert(data);
}
});
});
It is also possible to treat the data returned from the variable and different display shapes after success.
you can make a server call through ajax by calling a javascript function as:
function send_value() {
$.ajax({
type: 'POST',
url: 'get.php',
dataType: "json",
data:({"uniId":"test"}),
success: function (data) {
console.log(data);
}
});
return false;
}
Pass data as an argument and put them as json in data:({"uniId":"test"})

Add the last added database record right after form submission

I have a registration form and I want to display all of the registrants. I want to output whatever records are in the database and then once the form is submitted to register another display that record as well.
I can successfully register the records and display them using ajax however It does not load the last registered record until you reload/comeback to the page. I want the last record to just join its brethren right after the form submits. I appreciate anything you can suggest.
home.php
<form id="register-student" method="post" action="process_student_registration.php" class="basic-form not-toggled">
<h2>Enter Student Info to Register</h2>
<fieldset id="student-name-group" class="form-group">
<div class="split">
<fieldset id="student-firstname-group">
<label for="student-first-name">First Name:</label>
<input id="student-first-name" type="text" name="student_first_name">
</fieldset>
</div>
<div class="split">
<fieldset id="student-lastname-group">
<label for="student-last-name">Last Name:</label>
<input id="student-last-name" type="text" name="student_last_name">
</fieldset>
</div>
</fieldset>
<fieldset class="submit-button">
<div id="loading" class="hidethis"><img id="loading-image" src="../../images/ajax-loader.gif" alt="Loading..." /></div>
<button id="register-student-button" type="submit" class="btn btn-success" name="register-student-button">Register Student</button>
</fieldset>
</form>
<script>
$(document).ready(function() {
var students = $.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "fetch_students.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#registered-students").html(response);
//alert(response);
}
});
});
</script>
<div id="registered-students"></div><!--End # registered-students-->
fetch_students.php
<?php
//Fetch the Students
//First lets make sure the user is allowed
require_once('../auth/agency_session.php');
//App Functions
require_once('../../includes/functions/app_functions.php');
//Agents Home Page
require_once('../../db_config.php');
$db_connect = connectDB($mysqli);
$agency_id = $_SESSION['ID'];
//Here we display all the students the agent has registered
//First check the connection
if(!mysqli_connect_errno()){
if($stmt = $db_connect->prepare("SELECT student_id, student_first_name, student_last_name, student_email FROM students WHERE agency_id = ?")){
//Bind Parameters
$stmt->bind_param('i', $agency_id);
//Execute
$stmt->execute();
//Store Results
$stmt->store_result();
//Get the rows
$num_rows = $stmt->num_rows;
//Bind the results
$stmt->bind_result($student_id, $student_first_name, $student_last_name, $student_email);
if($stmt->num_rows < 1){
echo'<h3>No Students Registered</h3>';
}
else{
//Fetch the values
echo'<h3>Registered Students</h3>';
echo'<ul class="grid">';
while($stmt->fetch()){
echo '<li id="'.$student_id.'" class="col">'.$student_first_name.' '.$student_last_name.'<span>'.$student_email.'</span></li>';
}//End While
echo'</ul>';
}//End else
}//End if no prepare statment happens
}//End if No connection
?>
process_student_registration.php
jQuery(document).ready(function($){
// Get the form and place it into a variable
var form = $('#register-student');
//Creating an Event Listener for the submit buttom on the contact form
$(form).submit(function(event){
$('.form-group').removeClass('.has-error');//Remove the error class on the things that have the error class
$('.error-message').remove();//Remove the error messages completeley
//Serialize the Form Data (Converts the data the user has entered into a key/value string that can be sent with an AJAX request)
var formData = $(form).serialize();
//Submit the form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
dataType :'json',
encode:true
//.done refers to a successful completion of the form
})
.done(function(data){
//Log the data into the console so that we can be sure what is happening
console.log(data);
//If we do have errors create the
if(!data.successmessage){
if(data.errors){
$('.error').remove();
$('.error-message').remove();
$('#register-student').addClass('form-has-error'); // add the form-has-error-class
$('#register-student-button').after('<p class="error">Please check the errors above.</p>');
$(form).removeClass('success');
$('.submit-success').remove();
if(data.errors.student_first_name){
$('#student-firstname-group').addClass('has-error'); // add the error class to show red input
$('#student-firstname-group').append('<div class="error-message"><p>' + data.errors.student_first_name + '</p></div>'); // add the actual error message under our input
}
if(data.errors.student_last_name){
$('#student-lastname-group').addClass('has-error'); // add the error class to show red input
$('#student-lastname-group').append('<div class="error-message"><p>' + data.errors.student_last_name + '</p></div>'); // add the actual error message under our input
}
}
} else if(data.successmessage){
//Remove the errors stuff
$('.error').remove();
$('.error-message').remove();
$('#register-student').removeClass('form-has-error'); // add the form-has-error-class
$('#blocking').removeClass('hidethis').addClass('showthis');
$('#loading').removeClass('hidethis').addClass('showthis');
$('.submit-success').remove();
//Add the success stuff
$(form).addClass('success');
setTimeout(function(){
$('#blocking').removeClass('showthis').addClass('hidethis');
$('#loading').removeClass('showthis').addClass('hidethis');
$('#register-student').append('<div class="submit-success"><p>' + data.successmessage + '</p></div>');
$(form).find('input, :text').val('');
//Run the Get operation on the database to add newly added records to the list
}, 5000);
//Clear the form upon successful completion
}
//.fail referes to an unsuccessful completion of the form
})
.fail(function(data){
//If there is a failed submission lets log the errors
console.log(data);
});
//Stop the broweser from submitting the form
event.preventDefault();
});
});
I had a similar issue... you are processing from two different php file:
process_student_registration.php and fetch_students.php
I believe your problem might be solved if you do all the processing from one file:
You are only passing two pieces of data. Rather than collecting the data from a form you can collect the data through inputs and go straight to the jQuery.
Your Collection HTML would look like this: NOTICE the dashes replaced with underscores.
<h2>Enter Student Info to Register</h2>
<input type="hidden" id="processStudent" value="process_student_registration.php">
<fieldset id="student-name-group" class="form-group">
<div class="split">
<fieldset id="student_firstname_group">
<label for="student_first_name">First Name:</label>
<input id="student_first_name" type="text" name="student_first_name">
</fieldset>
</div>
<div class="split">
<fieldset id="student_lastname_group">
<label for="student_last_name">Last Name:</label>
<input id="student_last_name" type="text" name="student_last_name">
</fieldset>
</div>
</fieldset>
<fieldset class="submit_button">
<div id="loading" class="hidethis"><img id="loading_image" src="../../images/ajax_loader.gif" alt="Loading..." /></div>
<button id="register_student_button" type="submit" class="btn btn_success" name="register_student_button">Register Student</button>
</fieldset>
<div id="registered-students"></div>
Your jQuery...
<script>
$(document).ready(function() {
$( "#register-student-button" ).click(function(){
var url = $('#processStudent').val();
var student_first_name = $('#student_first_name').val();
var student_last_name = $('#student_last_name').val();
var postit = $.post( url, {student_first_name:student_first_name,student_last_name:student_last_name});
postit.done(function( data ) {
alert('Student has been processed');
$('#registered-students').html(data);
});
});
});
Your PHP...
<?php
$student_first_name = $_POST['student_first_name'];
$student_last_name = $_POST['student_last_name'];
// PROCESS REGISTRATION HERE AS YOU ARE
// FETCH STUDENTS HERE AS YOU ARE
?>
I have figured out a solution. Basically I run the script to display records fomr the database on once on page load. Then I took basically the same script again and run it once more upon successful completion of the form. This way we only scan the database for new records as we need to. Not sre if it the most elegant or efficient way but she work like a charm.
So in my process_student_registration.php I added this to the success message.
//Run the Get operation on the database to add newly added records to the list
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "fetch_students.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#registered-students").html(response);
//alert(response);
}

Populating the '<input>' value based on the selected value of a dropdown list

I am trying to display an <input> value base on a selected value of a dropdown list using jquery ajax.
This is the markup for my form -
<div class="form-group">
<label for="" class="control-label">District</label>
<div class="element">
<select class="form-control" id="district">
<?php echo $option; ?>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="control-label">Province</label>
<div class="element">
<input type="text" class="form-control province" placeholder="Province" value="" disabled>
</div>
</div>
Just I need to display province input's value When selecting a district from above dropdown.
This is my ajax code -
$("#district").change(function(event) {
var id = $("#district").val();
//alert(data);
/* Send the data using post and put the results in a div */
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: id,
success: function(){
alert('Submitted successfully');
},
error:function(){
alert("failure");
}
});
// Prevent default posting of form
event.preventDefault();
});
When I selecting a district from the dropdown its going to this alert alert('Submitted successfully');. But I am not sure how to display PHP processing value in my text field.
This is my PHP code from proccess_province.php
// Require the configuration file before any PHP code:
require('./configuration.inc.php');
// Need the database connection:
require('../'.MYDB);
if(isset($_POST['id'])) {
$province_id = (int)$_POST['id'];
// Select exsiting data for an user and display them in the form for modify
$prep_stmt = " SELECT province
FROM province
WHERE province_id = ?";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
// Bind "$userId" to parameter.
$stmt->bind_param('i', $province_id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($province);
// Fetch all the records:
$stmt->fetch();
$db_province = filter_var($province, FILTER_SANITIZE_STRING);
//echo $province;
} else {
echo 'Database error';
}
echo $db_province;
}
Hope somebody may help me out.
Thank you.
Since you echo the value of the province in the ajax file, you need to set the value based on that response. Try this:
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: id,
success: function(data){
$('#province').val(data);
alert('Submitted successfully');
},
error:function(){
alert("failure");
}
});
And your markup:
<div class="form-group">
<label for="" class="control-label">Province</label>
<div class="element">
<input id="province" type="text" class="form-control province" placeholder="Province" value="">
</div>
</div>
If you want to set the value of input same as your select option value, you can change your success callback to this-
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: id,
success: function(){
$('.province').val(id);
},
error:function(){
alert("failure");
}
});
Or, if you are bothered about the ajax response and populate the value of input based on the ajax response, you can access the data being returned as follows-
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: id,
success: function(data){
// access data here and do something
},
error:function(){
alert("failure");
}
});
Add to php file -
$db_province = filter_var($province, FILTER_SANITIZE_STRING);
echo json_encode($db_province);
at the end.
On the html page -
<input type="text" id="province" class="form-control province" placeholder="Province" value="" readonly>
then set the response to the field value -
success: function(response){
$('#province').val(response)
alert('Submitted successfully');
},
In the the form change the code as,
<div class="form-group">
<label for="" class="control-label">Province</label>
<div class="element">
<input type="text" id="province" class="form-control province" placeholder="Province" value="">
</div>
</div>
In script section use,
<script type="text/javascript">
$("#district").change(function(event) {
var id = $("#district option:selected").val();
/* Send the data using post and put the results in a div */
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: {id : id},
dataType: "json",
success: function(){
$('#province').val(data.province);
alert('Submitted successfully');
},
error:function(){
alert("failure");
}
});
// Prevent default posting of form
event.preventDefault();
});
</script>
In the proccess_province.php file, instead of
echo $db_province;
use,
echo json_encode(array('province' => $db_province));
Hope it helps.

CodeIgniter and AJAX form submit

I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.
How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?
The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val().
Also there is an unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function(data){
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
Html part in view
<form id="comment" method="post">
<h2>Enter Your Details</h2>
<center><div id="result"></div></center>
<div class="form_fld">
<label>Name</label>
<input type="text" placeholder="Enter Your Full Name" name="name" required="">
</div>
<div class="form_fld">
<label>Email ID</label>
<input type="text" placeholder="Enter Email ID" name="email" required="">
</div>
<div class="form_fld">
<label>Contact Number</label>
<input type="text" placeholder="Enter Contact Number" name="contact" required="">
</div>
<div class="form_fld">
<label>Developer</label>
<select name="developer">
<option>Lotus</option>
<option>Ekta</option>
<option>Proviso</option>
<option>Dosti</option>
<option>All</option>
</select>
</div>
<div class="form_fld">
<button type="submit" id="send">Submit</button>
</div>
</form>
After Html Part Just put ajax request
<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "home/contact",
data: dataString,
success: function(data){
// alert('Successful!');
$("#result").html('Successfully updated record!');
$("#result").addClass("alert alert-success");
}
});
return false; //stop the actual form post !important!
});
});
</script>
Within Controller
public function contact()
{
$ip = $_SERVER['REMOTE_ADDR'];
$data = array('name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'number' => $this->input->post('contact'),
'developer' => $this->input->post('developer'),
'ip' => $ip,
'date' => date("d/m/Y"));
$result = $this->User_model->contact($data);
print_r($result);
}
You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.
You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.
You should also check if you have errors in your console.
To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.
You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error e.preventDefault(); is not stopping the ajax.
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $("#form").serializeArray(),
success: function(resp){
$('#container').html(resp);
},
error: function(resp) { alert(JSON.stringify(resp)); }
});

Categories