search
HomeBackend DevelopmentPHP TutorialAjax form submission and background processing simple example

This article mainly brings you a simple application based on Ajax form submission and background processing. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

First of all, let’s talk about form submission. To submit the form, you must first collect the form data (as for verification, I won’t talk about it. I’ll leave it for next time). With jquery, you can get the html. The value is still as simple as $("xxid").val() and so on, but if a form collects a lot of data, and there are many forms like this, it will definitely be troublesome to use this method, and it is easy to make mistakes in recording. Therefore, we can simply define a collection rule. For example, we can mark the data form control that is to be sent back to the server, and then retrieve the marked data together.

Let’s take the simplest stylistic input as an exampleUs Add a "datafield" attribute, and the stored value is the attribute name of the corresponding server-related class. With this mark, it will be easier to retrieve data from the front desk.

We can define a general method such as the following code


getFormData: function(formid) {    
    var data = {};

    //获取TEXT文件内容
    $("#" + formid + " input[type=text]").each(function(i, o) {
      var jo = $(o);
      if (jo.attr("datafield")) {
        var str = jo.val();
        str = str.replace(" ", "");
        if (str !== "") {          
          data[jo.attr("datafield")] = jo.val();
        }
      }
    });
    return data;
}

Here is a simple way to get all the text in the form, and Put it into a data object. I won’t go into details about how to get the values ​​of other form controls. The principles are similar.

The next step is to send the data to the server. I will directly use ajax with jquery here.


var save = function(sender) {     
      $(sender).prop("disabled", true); //禁用按钮,防止重复发送
      var data = getFormData("form1");
      var jsonobj = { jsondata: data };
      var textdata = JSON.stringify(jsonobj);
      $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "xxxxx.aspx/Save",
        dataType: "json",
        data: textdata,
        success: function(msg) {
          if (msg.d == "1") {
            document.form1.reset();
            alert("保存成功!");           
          }
          else if (msg.d == "0") {
            alert("保存失败!");
          }
        },
        complete: function(jqXHR, textStatus) {
          $(sender).prop("disabled", false); //还原按钮
        }
      });
    }

The "xxxxx.aspx/Save" here is the ajax processing page, and the other is a webmethod. We have done some work to prevent customers from moving too fast, serving too slowly, and making repeated clicks.

Such a form data collection and return to the server is completed. The JSON.stringify method of json2.js is used here to uniformly convert objects into json characters. The advantage is that you don’t have to consider the format of json to spell the json string yourself. It is simple and clean.

Then the client has collected the data, and the server should process the data. The key of the data we come from the front desk (json key) cannot all include all attributes of a certain data class. And there are many data classes, and only the server knows which class it is. So here we need to write a helper conversion class. There is another problem here. There may be many data classes. Do I have to write a method for each class? Isn’t that a pitfall? So we analyze the data format transmitted from the client to the server. It is a set of key-value pairs and does not repeat. It is equivalent to a Dictionary. There are many kinds of background classes, so at least we can Once an incoming parameter is determined, the relevant class will be passed out. Related classes? Which category it is can only be known by looking at the specific background collection method. So, let’s sort out our thoughts. Now we have a Dictionary that needs to be turned into a data class. What exactly is a data class and what are its attributes? I can’t figure it out, but the key (key) of this Dictionary can be regarded as a subset of the attribute set of this data class, and the value (value) of this Dictionary is the value of this data class attribute. A subset of toString(). That would be easier to handle. How to get the attribute set? reflection. Which of these categories are there? Regardless, generics solve it.

After talking about so much, I will post the core code


##

public static T1 UpdateObjectByDic<T1>(T1 scrobj, IDictionary<string, string> sourceobject, bool ignoreCase)
     where T1 : new()
    {
      T1 result = scrobj;
      PropertyInfo[] pifresults = typeof(T1).GetProperties();
      foreach (var dic in sourceobject)
      {
        foreach (PropertyInfo pifresult in pifresults)
        {
          if (string.Compare(dic.Key, pifresult.Name, ignoreCase) == 0)
          {
           pifresult.SetValue(result, ChangeType(dic.Value, pifresult.PropertyType), null);
            break;
          }
        }
      }
      return result;
    }

    public static Object ChangeType(object value, Type targetType)
    {
      Type convertType = targetType;
      if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
      {
        NullableConverter nullableConverter = new NullableConverter(targetType);
        convertType = nullableConverter.UnderlyingType;

      }
      return Convert.ChangeType(value, convertType);
    }

I am here to update T1 scrobj Do it together. If you add a form, pass in a new object. If you update the order, pass in the original form data. By the way, here is the ChangeType method. Others are that some attributes in the data class are nullable (int? DateTime?, etc.). The traditional Convert.ChangeType will have exceptions, so I simply changed it. ignoreCase is the attribute (the value corresponding to the datafield in the front desk) Check whether it handles upper and lower case (usually regardless of case, if you want to handle case, I believe you will be drowned by the front desk's saliva).

This completes the background data processing core, and the calling part of the code is also posted


[WebMethod(EnableSession = true)]
    public static string Save(Dictionary<string, string> jsondata)
    {
      string result = "0";
      Model.Project pro = ConvertHandle.UpdateObjectByDic< Model.Project>(jsondata,new Model.Project,true);      
      pro.CreatorID = BLL.Sys_User.GetCurUser().ID.ToString();
      pro.CreatorName = BLL.Sys_User.GetCurUser().Name;    
      prohandle.Insert(pro);
      result = "1"; 
      return result;
    }

Here is the core usage of the background specific processing method call, prohandle. Insert(pro) stores the class in the database, pro.CreatorID, pro.CreatorName are some other information about the project, which I won’t go into. Here we have a form of front-end data collection and background processing, except for the saving part, it’s all over, haha.

Finally, this article is just a simple application. Like the front-end collection I mentioned, many front-end js frameworks have already been developed, and the considerations are much more comprehensive than mine. For background processing, this is Based on my simple collection at the front desk, many third-party frameworks have complete systems, but what I am talking about here is just a simple idea. When you don’t have so many controls at the moment, can you easily follow this path? accomplish. Of course, I strongly recommend not to reinvent the wheel, but you must understand the core function and principle of the wheel.

related suggestion:


JQuery creates an AJAX form submission example for PHP_jquery

Using Vue.js in Laravel to implement Ajax form verification example

Use Session token in php to prevent repeated submission of Ajax forms

The above is the detailed content of Ajax form submission and background processing simple example. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment