3

I'm trying to post some very simple data to a php file using jquery and then get the json response but I seem to be running into a road block somewhere. Here is my jquery:

<script>
    $(function() {
        $('.resend-verify').click( function() {
            var userid = $(this).attr('rel');            
            $.ajax({
                type: "POST",
                url: "resend_verification.php",
                contentType: "application/json; charset=utf-8",
                data: "userid=" + userid,
                dataType: "json",
                success: function(data) {
                    console.log(data.response);
                    if(data.response == 'error') {
                        $('div.alert').addClass('error');
                    }
                    $('div.alert').html(data.comment);
                }

            });

        });       
    });
</script>

and here is the php page it posts to

<?php

if ($_SERVER['REQUEST_METHOD'] == "POST") { // Check For Post
    require '../../config.php'; // Site Settings
    require '../../connectors/mysqlConnector.php';
    include $DIR['php'] . 'functions.php'; // Common Functions

    //var_dump(json_decode($_POST));
    $UserID = $_POST['userid'];

    $userSQL = "SELECT p.user_firstname,p.user_lastname,a.user_email,a.user_salt FROM web_profiles p INNER JOIN web_accounts a ON p.user_id = a.user_id WHERE p.user_id ='" . $UserID . "'";
    $userQuery = mysql_query($userSQL);
    //var_dump($userSQL);
    $user = mysql_fetch_object($userQuery);

    if (!$user->user_email) {
        $response = array('response' => 'error', 'comment' => 'User not found');
    } else {
        // Send User Verification Email
        $sendmail = new sendMail();
        $message = createUserAuthEmail($user->user_firstname, $user->user_lastname, $user->user_salt, $Site['register_email_body']);

        $content['body'] = '<br /><br />' . $message . '<br /><br />DO NOT REPLY TO THIS EMAIL! IT IS ONLY AN AUTOMATED NOTIFICATION EMAIL!';
        $sendmail->set(to, $user->user_email);
        $sendmail->set(subject, 'Action Required to Activate Membership');
        $sendmail->set(from, 'no-reply@domain.com');
        $sendmail->set(html, true);
        $sendmail->getParams($content);
        $sendmail->parseBody();
        $sendmail->setHeaders();
        if ($sendmail->send()) {
            $response = array('response' => 'success', 'comment' => 'email sent');
        } else {
            $response = array('response' => 'error', 'comment' => 'Error sending email');
        }
    }
    echo json_encode($response);
}
?>

The problem im having is that if I use contentType: "application/json; charset=utf-8" the $_POST is always empty. And when I remove contentType: "application/json; charset=utf-8" the $_POST is populated but I cant get a json response. What am I doing wrong??

tdammers
  • 20,353
  • 1
  • 39
  • 56
Tommy
  • 111
  • 1
  • 2
  • 8
  • Please try to use titles that describe the problem; it will help people with similiar issues to find your question and will make it easier for others to answer your question. I edited the question for you this time :) – Aron Rotteveel Feb 16 '11 at 20:14
  • ...and read the markup syntax help. – tdammers Feb 16 '11 at 20:18
  • Try setting `header('Content-type: application/json');` before echo in php – Mr Hyde Feb 16 '11 at 20:25
  • 1
    Plus the default contentType `application/x-www-form-urlencoded` usually works best – Mr Hyde Feb 16 '11 at 20:29
  • @Tommy..have you found out the reason? I'm experiencing the same problem – William Sham Aug 12 '11 at 18:26
  • Here is another thread with the same problem and more answers: http://stackoverflow.com/questions/8983247/post-json-data-via-ajax-sends-an-empty-array/9055343#9055343 – User Jan 29 '12 at 18:08
  • 1
    Skip contentType property. Default `application/x-www-form-urlencoded` as suggested by @MrHyde works. – user Apr 11 '14 at 09:00

3 Answers3

2

You should read through the jquery documentation once more, especially the part that covers the data and dataType parameters. data must be a key/value object, i.e.:

data: { 'userid': userid }

...and for dataType, allowed values are xml, html, text, json, and jsonp. If your PHP script sends a suitable Content-type header (e.g. header('Content-type: text/json');, then you can simply leave this parameter at the default ('Intelligent guess'). jQuery will infer the response type from its content type header. You should send the header anyway because otherwise, the server will probably assume you're sending HTML and add a HTML content type header itself, which jQuery then chokes on. It's probably also a good idea to set the internal encoding and output encoding in your PHP script, so that it understands the request correctly and sends a well-formed UTF-8 response.

For further debugging, you might want to:

  • add some logging code to your PHP, for example, dump the $_POST array and the response you're sending to a text file on the server
  • post a test request to your PHP script using something like curl or wget, and see if the response is what you expect
  • have your javascript post to a dummy script that does nothing but log the request and send an empty response; see if that works
  • step through your javascript using a script debugger (e.g. Firebug on Firefox, or the thing that's built into Chrom[e|ium]); set a breakpoint inside the success handler and see if it's hit, and if so, what the response contains
tdammers
  • 20,353
  • 1
  • 39
  • 56
1

I was fighting with the same problem for longer than I would like to admit, and then I read this from the PHP documentation:

$_POST: An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

I was trying to do it without jquery though, I built my own xmlhttprequest object. The thing that really made me realise that $_POST doesn't get populated when the query is in JSON format, or in any format other than the %encoded type, was that when I finally gave up and tried to use JQuery, I looked at the raw post data they were sending, and it wasn't JSON after all, they had just used "application/x-www-form-urlencoded" and had converted my JSON to urlencoded format before sending it over. PHP then happily populated the $_POST array with my data because it was "percent-encoded" and not JSON data at all. I thought $_POST was some magical thing that would read most content-types and magically populate, I thought it was the raw data, until I remembered $HTTP_RAW_POST_DATA, but that was depreciate and people now use "php://input" and read it by doing something like this:

$rawPOST = file_get_contents('php://input');

So one should be able to find their JSON in there, but it won't automagically be parsed into separate variables yet.

I hope I helped someone else at least, this post is 4 years old, but it says it's been viewed more than 7,000 times.

ADJenks
  • 2,973
  • 27
  • 38
0

You should try using $.post and bind it with an event if necessary. I did it for a mousemove event:

$.fn.saveArray = function() { 
    var data = {data: selectednumbers};
    $.post('clickmap.php',{
        data:JSON.stringify(data)
        //contentType: 'application/json',
    });
};
sagi
  • 1