简体   繁体   中英

POST a javascript objet to a PHP file

I try to post an JS object to PHP, but the PHP says nothing.. It looks like it don't recognize the POST...

Here is the JS :

$('.send').click(function() {
    var Scommand = JSON.stringify(command);// Command is my JS obj

    if (commande.type) {
        $.ajax({
            url:'test.php',
            context:$(this),
            type:'POST',
            data:Scommande,
            success : function(data){
                commande = {};
                window.location='test.php';
            }
        });//End Ajax
    }
    else {'PLz specify a type');}
});

And my PHP :

<?php
echo $_POST['type'];
?>

It returns : Notice: Undefined index: type in /Applications/MAMP/htdocs/BackOfficeDavid/test.php on line 2

Like nothing go throw the POST ... Any clue ?

Disable/remove window.location='test.php'; .

What might be happening is that the success callback is called, redirecting you to the test.php after everything is actually done. This would be a plain move to test.php , by GET , so there will be no parameters in $_POST .


Actually, better yet, replace window.location='test.php'; with alert(data) , so you'll see what is returned. Otherwise it will seem like nothing happened since the ajax just completes successfully and silently in the background.

You probably mean

data:'type=' + encodeURIComponent(Scommande),

instead of

data:Scommande,

This will URL-encode the Scommande variable and assign its value to the type POST variable.

Alternatively, you can rely on jQuery to do that for you by using

data: {'type': Scommande},

(PS. Not sure if the variable is meant to be named Scommand or Scommande . You probably have a typo somewhere)

The problem is that you're converting the command to a string. The data on the ajax call has to be a JSON object, not a string. What you can do is pass the command variable directly:

var command = { type: "whatever" };

$.ajax({
    url:'test.php',
    context:$(this),
    type:'POST',
    data: command,
    success: function(data){
       command = {};
       window.location='test.php';
    }
});

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