1

I have the following code:

  var result = confirm("You want to Subscribe to our Newsletter?");
  var emailAddress = $("#subscribeEmail").val();

  if (result == true) {

    $.ajax({
      type: 'POST',
      url: '/php/subscribeNewsletter.php',
      data: '{"email": "' + emailAddress + '"}',
      complete: function(r){
    alert(r.responseText);
    }

    });


  }

I believe the problem is to do with: data: '{"email": "' + emailAddress + '"}',

I am receiving an empty $_POST array on the server side of things.

1
  • try with this data: JSON.stringify({email: emailAddress}), Commented Jul 1, 2014 at 10:03

6 Answers 6

2

Pass an object literal, not a string:

data: {email: emailAddress },

jQuery will transform the object into the URL encoded key/value pairs, which will be picked up in the $_POST array on the PHP side.

Your current code is actually sending a JSON string as the raw POST data. jQuery is seeing the data type is a string, and so it doesn't do any processing, so you'd have to access the raw POST data on the PHP side and do a JSON decode to get it.

Sign up to request clarification or add additional context in comments.

Comments

1

yes problem is: data: '{"email": "' + emailAddress + '"}', it should be object:

...
data: {"email": emailAddress},
...

Comments

1

provide the data attribute in the ajax call as a json object instead of string.

like

data: {"email": emailAddress },

Comments

0

You can use like below

$.get('/Presentation/AjaxData/History.aspx', { itemID: itemid }, function (data) {
        $('.history-listing-tabs>.tab-item').html(data);
});

Comments

0

Try this format

data: {email: emailAddress}

Comments

0

Better pass data to a variable and use it while sending,

 var temp = 'email:' + emailAddress;
 ...
 data: temp;
 .....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.