I'm checking this form for errors using PHP code which is on the same index.php file:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<?php if(!empty($formErrors)){ ?>
<div id="errors">
<?php
foreach($formErrors as $error)
{ echo '* ' . $error . '.<br/>';}
?>
</div>
<?php } ?>
<input type="text" name="firstname">
<input type="submit" value="send">
</form>
The PHP code is as follows:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$fname = $_POST['firstname'];
$formErrors = array();
if(strlen($fname) < 2 ){
$formErrors[] = "First name must be longer than 1 character";
}
}
?>
Everything is working fine up to this point, except that I want to prevent the page from scrolling to the top upon form submission. Therefore i used ajax to solve this problem:
$("form").submit(function(e){
e.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize()
});
});
Now the form errors won't display anymore, which is not what I want. How can I show the errors again while not discarding ajax? Thanks.
Although this isn't the best way, you can echo the JSON from the file and display those errors in your ajax function like below:
FrontEnd(ajax):
$("form").submit(function(e){
e.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize() + '&ajax=1',
dataType:'json',
success: function(res){
if(res.success === false){
$('#errors').html('<ul><li>' + res.errors.join('</li><li>') + '</li></ul>');
}else{
$('#errors').html('');
}
}
});
});
Backend:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$fname = $_POST['firstname'];
$formErrors = array();
if(strlen($fname) < 2 ){
$formErrors[] = "First name must be longer than 1 character";
}
// add this additional check
if(($_POST['ajax'] ?? 'N/A') == '1'){
echo json_encode(['success' => false,'errors' => $formErrors]);
exit; // since we will only send the JSON back to the browser, not the entire form
}
}
?>
Change your form code to this(adding a errors div always by default):
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<div id="errors"></div>
<input type="text" name="firstname">
<input type="submit" value="send">
</form>
Related
I am creating my custom form-edit-account.php template. This contains a form that allows users to change their name, surname, password and other info. Originally the form does not perform ajax requests, you click the save changes button, the data is saved and the page is reloaded. The required fields and their validity are managed by the file https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-form-handler.html#source-view.218
What I did was create ajax request for the form in order to save the fields without the page refresh. The fields are edited and updated correctly, so it works. However, handling validation not working.
Somehow I need field handling validation but I don't know how to proceed I'm stuck at this point. I have two ideas I could work on:
Try somehow to make the original handling validation work.
Create a custom handling validation with js or php separately from the original file, but I don't know if this is correct.
How could I handle field validation? I hope someone can help me understand how I could do this, I appreciate any help and thank you for any replies.
Example of My-Form
<form name="Form" class="mts-edit-account" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> >
<!-- Fist & Last Name Field -->
<div class="row name_surname">
<div class="form-row">
<label class="t3" for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" class="field-settings" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div class="form-row">
<label class="t3" for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" class="field-settings" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />
</div>
<!-- Save Settings -->
<p style="margin-bottom: 0px!important;">
<?php wp_nonce_field( 'save_account_details', 'save-account-details-nonce' ); ?>
<button type="submit" class="edit-account-button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>"><?php esc_html_e( 'Salva modifiche', 'woocommerce' ); ?></button>
<input type="hidden" name="action" value="save_account_details" />
</p>
</div>
</form>
Js File
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) { //form onsubmit ecent
e.preventDefault(); // the preventDefault function stop default form action
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success: function(data) {
alert('Form Inviato');
}
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'wp_ajax_nopriv_save_account_details', 'save_account_details' );
add_action('woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
// A default response holder, which will have data for sending back to our js file
$response = array(
'error' => false,
);
// Example for creating an response with error information (This not working)
if (trim($_POST['account_first_name']) == '') {
$response['error'] = true;
$response['error_message'] = 'Name is required';
if (trim($_POST['account_first_name']) == '') {
$response['status'] = false;
$response['message'] = 'Name is required';
}else{
$response['status'] = true;
$response['message'] = 'success';
}
// Exit here, for not processing further because of the error
echo json_encode($response);
exit();
}
exit(json_encode($response));
}
Thanks to the intervention of Martin Mirchev in the comments I was able to solve the problem.Here is the solution for anyone who is in the same conditions.
(The form remained the same)
Js File
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
//jQuery('.woocommerce-notices-wrapper').append(response);
jQuery('.woocommerce-notices-wrapper').prepend(response);
}
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
$response = wc_print_notices();
} else {
$response = "Settings Saved!";
}
// Don't forget to exit at the end of processing
echo json_encode($response);
exit();
}
I am submitting form using ajax in the while loop but because of loop the same form id is using many times , so as a result the form is submitting only once . I think i have to make unique id every time in the loop for the form but don't know how.
Here is my code so far,
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while($row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC)){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?>
<form id="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php } ?>
<script src="jQuery v2.1.1"></script>
<script>
$("#subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
submit_subcmt.php
<?php
$comtr_id =$_POST['comtr_id'];
$comment_id =$_POST['comment_id'];
echo $comtr_id;
echo $comment_id;
?>
Try this.
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while($row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC)){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?>
<form class="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php } ?>
<script src="jQuery v2.1.1"></script>
<script>
$(".subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
To illustrate the comment I made above you could try something similar to this perhaps.
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while( $row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC) ){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?> <!-- use a class attribute here -->
<form class="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php
}//end loop
?>
<script src="jQuery v2.1.1"></script>
<script>
/* and assign event handlers to form objects with this class as per above */
$("form.subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
I am trying to make an search box which to display the "Address" from MYSQL/PHP
I have used ajax to refresh page without leaving page, but when I run in browser, it always give me an error. when I used console, the return result of echo $_POST['name'] = ( html code of header.php + "What I need" + html code of footer.php )
<?php
include 'header.php';
include 'Connect.php';
if( isset($_POST['ajax']) && isset($_POST['name']) ){
echo $_POST['name'];
exit;
}
?>
<form method="POST">
<label>Username</label>
<input type="text" name="name" required="required" id='name'>
<div id='response'></div>
</form>
<script>
$(document).ready(function(){
$('#name').keyup(function(){
var name = $('#name').val();
$.ajax({
type: 'post',
url: index.php,
data: {ajax: 1,name: name},
success: function(response){
$('#response').text(response);
}
});
});
});
</script>
<?php
if(isset($_POST['name'])){
$username = $_POST['name'];
$stmt = $con->prepare("SELECT Username, FullName, Adresse, Email, Phone FROM dbo.users WHERE Username= ?");
$stmt->execute(array($username));
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$Username = $row["Username"];
$FullName = $row["FullName"];
$Adresse = $row["Adresse"];
$Email = $row["Email"];
$Phone = $row["Phone"];
echo "<tr>
<div>
<td>".$Username."</td>
<td>".$FullName."</td>
<td>".$sEID."</td>
<td>".$Email."</td>
<td>".$Phone."</td>
</div>
</tr>";
}
echo "</table>
</div>";
} else echo '<div class="alert alert-danger"> This Name <strong>is not exit</strong></div>';
include $tpl.'footer.php';
}
?>
Your question isn't very clear... if i understand correctly... this is broken by design, you're calling the page itself and update #name with the content of the entire page, thats why you see html + "what you need" (the response): the response is the whole page.
The right way to do this would be to move the second part of PHP code (where you perform the query ecc.) on a separate script and then call that new script by putting its name as the url parameter in the ajax call.
thank you for your respanse, i want to use the value returned by ajax to use with MYSQL/PHP to echo $row['Address'];
if i move the second part of PHP code the result is
echo $_POST['name'] = ( "What I need" + html code of footer.php )
I am currently working on a PHP based web-interface, with a login system.
But for some reason when I hit login, it seems to get to the login.php and return a response back.
But the thing is, the response is not what I need to have, and furthermore logging in is still not happening.
The HTML based login form (Within a modal):
<form class="form" method="post" action="<?php echo Utils::resolveInternalUrl('backend/Login.php') ?>" id="loginForm">
<div class="form-group">
<label for="loginUsername">Username:</label> <input type="text" class="form-control" name="loginUsername" id="loginUsername" />
</div>
<div class="form-group">
<label for="loginPassword">Password:</label> <input type="password" class="form-control" name="loginPassword" id="loginPassword"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
Javascript/jQuery related to login:
var form = $('#loginForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
'data': form.serialize(),
'type': $(this).attr('method'),
'url': $(this).attr('action'),
'dataType': 'JSON',
success: function (data) {
alert("Success: " + data)
},
error: function (error) {
alert("Error: " + error)
}
})
})
PHP backend, related to login:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$database = Database::getDefaultInstance();
if(isset($_POST['loginUsername']) && isset($_POST['loginPassword'])) {
$connection = $database->getConnection();
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
echo $username . ":" . $password;
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
if($stmt->fetch()) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['sessionId'] = Utils::randomNumber(32);
echo json_encode("Successfully logged in as ${username}.");
exit;
} else {
echo json_encode("No user exists with the name \"${username}\".");
exit;
}
} else {
echo json_encode("Username and/or password is not provided.");
exit;
}
} else {
echo json_encode("Submit method is not POST.");
exit;
}
The result of it:
Click here for screenshot
Edit:
Changed SQL query to: SELECT COUNT(*) FROM banmanagement.users WHERE username=:username;
Edit 2:
Per suggestion, I have used var_dump the output var_dump($_POST) is: array(0) { }.
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
I'm assuming you're using PDO on the backend. If so, you don't need the semicolon in your query. That's why your fetch is failing.
$stmt = $connection->query("SELECT * FROM banmanagement.users");
Ok, so that wasn't it. I was reading the wrong braces. Have you tried var_dump($_POST) to see what, if anything, is being sent?
I am using php and javascript in order to display data from mysql in a table where each row must have an update button.
It seems to be working fine but i'm getting a weird behavior: it works when i click the buttons in consecutive order (#1 then #2 then #3..) but when i click them randomly (starting with #2 or #3...) it does nothing, just reloads the page.
Can you help me find what am i doing wrong, here's my code so far...
Thanks!
list.php:
<?php
$q= "SELECT * FROM list WHERE id = $f ORDER BY id";
if ($query = mysqli_query($db_con, $q)) {
$y=1;
echo '<table>'.
'<tr>'.
'<th>#</th>'.
'<th>Name</th>'.
'<th>Edit</th>'.
'</tr>';
while ($reg= mysqli_fetch_row($query)){
echo '<tr>';
echo '<td>'.$y.'</td>';
echo '<td>'.$reg[0].'</td>';
echo '<td>
<form id="frm_data'.$y.'" method="post">
<input type="hidden" id="name" name="name" value="'.$reg[0].'" />
<input type="hidden" id="f" name="f" value="'.$f.'" />
<input type="hidden" id="a" name="a" value="'.$a.'" />
<input id="FormSubmit" type="submit" value="EDIT">
</form>
</td></tr>';
$y = $y +1;
}
echo '</table>';
}
?>
validate.js
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
e.preventDefault();
$("#FormSubmit").hide();
var myData = {
name: $("#name").val(),
a: $("#a").val(),
f: $("#f").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "update.php", //Where to make Ajax calls
dataType:"json", // Data type, HTML, json etc.
data:myData, //Form variables
success : function(data) {
if(data.status == 'success'){
alert("OK!");
} else if(data.status == 'error') {
alert("ERROR!");
}
},
error : function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
update.php
<?php
$f = $_POST["f"];
$name = $_POST["name"];
$q = "UPDATE list SET edited = '1' WHERE id = '$f' AND name = '$name' ";
$update_row = mysqli_query($db_con, $q);
if (!$update_row) {
$response_array['status'] = 'error';
} else {
$response_array['status'] = 'success';
}
?>