Unable to submitting the form using jquery post request like a form submit

Ashok Kumar 161 Reputation points
2024-04-24T11:36:47.15+00:00

Using Form Submit redirecting page from one page to another page and the page is redirecting successfully but the parameter value getting length 0(if array) or null(if string) based on the data passed on param.

To achieve this concept I have used the below logic.

Redirecting to page-2 from page-1:-


function redirectopage() {

    post_to_url('http://xxxxxxxxx/option.aspx', {

        data: 'dynamic'

       //option: 't'

    }, 'post', '_blank');

}

Form Submit Logic POST request:-


// Form Submit

function post_to_url(path, params, method, targetOpt) {

    var form = $(document.createElement('form'));

    $(form).attr("action", path);

    $(form).attr("method", method);

    $(form).attr("target", targetOpt);

    

    // Loop through params and append them as hidden inputs

    $.each(params, function(key, value) {

        var input = $("<input>")

            .attr("type", "hidden")

            .attr("name", key)

            .val(value);

        $(form).append(input);

    });

    // Append the form to the body and submit

    $(form).appendTo(document.body).submit();

}

Serializing the data in redirect page(page-2):-


$(document).ready(function() {

    var queryString = $('#form').serializeArray();

      console.log(queryString) //getting null or length 0

    $.each(queryString, function(i, field) {

        alert(field.name + ":" + field.value);

    });

});

Note:- I have created these two pages(using web form{with master page}) in asp.net empty website project and I have read this answer post also but I didn't understand well.

Suggest me where I did the mistake and how to achieve this.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,273 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,716 Reputation points Microsoft Vendor
    2024-04-25T02:08:02.3933333+00:00

    Hi @Ashok Kumar,

    What you need to get is the <form> tag instead of the one with id form.But this method can only get the form of the current page.

    var queryString = $('form').serializeArray();

    POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.

    You can use Request.Form Collection. The Form collection retrieves the values of form elements posted to the HTTP request body, with a form using the POST method.

    page-2:

    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: "page-2.aspx/getMessage",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert(msg.d);
                }
            });
        });      
    </script>
    
    public static string message { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.RequestType == "POST")
            {
                message = Request.Form["data"];
                
            }
        }
    }
    [WebMethod]
    public static string getMessage()
    {
        return message;
    }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,846 Reputation points
    2024-04-25T02:44:35.46+00:00

    When page posts its dynamic form to page2, the server code for page 2 needs to render the post data as a html form and add a hidden field for each posted value. so the page2 JavaScript can parse the form data.

    if page1 did a redirect rather than post, and passed all the values on the query string, then page2 JavaScript could parse the query string rather than form.

    0 comments No comments

  2. SurferOnWww 1,911 Reputation points
    2024-04-25T00:43:14.0133333+00:00

    I suggest that you use the jQuery ajax to upload a file. Shown below are sample of ASP.NET Core MVC:

    Model

    using Microsoft.AspNetCore.Http;
     
    namespace MvcCoreApp.Models
    {
        public class UploadModels
        {
            // additional info if required
            public string CustomField { get; set; }
    
            public IFormFile PostedFile { get; set; }
        }
    }
    

    View

    @model MvcCoreApp.Models.UploadModels
     
    @{
        ViewData["Title"] = "Upload";
    }
     
    <h1>Upload</h1>
     
    <hr />
    <div class="row">
      <div class="col-md-4">
        <form method="post" enctype="multipart/form-data"
            asp-controller="Upload" asp-action="Index">
          <div class="form-group">
            <div class="col-md-10">
              <p>Upload file using this form:</p>
              <input type="file" name="postedfile" />
            </div>
          </div>
          <div class="form-group">
            <div class="col-md-10">
              <input type="submit" value="Upload by Submit"
                     class="btn btn-primary" />
              <div>@ViewBag.Result</div>
            </div>
          </div>
        </form>
     
        <div class="form-group">
          <div class="col-md-10">
            <input type="button" id="ajaxUpload"
                value="Ajax Upload" class="btn btn-primary" />
            <div id="result"></div>
          </div>
        </div>
      </div>
    </div>
    
    @section Scripts {
    <script type="text/javascript">
      //<![CDATA[
      $(function () {
        $('#ajaxUpload').on('click', function (e) {
          // obtain FormData object
          var fd = new FormData(document.querySelector("form"));
     
          // additional info if required
          fd.append("CustomField", "This is some extra data");
     
          $.ajax({
            url: '/fileupload',
            method: 'post',
            data: fd,
            processData: false, // prevent jQuery to process data
            contentType: false  // prevent jQuery to set contentType
            }).done(function(response) {
              $("#result").empty;
              $("#result").text(response);
            }).fail(function( jqXHR, textStatus, errorThrown ) {
              $("#result").empty;
              $("#result").text('textStatus: ' + textStatus +
                              ', errorThrown: ' + errorThrown);
            });
        });
      });
      //]]>
    </script>
    }
    

    Controller and Action Method

    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Hosting;
    using MvcCoreApp.Models;
    using Microsoft.AspNetCore.Http;
    using System.IO;
     
    namespace MvcCoreApp.Controllers
    {
      public class UploadController : Controller
      {
        rivate readonly IWebHostEnvironment _hostingEnvironment;
     
        public UploadController(
                        IWebHostEnvironment hostingEnvironment)
        {
          _hostingEnvironment = hostingEnvironment;
        }
     
        [HttpGet("/fileupload")]
        public IActionResult Index()
        {
            return View();
        }
     
        [HttpPost("/fileupload")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Index(UploadModels model)
        {
          string result = "";
          IFormFile postedFile = model.PostedFile;
          if (postedFile != null && postedFile.Length > 0)
          {
            string filename = Path.GetFileName(postedFile.FileName);
     
            string contentRootPath = _hostingEnvironment.ContentRootPath;
            string filePath = contentRootPath + "\\" + 
                              "UploadedFiles\\" + filename;
     
            using (var stream = 
                        new FileStream(filePath, FileMode.Create))
            {
              await postedFile.CopyToAsync(stream);
            }
     
            result = filename + " (" + postedFile.ContentType + 
                     ") - " + postedFile.Length + 
                     " bytes upload complete";
          }
          else
          {
            result = "upload fail";
          }
     
          if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
          {
            return Content(result);
          }
          else
          {
            ViewBag.Result = result;
            return View();
          }
        }
      }
    }
    
    0 comments No comments