简体   繁体   中英

jQuery AJAX Post alert() not being called

The code below is not working. An alert should show but it does not. My HTML form button has the attribute onclick="doPost()" which is the function below:

function doPost() {
    if ( allFieldsValid() ) {
        var data1 = $( '#data1' ).val();
        var data2 = $( '#data2' ).val();
        var data3 = $( '#data3' ).val();
        var data4 = $( '#data4' ).val();

        var data5 = localStorage.getItem( 'data5' );
        var data6 = localStorage.getItem( 'data6' );

        var post_data = { d1: data1, d2: data2, d3: data3, d4: data4, d5: data5, d6: data6 };

        //console.log( post_data ) always displays the data with no nulls.

        $( '#myForm' ).submit( function(e) ) {
            $.ajax({
                type: 'post',
                url: 'http://localhost/myphpfilelocation.php',
                data: post_data,
                cache: false,
                success: function( response ) {
                    alert( response );
                },
                error: function( response ) {
                    alert( response );
                }
            });
            e.preventDefault();
        }      
    } else {
        alert( 'Fields are not valid' );
    }
}

My PHP code uses echo to display the data it gets:

<?php
    $data1 = $_POST[ 'd1' ];
    $data2 = $_POST[ 'd2' ];
    $data3 = $_POST[ 'd3' ];
    $data4 = $_POST[ 'd4' ];
    $data5 = $_POST[ 'd5' ];
    $data6 = $_POST[ 'd6' ];

    echo( $data1. ' '.$data2. ' '.$data3. ' '.$data3. ' '.$data4. ' '.$data5. ' '.$data6 );
?>

The alert() in my script doesn't even show up.

All my HTML form inputs have the correct ids ( which is the ('#data1') etc. ).

You have to use JSON.stringify() method.

JSON.stringify function turns a Javascript object into JSON text and stores it in a string.

Also, contentType is the type of data you're sending, so application/json .

Please try this:

$.ajax({
        type: 'post',
        url: 'http://localhost/myphpfilelocation.php',
        data: JSON.stringify(post_data),
        contentType:'application/json',
        cache: false,
        success: function( response ) {
            alert( response );
        },
        error: function( response ) {
            alert( response );
        }
});

In your php file, you have to decode json object, using json_decode function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM