• Hi,
    I created my own template that has the PHP code I want to run.
    In this template, I have a form to be displayed on a certain page. When the user fills this form, the form is saved in the database. What I want is to validate the form with AJAX. I have written the code for that, but I am confused about where to put this code :
    I have the form I want to submit in myTemplate.php:

    <script>
    
    $(document).ready(function (){
    
    $("#editStudent").submit(function (event){
    
    event.preventDefault();
    var studentName = $("name1").val();
    var studentgrade = $("grade1").val();
    var studentGender = $("gender1").val();
    var studentIxlUsername = $("IXLusername1").val();
    var studentIxlPassword = $("IXLpassword1").val();
    var studentJksMailusername = $("jksmailUsername1").val();
    var studenrJksMailPassword = $("jksmailPassword1").val();
    var studentTurnitinUsername = $("turnitinUsername1").val();
    var studentTurnitinPassword = $("turnitinPassword1").val();
    var studentEmail = $("Email1").val();
    var studentManagebacUsername = $("managebacUsername1").val();
    var studentManagebacPassword = $("managebacPassword1").val();
    var studentCompareEmail = $("compareEmail").val();
    var submitStudent =$("save").val();
    
    $(".studentUpdated").load("https://digitect.com/jksportal/edit.php", {
    studentName : studentName,
    studentgrade : studentgrade,
    studentGender : studentGender,
    studentCompareEmail :studentCompareEmail
    
    });
    }):
    
    });
    
    </script>
    
    <?php
    echo ' <div>
    
    <form id="editStudent" method="post" action="https://digitect.com/jksportal/edit.php" >
    
    <label for="name">Name: </label>
    	<input id="name1" name="name1"  value = "'.$name.' " required><br>
    
    <input type="hidden" id="gradeHidden" name="gradeHidden"  value = "'.$grade.'">
    <label for="grade">Grade: </label>
    <select name="grade1" id="grade1" value = "'.$grade.'"required>
    
      <option value="11">11</option>
      <option value="12">12</option>
    </select><br>
    <input type="hidden" id="genderHidden" name="genderHidden"  value = "'.$gender.'">
    <label for="gender">Gender: </label>
    <select name="gender1" id="gender1" value = "'.$gender.'"required>
    
      <option value="M">M</option>
      <option value="F">F</option>
    </select><br>
    <input type="hidden" id="compareEmail" name="compareEmail" value="'.$mailUser.'"> 
      <input type="submit" name="save" id="save" class="save" value="Save" >
    // this is where i want to display the appropriate error or success message
    echo '<p class ="studentUpdated" id="studentUpdated" 
    ';
    ?>
    and in the edit.php file I have:
    
    <?php
    
    if (isset($_POST['save'])){
    $studentName= $_POST['studentName'];
    $studentgrade=$_POST['studentgrade'];
    $studentGender=$_POST['studentGender'];
    $studentCompareEmail=$_POST['studentCompareEmail'];
     
     $errprEmpty =false;
     $errorEmail=false;
       
    if (empty($studentName || empty($studentgrade) || empty($studentGender)|| empty($studentIxlUsername)|| empty($studentIxlPassword)|| empty($studentJksMailusername)|| empty($studenrJksMailPassword)|| empty($studentTurnitinUsername)|| empty($studentTurnitinPassword)|| empty($studentManagebacUsername)|| empty($studentManagebacPassword))
    {
    echo "<span class='form-error-haya'> Fill in all fields</span>";
    $errprEmpty=true;
    }
    
    elseif (!filter_var($studentEmail, FILTER_VALIDATE_EMAIL))
    {
    echo "<span class='form-error-haya' > Write a valid email address </span>";
    $errorEmail=true;
    }
    
    else
    {
    echo "<span class='form-success-haya' > Student Updated! </span>";
    }
    }
    
    else {
    echo "There was an Error";
    }
    
    $wpdb->update('Students',
     array('Name'=>$name1,
      'Grade'=>$grade1,
      'Gender'=>$gender1,
    array('Email' => $studentCompareEmail));
    
    ?>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
    $("#name1,grade1,gender1,#IXLusername1,#IXLpassword1,#jksmailUsername1,#jksmailPassword1,#turnitinUsername1,#turnitinPassword1,#Email1,#managebacUsername1,#managebacPassword1").removeClass("input-error-haya");
    
    var errorEmpty="<?php echo $errorEmpty; ?>";
    var errorEmail="<?php echo $errorEmail; ?>";
    
    if (errorEmpty==true){
    $("#name1,#IXLusername1,#IXLpassword1,#jksmailUsername1,#jksmailPassword1,#turnitinUsername1,#turnitinPassword1,#Email1,#managebacUsername1,#managebacPassword1").addClass("input-error-haya");
    }
    if (errorEmail==true){
    $("#Email1").addClass("input-error-haya");
    }
    
    if (errorEmpty==false && errorEmail==false){
    $("#name1,#IXLusername1,#IXLpassword1,#jksmailUsername1,#jksmailPassword1,#turnitinUsername1,#turnitinPassword1,#Email1,#managebacUsername1,#managebacPassword1").addClass("input-error-haya").val("");
    
    }
    
    </script>

    This code is not working, and after much research, I found that I need to use ajax hooks and editing functions.php file. I’m not sure how to do that
    could you please assist?

    • This topic was modified 3 years, 11 months ago by bcworkz. Reason: code fixed
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    You shouldn’t use jQuery from googleapis because there’s a decent chance it’ll conflict with the version shipped with WP. Outputting script within <script> blocks isn’t ideal because dependencies can be difficult to resolve. Scripts are better enqueued so dependencies can be resolved. Then to load jQuery you just specify ['jquery'] as a dependency when you enqueue your script.
    https://developer.www.ads-software.com/reference/functions/wp_enqueue_script/

    If your Ajax handler does not utilize WP resources, it’s no different than Ajax on any website. But if you need WP resources, there’s a specific way to do Ajax for WP. Review the related sections in the Plugin Handbook.
    https://developer.www.ads-software.com/plugins/javascript/ajax/

    Thread Starter hayaalahmad

    (@hayaalahmad)

    Ok thank you. Here is where I am at now:

    In my functions.php I wrote:

    add_action('wp_enqueue_scripts','enqueue_jquery_form');
    function enqueue_jquery_form() {
    	wp_enqueue_script('jquery-form');
    		wp_enqueue_script('jquery');}
    	
    add_action('wp_ajax_editStudent', 'editStudent');
    add_action('wp_ajax_nopriv_editStudent', 'editStudent');
    
    function editStudent(){
    	wp_send_json_success("test");}

    and in myTemplate.php:

    echo '
    <form id="editStudentForm" method="post" action="'.admin_url("admin-ajax.php").'">
    <input type="hidden" name="action" value="editStudent">
    <label for="name">Name: </label>
    	<input id="name1" name="name1"  value = "'.$name.' " required><br>
    
    <input type="hidden" id="gradeHidden" name="gradeHidden"  value = "'.$grade.'">
    </form>';
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($){
    	$("#editStudentForm").ajaxForm({
    		success: function(response){
    		console.log(response);		 }
    	}):
    });
    </script>

    And now the problem is, I am getting the response :
    {“success”:true,”data”:”test”} in a new page which is /wp-admin/admin-ajax.php
    I don’t understand why is this happening since ajax is suppose to run without reloading the page!.

    • This reply was modified 3 years, 11 months ago by bcworkz. Reason: code fixed
    Moderator bcworkz

    (@bcworkz)

    I’ve not used jquery-form, so I’m not sure what listeners it’s setting up. It’s not clear to me how your form data even gets submitted. With onchange event? I can tell you that often when we get new page behavior when attempting Ajax, typically a submit button is involved, which by default invokes a new page. Thus we need to call the .preventDefault() method of the event object to suppress new page behavior and let the script manage the Ajax request/response. I suspect something along those lines is happening, but related to what .ajaxForm() is doing. It doesn’t add up since it’s obviously for Ajax and I’d expect it to not invoke a new page in what it does.

    Long story short, IDK. All I can suggest is to try something else like .ajax() from an event like onchange.

    BTW, when you post code in these forums, please use the code button or demarcate code with backticks. When you don’t, the forum’s parser corrupts you code, making it difficult for others to test your code to help identify problems. I fixed the code in your last reply for you.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘form validation with ajax’ is closed to new replies.