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.
Related
I have my first PHP page having search form:
<form action="#" class="form-inline" id="form_srch">
<input type="text" id="toSearch" name="toSearch" placeholder="Enter Application Number" class="form-control" style="width:250px" required >
<button type="button" class="btn btn-primary" onclick="search()">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
<i><b><p style="display:none;color:red" id="result">** Empty Value</p></b></i>
</form>
<div id="ajax"></div>
and a javascript function
<script>
function liveCheck() {
$("#result").show();
}
function search() {
var inp = $("#toSearch").val();
if(jQuery.trim(inp).length > 0)
{
jQuery.ajax({
url: "load_search_prereg.php",
data:{ to : inp },
type: "POST",
success:function(data){
$("#ajax").load('load_search_prereg.php');
//alert(data);
},
error:function (){}
});
}
else{
liveCheck();
}
}
</script>
And i have my second PHP page named load_search_prereg.php to process the POSTed input and the code is
<?php
require '../backend/_classes.php';
$x = new DB();
$id = $_POST['to'];
$sql=$x->select(1,'*','tblregistration','app_number',"'$id'");
$fetch = $sql->fetchObject();
var_dump($fetch);
The problem is when i clicked the search button in my first PHP page, It displays no array of posted data while im using the $("#ajax").load('load_search_prereg.php'); method in my javascript. But when i use alert(data);, it returns the expected result. Does the problem occur in $("#ajax").load('load_search_prereg.php'); method ? Help pls.
Not:
$("#ajax").load('load_search_prereg.php');
But:
$("#ajax").html(data);
I've assumed you just want to write this data into div
edit:
instead of var_dump($fetch); you must return your data a JSON object, eg:
$fetch = $sql->fetchObject();
echo json_encode($fetch);
Then you can do in js what you want
It should be method:"POST" instead of type: "POST".
By default method is set to GET.
I've been reading multiple threads about similar cases but even now I'm still unable to do it correctly.
What I want to do
Basically, i.e. I have form which allows user to change his login (simply query to database).
PHP script looks like that:
if(isset($_POST['login'])) {
$doEdit = $user->editData("login", $_POST['login']);
if($doEdit) {
$result = displayInfobox('success', 'Good!');
} else {
$result = displayInfobox('warning', 'Bad!');
}
} else {
$error = 'Bad!';
echo $error;
}
displayInfobox is just a div with class i.e. success and content - Good!.
Right now I would like to send this form by AJAX and display $result without reloading page.
HTML:
<form id="changeLogin" method="post" class="form-inline" action="usercp.php?action=editLogin">
<label for="login">Login:</label><br />
<div class="form-group ">
<input type="text" class="form-control" name="login" id="login" required>
<input type="submit" value="ZmieĆ" class="btn btn-primary">
</div>
</form>
And finnally - my jquery/ajax:
$("#changeLogin").submit(function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(result) {
alert(result);
},
error: function(response) {}
});
e.preventDefault();
});
$("#changeLogin").submit();
If I leave "success" blank, it works -> form is submitted by ajax, login changed, but I do not see the result message. Otherwise whole page get reloaded.
Also, when I hit F5 form is being submited once again (even in Ajax).
I cant add comments because i do not have enough reputation but...
You should delete the last line with $("#changeLogin").submit();
And then in your php script file you should echo the result so you can get this result in ajax request. After that in your success method you have to read the result and (for example) append it somewhere to show the success or error box
I think you can use a normal button instead of submit button,just onclick can be an ajax request, the form should not be submitted,good luck.
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);
}
So, as the titles says, I need some clarifications on how to make interact jquery, ajax and php in order to realize a form submission and other controls.
This is my first web experience with jquery, ajax and php used all together, and, of course, I'm facing some problems.
I describe what I'm trying to do.
Basically, I've an index page with a registration form:
<form id="formRegistration" action="registration_success.php" method="post">
<p id="ptxtFullName">
<input id="txtFullName" name="txtFullName" class="textbox" placeholder="Insert you full name" type="text" />
</p>
<p id="pTxtEmail">
<input id="txtEmail" name="txtEmail" class="textbox" placeholder="Insert an email" type="text" />
</p>
<p id="pTxtPassword">
<input id="txtPassword" name="txtPassword" class="textbox" placeholder="Choose a password" type="password" />
</p>
<p id="pTxtPasswordConfirmation">
<input id="txtPasswordConfirmation" name="txtPasswordConfirmation" class="textbox" placeholder="Confirm your password" type="password" />
</p>
<p id="pBtnRegistration">
<input id="btnRegistration" type="submit" value="Register!" />
</p>
</form>
Then, I've a jquery file, which does all the input validation things (some effects if the inputs are correct or incorrect, and things like these), and, if the validation went good, makes an ajax call.
This is only an example, I don't post the entire file, because it's quite huge:
jQuery(document).ready(function($) {
$(function() {
var $fullName = $("input[name='txtFullName']");
var $email = $("input[name='txtEmail']");
var $password = $("input[name='txtPassword']");
var $passwordConfirmation = $("input[name='txtPasswordConfirmation']");
$("#btnRegistration").click(function() {
//Validation controls and effects.
});
return true;
});
$.ajax({
type : "POST",
url : "process_registration.php",
data : "fullName", "email", "password",
dataType : "HTML",
success : function() {
alert("Ok");
},
error : function() {
alert("Error");
}
});
});
NOTE that, the jquery file, when I add the ajax call, it stops to work, whilst if I don't add the ajax call, it works perfectly.
And then, here's my php file, named process_registration.php, wich is supposed to control if the email is already in use, and, after that, to insert the validated input datas into a MySQL database:
<?php
require 'db_connection.php';
$fullName = isset($_POST["fullName"]);
$email = isset($_POST["email"]);
$password = isset($_POST['password']);
$sql = mysql_query("SELECT * FROM utente WHERE mail = '$email'") or die("Email already in use");
$num_rows = mysql_num_rows($sql);
if ($num_rows == 0)
{
$password_md5 = md5($password);
mysql_query("INSERT INTO user (Full_Name , Email, Password) VALUES
('$fullName', '$email', '$password_md5')") OR DIE(mysql_error());
}
Thats all.
Obviously it isn't working.
Maybe I'm adopting a completely wrong approach in this thing?
Thanks in advance for your kindess and your answers.
Try using this:
jQuery(document).ready(function($) {
$('#formRegistration').submit(function() {
e.preventDefault();
// Perform form validation here and return from this function
// if you do not want to submit the form.
$.ajax({
type : "POST",
url : "process_registration.php",
data : $(this).serialize(),
dataType : 'html',
success : function() {
alert("Ok");
},
error : function() {
alert("Error");
}
});
});
});
This registers an event handler that gets called when the form is going to be submitted. The call to e.preventDefault() prevents the regular form submission. Then the handler posts the form via ajax.
You'll have to change the names of the input elements though because they need to match the names your PHP code is looking for (e.g., change "txtFullName" to "fullName").
The data attribute in the ajax call is supposed to be an object.
data : {
"fullName" : fullName,
"email" : email
}
I am trying to add data to a database and for some reason it does not always work. I'd say 80% of the time it will work and I'll see the result in the database but sometimes its like the script won't run.
here is the ajax :
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('.error').hide();
$("#success").hide();
$(".button").click(function () {
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: $("input#name"),
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
});
});
});
});
</script>
here is the html:
<div id = "contact_form">
<form name ="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="send" />
</fieldset>
<span id="success"> the name has been updated successfully!</span>
</form>
</div>
<div id ="upd"></div>
and here is the proccess.php file:
<?php
$va = $_POST["name"];
$dbconnection = mysql_connect('adatabase','someuser','somepw');
if(!mysql_select_db('some_database', $dbconnection)) {
echo mysql_error();
}
else
{
echo 'connection success';
}
$sql = "INSERT INTO some_db(text) VALUES ('$va')";
$result = mysql_query($sql) or die('erreur sql!'.mysql_error());
if(!$result) {
echo "not working";
}
else {
echo "working";
}
?>
so how come it does not always insert into the database?
and is there a way to get the result from the php if(!$result) to show in the success part of the ajax?
You're actually passing a jQuery-Object to your PHP-File.
$.post("class/proccess.php", {
name: $("input#name").val() //Pass val() not the whole jQuery-Object!
}, function() {
/* success */
});
While you're debugging, make sure MySQL errors are enabled.
In your Javascript for the Ajax success handler, show an alert with the text returned from the call. That way if there's an error with MySQL you'll see it.
Another thing is, could the "text" field be set in the database as UNIQUE? Trying to insert a new record with a duplicate string would fail in that case.
And... the name of the field isn't really 'text' is it? I would recommend avoiding field names that are the same as the basic data types for MySQL. Just to avoid confusion if no other reason.
If it is not working sometimes, you need to check the returned string for errors. The right way to do this using AJAX is as follows.
You can include a parameter in your success callback which will fetch the page-result from the PHP.
Instead of
success: function () {
...
}
use
success: function (data) {
alert(data);
}
Change your ajax call to:
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: {name : $("input#name").val()},
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
So that $_POST['name'] is set to the value of your input box.
Also, as suggested, you should change your mysql functions to mysqli functions to help protect against sql injections.