Javacadabra
Javacadabra

Reputation: 5758

Receiving response from PHP via AJAX

I am trying to send information from a form on my website to a PHP script using Ajax. However each time I try to submit the form I get no response back from the script on the server. I don't know what I'm missing and I'd appreciate any help.

This is my HTML:

<form method='post' action='<?= get_template_directory_uri() ?>/mailchimp.php'>
    <input type='text' name='email'/>
    <input type='submit' name='submit' value='Subscribe'/>
</form>

This is my PHP:

session_start();
if(isset($_POST['submit'])){
    $email = $_POST['email'];
    if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){
        // MailChimp API credentials
        $apiKey = 'xxx-xxx';
        $listID = 'xxxxxxx';

        // MailChimp API URL
        $memberID = md5(strtolower($email));
        $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
        $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;

        // member information
        $json = json_encode([
            'email_address' => $email,
            'status'        => 'subscribed'
        ]);

        // send a HTTP POST request with curl
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        echo "<h1>Success</h1>";
    }
}

This is my JQuery:

jQuery('form').submit(function (event) {

   console.log('submitting...')

    //1. Get the form Data
    var formData = {
        'email': jQuery('input[name=email]').val()
    }

    console.log("DATA FROM FORM:")
    console.log(formData);

    //2. Process the form
    jQuery.ajax({
        type: 'POST', //Type of HTTP request
        url: 'mailchimp.php', //URL to POST
        data: formData //Data from form
    }).done(function (data) {
        console.log("RESPONSE: " + data);
    });

    //3. Stop the form from submitting in usual manner
    event.preventDefault();
});

I've checked my console and I can see no errors from the JS. I see this:

submitting...
DATA FROM FORM:
Object {email: "[email protected]"}
RESPONSE: 

I've also checked my network requests and I can see that I've requested the PHP script and it's sent a 200 reponse back so I am hitting the script - however I am not seeing any Response data.

*Also please note - I know in my above PHP code I don't check the $httpCode variable. I will be implementing this. I just want to get the scripts talking to eachother first.

Upvotes: 0

Views: 147

Answers (3)

devpro
devpro

Reputation: 16117

As i mentioned and others saying you are not using index submit in your ajax request which means you have undefined index warning in your PHP code.

This is better to use php error_reporting() in your PHP code, this will help to find out errors and warnings.

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

Second, if you still want to add check in your code than you can use:

if(count($_POST) > 0)

or

if(isset($_POST['email']) && !empty($_POST['email']))

In last, you want this response from CURL request? echo "<h1>Success</h1>"; It means you always get the success message either curl execute or not.

Upvotes: 2

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

That happen because your condition :

if(isset($_POST['submit'])){

Will never reach since you don't sent the submit parameter in your POST request you send just the email.

So remove the condition or replace it by isset($_POST['email']), or also you could add the submit parameter to your formData.

To make sure that the request sent to the right route try to comment all the code and add an echo (e.g echo "<h1>Test</h1>";) and check if it will be logged.

Hope this helps.

Upvotes: 7

Razib Al Mamun
Razib Al Mamun

Reputation: 2713

Try this in your php script :

if(isset($_POST['email'])){

}

not bellow

if(isset($_POST['submit'])){

}

Upvotes: 0

Related Questions