Dynamic content loading using AJAX to selectively update a designated section

I am having trouble displaying the error message in my form. Currently, it is causing my form page to load four times. Can someone help me identify what I did wrong? I only want to display that span:

controllers:

<?php
/* 
 * File Name: user.php
 */


if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->database();
        $this->load->library('form_validation');
        //load the user model
        $this->load->model('User_model');
    }

    //index function
    function index()
    {

        //fetch data from country table
      $data['country'] = $this->User_model->get_country();


        //set validation rules
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules  ('passconf', 'Password Confirmation', 'trim|required');




        if ($this->form_validation->run() == FALSE)
        {
            //fail validation
            $this->load->view('user_view2', $data);
        }
        else
        {    
            //pass validation
            $data = array(
                'user_email' => $this->input->post('email'),
                'Password' => $this->input->post('passconf'),
                //encrypting pass on database.
                'Password' => password_hash('passconf', PASSWORD_BCRYPT),

            );

            //insert the form data into database
            $this->db->insert('test', $data);

            //display success message
            $this->session->set_flashdata('msg', '<div class="alert alert-success text-center">You Are Now Registered</div>');
            redirect('user/index');
        }

    }

    //custom validation function for dropdown input
    function combo_check($str)
    {
        if ($str == '-SELECT-')
        {
            $this->form_validation->set_message('combo_check', 'Invalid %s you need pick one');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

    //custom validation function to accept only alpha and space input
    function alpha_only_space($str)
    {
        if (!preg_match("/^([-a-z ])+$/i", $str))
        {
            $this->form_validation->set_message('alpha_only_space', 'The %s field must contain only alphabets or spaces');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
}
?>

user_view.php

<?php 
        $attributes = array("class" => "form-horizontal", "id" => "userform", "name" => "userform");
        echo form_open("user/index", $attributes);?>

      <div class="form-group">
        <div class="row colbox">
        <div class="col-lg-4 col-sm-4">
            <label for="email" class="control-label">Email address</label>
        </div>
        <div class="col-lg-8 col-sm-8">
            <input id="email" name="email" placeholder="type your email here" type="text" class="form-control"  value="<?php echo set_value('email'); ?>" />
            <span class="text-danger"><?php echo form_error('email'); ?></span>
        </div>
        </div>
        </div>

  <div class="form-group">
                <div class="row colbox">
                <div class="col-lg-4 col-sm-4">
                    <label for="passconf" class="control-label">Password</label>
                </div>
                <div class="col-lg-8 col-sm-8">
                    <input id="passconf" name="passconf" placeholder="your password" type="password" class="form-control" value="<?php echo set_value('passconf'); ?>" />
                    <span class="text-danger"><?php echo form_error('passconf'); ?></span>
                </div>
                </div>

</div>
 <div class="form-group">
        <div class="col-sm-offset-4 col-lg-8 col-sm-8 text-left">
            <input id="btn_add" name="btn_add" type="submit" class="btn btn-primary" value="Insert" />
            <input id="btn_cancel" name="btn_cancel" type="reset" class="btn btn-danger" value="Cancel" />
        </div>
        </div>

<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>

jquery code

 var frm = $('#userform');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            //data: $('#myform').serialize(),
            success: function (data) {
                $(".text-danger").html(data);
            }
        });

        ev.preventDefault();
    });

Answer №1

In order to prevent the form from being submitted back to the server, you must include return false; after the line ev.preventDefault();. This is particularly necessary when using frm.submit along with your ajax call.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize jQuery to load AngularJS libraries into your web application

Trying to incorporate AngularJS into a jQuery-built webpage has been my latest challenge. While the rest of the site was developed using jQuery, I wanted to tap into the potential of AngularJS for a specific page. That's when I decided to do this: jQ ...

Alignment of Material-UI dialogue buttons on the left side

I have a Dialog containing three buttons as shown below: https://i.stack.imgur.com/T6o35.png Here is the JSX code: <DialogActions classes={{ root: this.props.classes.dialogActionsRoot }} > <Button classes={{ root: this.props ...

Comparison between SSD and HDD animation speed in web hosting environments

I am currently in search of a web hosting provider for a website I have created. The site features some performance-heavy animations, particularly due to a fullscreen slider with filter and scaling transitions. I need a provider that can ensure optimal per ...

Transferring JavaScript variables to PHP via AJAX and successfully utilizing them

A new WordPress plugin is currently in the works, involving AJAX to send a JavaScript variable as data. The goal is to retrieve and utilize this variable from the data in my PHP plugin template file. Here's a more detailed explanation: I have a file ...

The Javascript function must be executed with each page reload

Currently, I am analyzing an asp.net 2 web application that is in my care (even though I did not create it). There seems to be an issue with certain functionalities not working consistently when the page loads, particularly if using Firefox 3 within a vir ...

Paginator for Angular Material Cards

This section contains the TypeScript file for a component import { MatTableDataSource, MatPaginator } from "@angular/material"; import { FoodService } from "./food.service"; import { Food } from "./food"; @Component({ selec ...

It is impossible to change the text color to white

I am working on some JSX code which looks like the following: <div style={Object.assign({}, styles.occupyAllScreen, styles.backgroundContainer)}> <div styles={styles.overimposingText}> <h2 styles={{color: 'white !important& ...

Using PHP variables in JavaScript fetched through AJAX loading

I am currently attempting to retrieve a PHP variable from another page using AJAX in JavaScript, but it is not displaying any alerts. This is the PHP code for 'getposY': <?php include"connectdatabase.php"; $posYquery=mysql_query("Select posY ...

The clickable area on JQuery Tabs is not covering the entire surface

I'm having an issue with my JQuery tabs where the tab link does not work unless the mouse is directly over the text of the tab. It seems like the "li" element is being recognized instead of the link itself. I've searched for solutions, but most e ...

What is the method to make xsl:function return a string value containing HTML tags?

I am currently working on converting a Java function into an XSL:Function specification. The function is responsible for adding HTML tags around substrings. I have encountered some challenges in this process: while the Java code works perfectly with inline ...

AngularJS offers a single checkbox that allows users to select or

For my code, I need to implement a single checkbox. In my doc.ejs file: <tr ng-repeat="folder_l in folderlist | orderBy:created_date" > <td> <div class="permit"> <input class="chkbtn move_check" type="checkbox" id=" ...

Unable to retrieve JSON data from php script, but able to successfully retrieve it from file.json

This is the function of my PHP testing script: $json = array ( "age" => 5, "name" => "Lee", ); $json = json_encode($json); echo $json; The JSON data is successfully printed out. When I save its content in a file named file.json and read ...

Implement the parent jQuery library within a child iframe

I have a query regarding the use of two iframes in my HTML page. I am trying to implement a single jQuery file that is loaded on the parent page. The code snippet provided below works perfectly on all browsers, except for one issue with Chrome when using t ...

What could be causing the malfunction of this JavaScript dropdown select feature in Internet Explorer?

I created a website that requires users to input their location, including the city and state. The process involves two dropdown menus: - The first dropdown menu, labeled "state," loads all USA states as selectable options when the website is loaded. This ...

I am attempting to arrange 9 images in a grid format of 3 rows by 3 columns to create a seamless

I am currently working on setting up a 3x3 grid on my website with 9 images and text underneath. The first 6 images are displaying as I intended, but when I add the last 3 images, the layout gets messed up. The first image jumps under the 3rd image on the ...

Integrating a fresh element into the carousel structure will automatically generate a new row within Angular

I'm currently working on an Angular4 application that features a carousel displaying products, their names, and prices. At the moment, there are 6 products organized into two rows of 3 each. The carousel includes buttons to navigate left or right to d ...

Compiling a list of products, but the user interface needs some adjustments

Currently, I have designed a product list menu that includes a hover dropdown feature. This means that when a user hovers over a specific menu item, the corresponding list will automatically appear. However, I am facing two issues with this setup. Firstly, ...

Error: The value for $regex must be in the form of a string

Encountering a problem with an error in the Console: { [MongoError: $regex has to be a string] name: 'MongoError', message: '$regex has to be a string', waitedMS: 0, ok: 0, errmsg: '$regex has to be a string', code ...

Stuck with the same icon even after a successful AJAX call

I am currently working on implementing a 'add to my list' function in my web app. The goal is to change the color of an icon when a user clicks on it, after sending the necessary data to the server. Despite successfully sending the data to the s ...

The clickable areas for the href and onclick functions are extremely small and positioned inaccurately on the screen

The code below is supposed to load an image of a 'close window' button that should be clickable. However, when the page loads, the clickable area is only a couple of pixels wide and a pixel or two high, positioned just below or above the center o ...