Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

JSON/ php wont carry over data =(

I'm playing around with JQM and JSON for the first time. Iv watched a few videos online and everything seems really simply however no matter what I try I cant get it to carry over my form data. please help =(

JS

        var myURL = "http://www";
        contents = $('#form').serialize();

        $.ajax({
            url: myURL,
            dataType: 'json',
            type: 'post',
            data: contents,
            contentType: "application/json; charset=utf-8",
            async: true,
            beforeSend: function() {
                // This callback function will trigger before data is sent
                $.mobile.showPageLoadingMsg(true); // This will show ajax spinner
            },
            complete: function() {
                // This callback function will trigger on data sent/received complete
                $.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
            },

            success: function(data) {
                console.log(data);


            },
            error: function (request,error) {
                // This callback function will trigger on unsuccessful action
                alert('Network error has occurred please try again!');
            }
        });


     } else {
        alert('Please fill all nececery fields');
    }
    return false; // cancel original event to prevent form submitting
  });
  });

PHP

<?php

header('Content-type: application/json');

$json = array(
'success'       => false,
'result'        => 0

);

if(isset($_POST['name'], $_POST['email'], $_POST['memory'])){

$name       = $_POST['name'];
$email      = $_POST['email'];
$memory     = $_POST['memory'];

$json['success'] = true;
$json['result']  = $name;

}

echo json_encode($json);


?>

1 Answer

How do you know that the form variables are not being sent to the server? It looks like it should work, so if you are not getting a javascript error, and the server is not returning an error, then I would suspect that

if(isset($_POST['name'], $_POST['email'], $_POST['memory']))

is evaluating to false, which may mean the form names are different.

Normally when debugging AJAX I will dump the variables to a text file. Try a

file_put_contents("postData.txt", var_dump($_POST));

Then you can see if the variables are set. This is where I would start.