tags:

views:

46

answers:

2

Here is what I have going on in my AJAX:

$('#submit-button').click(function(){
    var twit = $('input#twittername').val();
    var email = $('input#email').val();
    if((email == "" || email == "[email protected]") && (twit == "" || twit == "@twittername")){
        $('p#empty-error').fadeIn();

    return false;
    }

    var datastring = 'email=' + email + '&twit=' + twit;

    if(email != "[email protected]"){
        $.ajax({
            type: 'POST',
            url: '/path/to/script1.php',
            data: datastring,
            success: function(){
                $('#signup').fadeOut('slow',function(){
                    $('#email-response').fadeIn('slow');
                });
            }
        });

        return false;
    }

    if(twit != "@twittername"){     
        $.ajax({
            type: 'POST',
            url: '/path/to/script2.php',
            data: datastring,
            success: function(){
                $('#signup').fadeOut('slow', function(){
                    $('#email-response').fadeIn('slow');
                });
            }       
        });
    }

    return false;       
});

AJAX is returning the success function. And I can navigate directly to /path/to/script2.php, and it will add an empty record to my database. But for some reason, the PHP is not actually receiving and inserting the AJAX variable.

This was working before, and I'm unsure at what point it stopped. It's just a bit strange that it is two scripts that were both working, and now neither are.

Script one was written by me, and it inserts a blank record if I navigate straight to it:

<?php

$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pw';

$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con) {
    die('Could not connect: ' . mysql_error());
}

$dbname = 'databasename';
mysql_select_db($dbname, $con);

$sql = "INSERT IGNORE INTO databasename (column) VALUES ('$_POST['twit']')";

if (!mysql_query($sql)){
    die('Error: ' . mysql_error());
}

echo 'record added successfully';

mysql_close($con);

Script two is modified from MailChimp, and this does nothing if I navigate straight to it, which is expected:

function storeAddress(){

    // Validation
    if(!$_POST['email']){ return "No email address provided"; } 

    if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_POST['email'])) {
        return "Email address is invalid"; 
    }

    require_once('MCAPI.class.php');
    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI('66a7f17d87e96e439f7a2837e2963180-us1');

    // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
    $list_id = "b1ebe7c0ba";

    if($api->listSubscribe($list_id, $_POST['email'], '') === true) {
        // It worked!   
        return 'Success! Check your email to confirm sign up.';
    }else{
        // An error ocurred, return error message   
        return 'Error: ' . $api->errorMessage;
    }

}

// If being called via ajax, autorun the function
if($_POST['email']){ echo storeAddress(); }
?>

Any ideas where I'm going wrong?

Also: I can successfully alert the datastring, if that's any help.

+1  A: 

Not sure if it is just a typo here, but this line won't work:

$sql = "INSERT IGNORE INTO databasename (column) VALUES ('$_POST['twit']')";

It should be (look at the quotes at the POST variale):

$sql = "INSERT IGNORE INTO databasename (column) VALUES ('".$_POST['twit']."')";

Besides that, you should never put a POST Variable directly into the SQL statement due to security reasons (have a look at SQL injections).

TheCandyMan666
Doh, should this serve me better: $message = mysql_real_escape_string($_POST['twit']); $sql = "INSERT IGNORE INTO twitter (user) VALUES ($message)";
Joshua Cody
Eh, that's still not working for me. I feel like something must be wrong in $_POST['twit']
Joshua Cody
Try putting quotes around $message too, because i think you are passing a string with that variable.If that doesn't work, what value is inside the Post variable? Just print it out and see if it is even passed to php.
TheCandyMan666
Yeah, caught that error and changed it. Given I'm submitting with AJAX, how would I print out the PHP variable?
Joshua Cody
(I'm thinking this must be the error since I can add an empty record by accessing the URL directly, but can you see anywhere my post variable could be going wrong?)
Joshua Cody
I don't know the framework you are using for the Ajax call so i can't really tell if everything is fine there.Try using firebug and have a look at the response, if you just do a print/echo, the variable out it should also be shown there. Or write the POST to a file and have a look whats inside:$fp = fopen('/path/to/file/log.txt', 'w');fwrite($fp, $_POST['twit']);fclose($fp);If you are using JQuery have a look here: http://api.jquery.com/jQuery.ajax/Then you need to pass "data" as a JSON string and not like you do. Then i think it should be:
TheCandyMan666
var datastring = "{email: '"+email+"', twit: '"+twit+"'}";
TheCandyMan666
Or as a json object:var data = {email: email, twit: twit};
TheCandyMan666
Joshua Cody
Ok, but if its empty i would try passing the data as JSON. I haven't workd with JQuery, but in all other frameworks i worked with this is the most common way to pass the parameters.
TheCandyMan666
+1  A: 

Needed to delete the top "return false." A fun way to spend 4 hours.

Joshua Cody