Storing information during the click event of the Submit Button and before the Form Submission in the View

Below is the form that gets posted from the view to the action method. When the onclick() event is triggered, it calls jquery.ajax and sends data (content of the first div) to the same action method. The order of execution is such that jquery.ajax runs first and then the form submission happens. How can I retrieve the value of pid (sent by jquery.ajax) when the form is submitted? Do I need to use something like Session for this purpose?

View:

<form id="newform" action="/ad/newad" method="post">
        <div id="divAjax">
            <p align="center" style="background: white; margin: 0cm 0cm 0pt;">Dan</p>
            <p align="center" style="background: white; margin: 0cm 0cm 0pt;">
                <b><span contenteditable="true"> CLICK TO CHANGE</span></b>
            </p>
        </div>
        <div class=" content">
            <input type="text" name="PName"/>
            <input type="text" name="SName"/>
            <input type="submit" value="Submit" id="btnSubmit" onclick="return updatePerson();" />
        </div>
    </form>
    <script>
        function updatePerson(){
            $.ajax({
                url         : "/ad/newad",
                type        : "POST",
                dataType    : "json",
                contentType : "application/json;",
                data        : "{ pid:'" + $("#divAjax").html() + "' }"       
            });
    </script>
    

Action Method:

[HttpPost]
    [ViewException]
    [UserFilter(OpUserAuthType.Admin, OpUserAuthType.Normal)]
    public ActionResult NewAd(string id, string pid, AdDetail model)
    {
        ...
    }
    

Answer №1

To improve your form functionality, consider replacing the submit button with a regular button. Since your form already submits to the same action as your ajax post, posting all of your data at once in the click handler may be more effective than just including the pid. You can utilize the success or error handler of the ajax call to perform any necessary actions after the post is completed.

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

Attempting to alter an image with a click and then revert it back to its original state

I'm currently working on a feature that toggles an image when a specific class is clicked. The code I have so far successfully switches from 'plus.png' to 'minus.png' upon clicking, but I need it to switch back to 'plus.png&ap ...

Steps for disabling a spinner directive in AngularJS for particular $http calls

This specific directive is designed to automatically toggle a loading icon on or off whenever there are $http requests happening. Here's the code snippet: angular.module('directive.loading', []) .directive('loading', [& ...

Retrieving JSON data from PHP using jQuery

I've been struggling with this issue for two whole days now, and I feel like I've hit a dead end in trying to solve it on my own. Here's the situation: I have two pages - one that contains a form with an address field that gets auto-filled ...

Fixing a Dropdown Problem in Codeigniter

I have encountered a problem with the Dropdown pop-up feature. Specifically, when I click on the "Add New" option in the Dropdown, the pop-up window fails to open. Here is the code for the Dropdown: echo form_dropdown('Birth_Certificate_Storage_id[& ...

Leveraging JQuery and JCarousel for Smart Wrapping: Harnessing the Power of WrapInner and nth Selectors to Wrap Items at

My goal is to utilize JCarousel for presenting UL elements with LI containing a total of eight images arranged in two rows of four, resembling this structure: <li> <div> [image][image][image][image] [image][image][image][image] </div& ...

What causes the toggle effect in my jQuery onclick function to alternate between on and off when the initialization is repeated multiple times?

I am facing an issue with my website where icons/buttons trigger a menu when clicked. I need to load more data by adding more buttons, so I tried re-initializing the existing buttons using a jQuery onclick function whenever the number of buttons changes. ...

Acquiring the index of a selector event within a list of dynamic elements

I am seeking guidance on how to go about solving the issue of obtaining an event index. I have a hunch that closures might play a role in the solution and would appreciate some insights. Initially, I dynamically build an HTML5 video container using an aja ...

Conceal/Vanish a Row within a Table - Utilizing jQuery

How can I use jQuery to hide a table row with a simple effect? I am looking for a fadeout effect or to hide the row slowly. Currently, my code hides it very quickly, similar to using document.getElementById('id').style.display='none&apos ...

Vertical centering not functioning as expected due to issues with margin-top and margin-bottom

I'm having trouble centering my red block in the middle of the webpage, with the footer block at the bottom and the white block between them. Oddly enough, margin-top doesn't seem to be working for me, but left and right are functioning fine. Al ...

Leveraging JQuery to extract the numerical value located between the slashes within a hyperlink

I need to extract numeric values from a link like this. For example: /produkt/114664/bergans-of-norway-airojohka-jakke-herre In this case, I want to fetch 114664. To achieve this, I have written the following jQuery code: jQuery(document).ready(functi ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Show the button's value in the textbox and update the selected button's color using JavaScript

I am having difficulty changing the background color of a selected button after displaying its value in a textbox. The code below successfully displays the button value in the textbox, but I can't figure out how to change the background color of the s ...

Error encountered in the FilterChain doFilter method due to a java.lang.NullPointerException

After adding a filter in the web.xml deployment descriptor, I am encountering a NullPointerException whenever a request is made to the server. java.lang.NullPointerException org.apache.commons.beanutils.PropertyUtilsBean.getIndexedProperty(PropertyUtilsB ...

Having trouble getting the post function to work properly in jQuery

Could someone please review the jQuery post function code snippet below? It seems to be unable to send data to a specific URL. Can anyone confirm if this code is correct? I'm struggling to identify what I might be doing wrong here. Any insights? $.p ...

Submitting multiple forms using AJAX and PHP

I am currently trying to send the form data to another page for processing, but I am not receiving any data. Below are the forms in question: The default form is the login form for requesting a username and password, with only one submit button. ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

Utilize select2 for dynamically loading an external html component

When the page is loaded, it includes another HTML page with a select element that I want to style using select2. The basic page structure looks like this: <select class="selectAddItem" id="selectAddItem" name="selectAddItem" style="width: 150px;" clas ...

Discovering, storing, and displaying JSON data in JavaScript

I am currently working on a PHP file called rows2.php that displays results from a database by showing the new id of the field in this format: {'new_id':'92'} My goal is to use JavaScript to load this data and add the new_id surrounded ...

Rearrange the sequence of numbers using JQuery when an HTML element is deleted

I'm currently working on a simple functionality where I have 5 rows, each with its own number. So initially, the rows are numbered from 5 to 1. If I remove a value like 3, the sequence should adjust to 4, 2, 1, indicating that I now have only 4 rows ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...