简体   繁体   中英

Store on PHP variables sent by Ajax

I am creating a DDBB Insert trough $.ajax:

$(document).on('click','.submitMessage', function(){
    content=$('textarea').val();
    img=$('#messageImg').val();
    stdMsg=$('.ms_stdMsg').val();
    prefix=$('.prefix').val();
    phone=$('.cuadroTelefono').val();

    $.ajax({
        url: "../actions/newMessage.php",
        type: "POST", 
        data:{ms_content:content, ms_img:img,ms_prefix:prefix,ms_phone:phone},
        contentType: false, 
        cache: false,  
        processData:false, 
        success: function(data) 
        {   
            alert("Enviado");
        }
    });
});

And this is the way I receive code on newMessage.php :

$ms_content = $_POST['ms_content'];
$ms_img = $_POST['ms_img'];
$ms_prefix = $_POST['ms_prefix'];
$ms_phone = $_POST['ms_phone'];

Console gives an error

Notice: Undefined index: ms_content in C:...\\newMessage.php on line 9

one for each variable passed (I have ommited entire URL)

As the posted information is an object, I guess I must decode it someway on PHP, but trying:

$ms_content = json_decode($_POST['ms_content']);

...has neither workd

You need to specify the data that you are sending with contentType parameter. For more references

    $(document).on('click','.submitMessage', function(){
        content=$('textarea').val();
        img=$('#messageImg').val();
        stdMsg=$('.ms_stdMsg').val();
        prefix=$('.prefix').val();
        phone=$('.cuadroTelefono').val();

        $.ajax({
            url: "../actions/newMessage.php",
            type: "POST", 
            data:{ms_content:content, ms_img:img,ms_prefix:prefix,ms_phone:phone},
            cache: false,              
            success: function(data) 
            {   
                alert("Enviado");
            }
        });
    });

Please remove processData:false, contentType: false and then try.

You can use this $_REQUEST instead of $_POST in your php file.

$ms_content = $_REQUEST['ms_content'];

Instead of

$ms_content = $_POST['ms_content'];

Second Maybe due to url path

try giving full url path.

Third

Provide a contentType.

I think you have to access the $_GET parameters because jquery documentation says:

data Type: PlainObject or String or Array Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

http://api.jquery.com/jquery.ajax/

So you will get your data with

$ms_img = $_GET['ms_img'];

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