0

I'm trying to post a segment to mail chimp accounts via AJAX. If the call is successful, I want to redirect to a URL. After much testing, the calls are successful every time, but I can't get a redirect...it's as if the code runs and then skips past the if "result = success", and goes right to my else statement which is just an alert. When I view the data being returned I get "nullsuccess". I've even tried if result = "nullsuccess" and it still goes right for the else statement.

$("#mc-embedded-subscribe-form").submit(function(e) {   
    var url = $(this).prop('action'); // the script where you handle the form input.
        $.ajax({
            type: "POST",
            url: "update-member.php",
            data: $("#mc-embedded-subscribe-form").serialize(), // serializes the form's elements.
            dataType: "text",
            success: function(data){
                if(data.result == 'success'){
                    window.location.href = 'https://google.com';
                }else{
                    alert("ERROR-ONLY IT STILL SUBMITS DATA!");
                }
            }
        });        
    e.preventDefault(); // avoid to execute the actual submit of the form.
});

Above for dataType - I've used "text" because if I use "json" or "jsonp", it completely ignores the success function, both if and else statements. Funny thing is all three data types will still post the data successfully.

And here is the PHP(update-member.php)

$apikey = 'myAPIKEYHERE';
            $auth = base64_encode( 'user:'.$apikey );    
            $data = array(
                'apikey'        => $apikey,
                'email_address' => $_POST['email_address'],
                'status'        => 'subscribed',
                'merge_fields'  => array(

                )                   
            );

            $json_data = json_encode($data);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'MYMAILCHIMPURL');
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Authorization: Basic '.$auth));
            curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);  

            echo json_encode($response_array);                                                                                                                

            $result = curl_exec($ch);
            $message = curl_errno($ch) === CURLE_OK ? 'success' : 'failure';
            echo $message; //echos nullsuccess

I feel like I'm not returning something right from update-member.php, or I'm not gathering it properly in my ajax success function.

Community
  • 1
  • 1
Ryan Ryan
  • 3
  • 4
  • 1
    remove echo from json_ecode($response_array) – Ahmed Sunny May 10 '19 at 09:02
  • check response in your network tab, i think you get more than success – Ahmed Sunny May 10 '19 at 09:03
  • As @AhmedSunny pointed out, your PHP is `echo`ing 2 things - `echo json_encode($response_array);` and later `echo $message;`. So you'll get 2 strings concatenated, which explains `nullsuccess`. – Don't Panic May 10 '19 at 10:36
  • Ok so I have commented out everything else being echo'd except $message...which returns success. But what does my success function in the ajax script supposed to look like? It's still skipping by the if success and going to the else alert. – Ryan Ryan May 12 '19 at 02:45
  • @RyanRyan I added an answer. – Don't Panic May 12 '19 at 10:16

2 Answers2

0

That is because you might have not set result = success. By default it is already in success function. You have to set as below in the server side.

$data['result'] = 'success';

and in ajax you'll have to set the dataType as 'json'

$("#mc-embedded-subscribe-form").submit(function(e) {   
    var url = $(this).prop('action'); // the script where you handle the form input.
        $.ajax({
            type: "POST",
            url: "update-member.php",
            data: $("#mc-embedded-subscribe-form").serialize(), // serializes the form's elements.
            dataType: "json", //CHANGED
            success: function(data){
                if(data.result == 'success'){
                    window.location.href = 'https://google.com';
                }else{
                    alert("ERROR-ONLY IT STILL SUBMITS DATA!");
                }
            }
        });        
    e.preventDefault(); // avoid to execute the actual submit of the form.
});
Jeeva
  • 566
  • 9
  • 18
0

As discussed in the comments, your PHP is echoing 2 things:

echo json_encode($response_array);
// ...
echo $message;

So that script returns 2 strings, concatenated - which explains the strange looking nullsuccess you are seeing. Get rid of the first echo, so that you are only returning your single, plain text status word.

The next problem is in your Javascript. You have specified that your AJAX call will return some text:

dataType: "text",

And in fact it does - a plain text success, or failure status message. But when it comes to using that response, your code is treating it like JSON:

if(data.result == 'success'){

data is your plain text response/status message, it has no .result property. It is just text, so change that to:

if(data === 'success'){

Update

Here's a simplified, working version of your code. I set this up locally and verified it works. The only things I have done are what I describe above - to make sure dataType matches what the PHP returns, and to make sure the JS treats it that way when it gets it. In this case it is text all the way.

Copy this code and try it. Enter "a@a.com" in your email field to test the success response, and anything else to test the failure.

Javascript

$("#mc-embedded-subscribe-form").submit(function(e) {   
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "update-member.php",
        data: $("#mc-embedded-subscribe-form").serialize(),
        dataType: "text",  // <-- WE EXPECT TO GET TEXT BACK
        success: function(data) {
            // Check what your PHP returns, make sure no newlines
            console.log(data);
            if (data === 'success') {  // <-- TREAT WHAT WE GOT AS TEXT
                window.location.href = 'https://google.com';
            } else {
                alert("Error");
            }
        }
    });        
});

PHP

<?php
// The problems you are having are unrelated to the Mailchimp processing,
// so let's simplify it to get the JS side working.  Make sure you have 
// no blank lines before or after your opening/closing PHP tags, as 
// they will show up in the output, and your JS would then see something
// like "\nsuccess" for example.  Also make sure nothing else in your PHP
// generates any output.
// WE RETURN TEXT
echo ($_POST['email_address'] === 'a@a.com') ? 'success' : 'failure';
?>

If you try this and it does not work, you have another problem somewhere. Open up your browser's dev tools, and check the console. Look at the network requests and view the POST.

To address some of your comments:

  • You are over-complicating things by tweaking random unrelated parts of the problem. In this particular problem, there are just a few remaining parts you need to align (you have the other parts working already):

    1) If you tell your JS that your PHP is going to return text, it must return text.

    2) If you tell your JS that your PHP is going to return text, your JS must then treat what your PHP returns as text.

    That's it. There is really nothing more to it.

  • GET vs POST: convention and standards are to use GET to retrieve and view data, and POST to change data. You are subscribing an email address - that's a change, and you should use POST.

    GET or POST will have no, none, zero effect on what your PHP returns, whether it runs OK, or what dataType you should use. They are unrelated pieces of the puzzle (though that does not mean it does not matter what you use).

Don't Panic
  • 9,803
  • 5
  • 25
  • 44
  • I tried this and the entire success function doesn't run...if I change the data type back to text, I get the alert. The only way I can get the success function to run at all is if the data type is set to text...I've tried json and jsonp and I get nothing...however keep in mind the script is successful in updating the record. :( – Ryan Ryan May 13 '19 at 07:41
  • @RyanRyan `change the data type back to text` - huh? Your code already has it as text. It should be text. I did not suggest changing that. I'm not sure now what you've done and where you are. Double check what I suggested above and let me know. – Don't Panic May 13 '19 at 08:17
  • Also, as I describe in my answer, the dataType specifies what your JS should expect back from your PHP. It has no bearing on whether or not the PHP will work - so yes, no matter what you put, your PHP will run fine. – Don't Panic May 13 '19 at 08:19
  • @RyanRyan Does it make sense? You have several options for `dataType` and how to use `data`, but they need to match up. If you keep `dataType` as `text`, you need to use `(data === 'success')`, that's all. Have you tried that? If you switch `dataType` to `json`, you'll need to change your PHP to return JSON, as well as update the AJAX success function to test your new JSON response, for example something like what you originally had (but your PHP needs to return this exact JSON format/message): `(data.result == 'success')`. – Don't Panic May 13 '19 at 12:39
  • If I change it to GET, and change datatype to "json" everything works. If I try to use POST with dataType json, I get nothing, not even the else alert statement. I believe the issue is I'm looking for a success statement on a POST, while I'm actually sort of running a GET statement. If I check for the status value as subscribed while dataType is text, it works as it returns "subscribed" as a string. My PHP file is returning this: $json = json_decode($result); echo $json->{'status'}; If (status == "subscribed"); // works – Ryan Ryan May 14 '19 at 04:40
  • @RyanRyan I have updated my answer, including **working** code. – Don't Panic May 14 '19 at 07:56
  • In the php file I'm returning 'status' which returns 'subscribed'. So this is working: if (data === 'subscribed') { window.location.href = 'https://google.com'; } – Ryan Ryan May 16 '19 at 01:12
  • @RyanRyan Great - that's what I said first time around, right? :-) If this or any other answer helped, [please accept and upvote](https://stackoverflow.com/help/someone-answers). – Don't Panic May 16 '19 at 08:18
  • Kind of, I was looking for success before but turns out it should have been 'subscribed'. Either way I'm getting proper results returned thanks to you! – Ryan Ryan May 16 '19 at 18:56
  • @RyanRyan Your original code in your question is echoing "success" ... ? In any case, glad you have it working. – Don't Panic May 16 '19 at 18:58