jQuery $ .toJSON no me deja publicar?

Tengo lo siguiente

    var storage = [], obj;
    $('form input[type=hidden]').each(function(){
        obj = {};
        obj[this.name] = this.value;
        obj["spot"] = this.className
        storage.push(obj);
    });

    storage = $.toJSON(storage);
    console.log(storage);

    $.post('storage/', storage, function(data) {
        if(data == "true") {
            //window.location.href = href;
        }else{
            alert("An error has been encountered, Blah has been notified, please try again later");
        }
    });

and in PHP I have a simple <?php print_r($_POST); ?> and it is printing Array( ) it does not seem to be posting the json encoded results.

It's driving me nuts and I have no idea what is going on lol. Any help?

PD. estoy usando http://code.google.com/p/jquery-json/ as a json encoder.

preguntado el 30 de enero de 12 a las 19:01

What are you getting back out from the console.log() you've got there? -

1 Respuestas

jQuery's ajax data option expects either an object, or a query string. You are passing is a json string, which it isn't expecting. try this instead:

$.post('storage/', {storage: storage}, function(data){...});

and in php, access the value with $_POST["storage"]

Editar: Además, data == "true" debiera ser /true/i.test(data) just in-case your php returns any hidden characters such as spaces tabs or returns.

Respondido el 30 de enero de 12 a las 23:01

he could also use $json = json_decode(file_get_contents("php://input")); turn the posted json into a variable thats usable, without using POST variables - Rahly

That's true. Are there any downsides to that? How does jquery know to send it as the request body instead of a post/get var? I can't find anything in the documentation about it which is why I stay away from it. - Kevin B

It would just become the raw request body, which is perfectly valid, and useful in cases where you want a cross-language easy way of providing a simple service (any language/dialect just writes json to your app). Setting a Content-Type header is advisable in that case though. - Wrikken

The only downside would be if you can't control and there is a limit to the post body. Either via apaches LimitPostBody, or php's post_max_size. jQuery knows because you are passing it via "string" and not as an object. It would also be good to use processData, as well as what Wrikken said. Personally, I use .ajax over .post/.get because you have much more control over what happens. $ajax({ type: "POST", url: url, contentType: "application/json", data: JSON.stringify(data), processData: false, success: function(){}, failure: function(){} }); - Rahly

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.