1

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 ?

2
  • data:{mydata: Scommand}, and look at $_POST['mydata'] Commented Jan 27, 2012 at 7:06
  • It's a paste mistake :) Commande is composed by commande.type, commande.obj & command.header... @Cheery it didn't works ... Commented Jan 27, 2012 at 7:24

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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';
    }
});

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.