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

Sending variable with AJAX/PHP

I've searched the web for an answer to this several times over but can't seem to find a working solution.

I've excluded a lot of the code for readability & sake of minimalism. The project I'm working on is supposed to open a modal window & load in content from the database.

My problem is that PHP won't pick up the variable for the life of me. Literally everything else is working with the exception of this variable pulling through. My code pulls the div id name and matches it in the php file. If they match, the information is pulled from the database. As of right now, my variable is empty... so no match. If I hardcode the variable, it works perfectly - but that isn't helpful in this situation.

I've tried GET, POST, I've tried adding it as a button instead of a div.

Any ideas would be greatly appreciated.

<div id="despair" class="cartoon" onclick="openEp(this.id)">
<p>content here</p>
</div>

<div id="friday" class="cartoon" onclick="openEp(this.id)">
<p>different content here</p>
</div>
function openEp(clikId) {
episode_name = clikId;

$.ajax({
     type: 'POST',
     url: 'cartoons.php',
     data: ({episode_name: episode_name}),
     success: function(data) {
      console.log('sent ' + episode_name);
     }
    });
}

and for my cartoons.php file

<?php include 'connect.php';

$conn = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

$episode_name = $_POST["episode_name"];
echo $_POST['episode_name'];

?>

1 Answer

Patrik Horvรกth
Patrik Horvรกth
11,110 Points

your problem is simple $_POST["episode_name"] doesnt not exist and thts all why ? take closer look on your code

if episode_name = 10

{episode_name : episode_name} => { 10 : 10 }

you should use = { "episode_name" : episode_name }

<?=
// simple check 
if (isset($_POST["episode_name"]) && !empty($_POST["episode_name"])) {
echo "yaaaay my epicode_name exist";
} else {
 echo "nach i made mistake T-T";
}

PS next time use $.post its easyer

I didn't include isset in my sample code because I knew the variable wasn't being set. That's my problem. :( I can't figure out why PHP isn't catching it.