3

Say, I have something like this

function submitform() {
    var data = JSON.stringify({
        "userdata": $('#user_data').val()
    })
    $('<input type="hidden" name="json"/>').val(data).appendTo('#myform');
    $("#myform").submit();
}

Now on the Server side, I've tried:

json_decode($_POST['json']);
json_decode($_POST['json'], true);
json_decode(htmlspecialchars_decode($_POST['json']), true);

All of these return NULL value when I do a var_dump on the page.

I am not submitting the form via ajax, and I do not want to use application/json to submit the form because there are other fields in the form that need to be submitted the normal form submission way.

How can I do this?? Just need to send json to php on form submission.

17
  • 1
    Under what event are you calling submitform()? What's the action attribute set to on the form element? Also note that your method of appending the user_id to the URL is really not secure in any way. Commented Jan 27, 2016 at 17:14
  • What is the method used on your form? I know, it could be obvious, but if its not filled in you will need to look inside $_GET... Commented Jan 27, 2016 at 17:14
  • method="post" on form. Commented Jan 27, 2016 at 17:15
  • Console.log data before you submit. Does it have a value? Commented Jan 27, 2016 at 17:16
  • 2
    There you go. That's magic quotes working. Do a stripslashes() and it will work. Commented Jan 27, 2016 at 17:23

1 Answer 1

2

Probably the magic quotes screw up your JSON string and PHP doesn't recognize it anymore. Use stripslashes() before you hand it over to json_decode():

$a = json_decode(stripslashes($_POST['json']));
var_dump($a);
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to check for magic quotes or will stripslashes() in order to know whether to use it or not, or will it work either way?
Is it needed to be known you think? Before doing stripslashes? Like I wouldn't want this script to get screwed up on different server with different magic quotes set.
Normally you can do a strip() safely every time. But if your string contains intentional backslashes (? does it? very unlikely), stripslashes() will remove them. Which is a mistake, of course. Also, consider base64 if you want to receive EVERYTHING without all the mess :)

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.