Caleb C.
Caleb C.

Reputation: 15

AJAX POST requests not being received by PHP via $_POST

I'm building part of a Firefox OS app and I'm having to use the OpenBadges API, meaning I can't use more PHP, which would make this much simpler.

The problem I'm having now is that my data sent from an AJAX POST request:

$(function(){
   $("#submitBtn").click(function(){
      var mail = $('#mail').val();
      $.ajax({
        type: 'POST',
        contentType: 'text',
        dataType: 'JSON',
        url: 'scripts/test.php',
        data: { 
            mail: mail 
        },
        success: function(data){
        var jdata = jQuery.parseJSON(data);
            alert("success! X: " + data);
        }

      });
   });
});

...isn't being received by my PHP script:

<?php
    if(isset($_POST['mail']))
    {

        $id_url = 'http://backpack.openbadges.org/displayer/convert/email';
        $mail = $_POST['mail'];
        $email = 'email='.$mail;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $id_url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $email);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec ($curl);
        curl_close ($curl);

        $user_id = json_decode($result)->userId;
        $test_var = json_decode($result);
        echo $result;
        //echo $test_var;
        //echo $user_id;

    }

//echo $mail;

?>

I keep getting a "cancelled" status on my PHP script in the Chrome dev tools Network tab, and I can see that it's sending the input in the form of "example%40gmail.com" instead of "@", but I'm not sure if that's part of the problem or not.

I've been looking and tweaking my code for about two days trying to figure out the problem, but none of the fixes that have worked for other people have worked for me.

Thanks in advance.

Upvotes: 0

Views: 316

Answers (1)

Samsquanch
Samsquanch

Reputation: 9146

You're getting "cancelled" because the link you're clicking is being executed at the same time as your ajax call, in turn canceling it. What you need to do is use preventDefault() to prevent the click from canceling your request.

$(function(){
   $("#submitBtn").click(function(e){
      e.preventDefault(); // don't cancel the request
      var mail = $('#mail').val();
      $.ajax({
        type: 'POST',
        contentType: 'text',
        dataType: 'JSON',
        url: 'scripts/test.php',
        data: { 
            mail: mail 
        },
        success: function(data){
        var jdata = jQuery.parseJSON(data);
            alert("success! X: " + data);
        }

      });
   });
});

Upvotes: 3

Related Questions