search
HomeBackend DevelopmentPHP Tutorialjavascript - jquery's $.ajax() submits incorrect data to php's post

<code>$('#form1').submit(function(){
        
        $.ajax({ 
            url:'login.php?act=login',
            data:$('#form1').serialize(),
            type:'POST',
            dataType:'text',
            beforeSend:function(){
                }
                if($('#password').val()==''){
                    alert('密碼不能為空');
                    return false;
                }else{
                    var p = $('#password').val();
                    alert(p);
                    $('#password').val(hex_md5(p));
                    alert($('#password').val());
                }
            },
            success:function(msg){
                ......
                };
            }
        });
        return false;
    });</code>

That’s right, my purpose is to perform md5 calculation on the password before submitting it to achieve the function of encrypting and transmitting the password.

But the actual effect is that when my password value is 123, alert($('#password').val()) prints out correctly 202cb962ac59075b964b07152d234b70, but after posting to the background php, it is still 123.

I feel like data:$('#form1').serialize() has already taken the value before beforeSend, so the old value is still passed later.

After testing, if I take out the md5 encryption part and put it before $.ajax() for operation, there will be no problem. It’s just inconvenient to use like this. Is there any way to make serialize() execute after beforeSend?

Supplement:
After using the method provided by @lisfan, the submission is normal

<code>$('#form1').submit(function(){
        
        $.ajax({ 
            url:'login.php?act=login',
            **data:null,**
            type:'POST',
            dataType:'text',
            beforeSend:function(){
                }
                if($('#password').val()==''){
                    alert('密碼不能為空');
                    return false;
                }else{
                    var p = $('#password').val();
                    alert(p);
                    $('#password').val(hex_md5(p));
                    alert($('#password').val());
                    **this.data=$('#form1').serialize();**
                }
            },
            success:function(msg){
                ......
                };
            }
        });
        return false;
    });</code>

But neither $_REQUEST nor $_POST in the background php can receive data. As shown below:
javascript - jquery's $.ajax() submits incorrect data to php's post

The following is the post data seen by firebug. The above is the data of php printing $_REQUEST, $_POST and php://input respectively. You can see that the original data is seen in file_get_contents("php://input") Data, but why is it not encapsulated in $_POST?

.

Reply content:

<code>$('#form1').submit(function(){
        
        $.ajax({ 
            url:'login.php?act=login',
            data:$('#form1').serialize(),
            type:'POST',
            dataType:'text',
            beforeSend:function(){
                }
                if($('#password').val()==''){
                    alert('密碼不能為空');
                    return false;
                }else{
                    var p = $('#password').val();
                    alert(p);
                    $('#password').val(hex_md5(p));
                    alert($('#password').val());
                }
            },
            success:function(msg){
                ......
                };
            }
        });
        return false;
    });</code>

That’s right, my purpose is to perform md5 calculation on the password before submitting it to achieve the function of encrypting and transmitting the password.

But the actual effect is that when my password value is 123, alert($('#password').val()) prints out correctly 202cb962ac59075b964b07152d234b70, but after posting to the background php, it is still 123.

I feel like data:$('#form1').serialize() has already taken the value before beforeSend, so the old value is still passed later.

After testing, if I take out the md5 encryption part and put it before $.ajax() for operation, there will be no problem. It’s just inconvenient to use like this. Is there any way to make serialize() execute after beforeSend?

Supplement:
After using the method provided by @lisfan, the submission is normal

<code>$('#form1').submit(function(){
        
        $.ajax({ 
            url:'login.php?act=login',
            **data:null,**
            type:'POST',
            dataType:'text',
            beforeSend:function(){
                }
                if($('#password').val()==''){
                    alert('密碼不能為空');
                    return false;
                }else{
                    var p = $('#password').val();
                    alert(p);
                    $('#password').val(hex_md5(p));
                    alert($('#password').val());
                    **this.data=$('#form1').serialize();**
                }
            },
            success:function(msg){
                ......
                };
            }
        });
        return false;
    });</code>

But neither $_REQUEST nor $_POST in the background php can receive data. As shown below:
javascript - jquery's $.ajax() submits incorrect data to php's post

The following is the post data seen by firebug. The above is the data of php printing $_REQUEST, $_POST and php://input respectively. You can see that the original data is seen in file_get_contents("php://input") Data, but why is it not encapsulated in $_POST?

.

Without modifying the original structure of the question, try modifying it as follows and look at the position of the asterisk *

<code>$('#form1').submit(function(){
        
        $.ajax({ 
            url:'login.php?act=login',
            **data:null,**
            type:'POST',
            dataType:'text',
            beforeSend:function(){
                }
                if($('#password').val()==''){
                    alert('密碼不能為空');
                    return false;
                }else{
                    var p = $('#password').val();
                    alert(p);
                    $('#password').val(hex_md5(p));
                    alert($('#password').val());
                    **this.data=$('#form1').serialize();**
                }
            },
            success:function(msg){
                ......
                };
            }
        });
        return false;
    });</code>

You can process the password before sending the $.AJAX() request. That is to process the content of the beforeSend function first, and then send the request, so that the data of $('#form1').serialize() is correct

This shows that the function $('#form1').serialize() is called before beforeSend.

It is recommended that when you enter the password in the verification function, if the verification is passed, directly encrypt it and assign it to a hidden field in the form

$('#form1').submit(function() {
  if ($('#password').val() == '') {
    alert('密碼不能為空');
    return false;
  }
  var p = $('#password').val();
  alert(p);
  $('#password').val(hex_md5(p));
  alert($('#password').val());


  $.post('login.php?act=login',
    $(this).serialize(),
    function(msg) {
      console.log(msg);
    }
  );
  return false;
});

Take out the judgment and put ajax behind the password encryption.

This is because when executing $.ajax, the js engine will create a literal object. When the object is created, the value of data is stored as the return value of $('#form1').serialize() at that time, also That’s 123.

You can see the following example:
var c=1;
var a={

<code>b:c,
d : function(){
    c=2
}</code>
};

console.log(a.b);// 1
a.d();//c=2
console.log(a.b);// 1
This can be explained The above question is gone.
The possible solution is to move the md5 encryption before creating the literal object.

First of all, since md5 is required, why do we need to assign it to the input of password? Is there no security risk? Secondly, the beforeSend function is called before sending the request, not before the Ajax method. When you call the ajax method, you have already taken out the form data and set it into the parameters of the function. How can the form value modified later be automatically updated? When it comes to ajax data, it is completely whimsical. Just put the password md5 operation before calling the Ajax method

Prepare the encrypted password string before the ajax method

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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor