views:

23

answers:

2

I have a PHP script that I'm calling with the .post() function in jQuery. If everything goes well, it outputs "WIN", otherwise it outputs whatever database errors or whatever else it gets.

$.post("myscript.php", {key: "value"}, function(data) {
   if(data=="WIN") {
      // the stuff that I want it to do that it won't do
   } else {
      alert(data);
   }
});

When it runs however, I get "WIN" in a JS alert, and the stuff that I want it to do doesn't happen. Since "WIN" shows up in the alert, the PHP script is clearly outputting what I had expected. I had even made sure to set the Content-Type of the PHP script to text/plain, so why doesn't data=="WIN". Why does my WIN FAIL?

+1  A: 

Have you checked for whitespace? Any whitespace before or after echo "WIN" will affect the output, also, check for whitespace before and after your <?php tags.

Kristoffer S Hansen
Hmm good point. I think I've gotten rid of all the whitespace before the "WIN", but my IDE seems to be adding a newline at the end of the file every time I save. Maybe I should filter out the whitespace in javascript.
DLH
`data.replace(/^\s+|\s+$/g, '');` trimmed things up real good.
DLH
Oh nevermind, I just realized jQuery had a `.trim()` function. I'll use that.
DLH
You could also just avoid closing your php files with `?>` leave it open, works fine ^^
Kristoffer S Hansen
A: 

You are most likely trying to access the returned data from 'data' directly. Try

 alert(data.d);

I think that you will find that the returned data is in a property. If I remember correctly, that property's name is 'd'. Use the FireFox plugin FireBug to view the returned data. It is very helpful for AJAX debugging.

Good Luck!

Nick
If the returned data is plain text, then `data` should be the exact output of the file from what I understand. I think the whole properties thing mostly applies to JSON data.
DLH