简体   繁体   中英

sent javascript variable to php and it prints out “Array”

I sent a JavaScript variable containing the innerHTML "Basic" to PHP with Ajax and sent an email with the variable and it returned "Array" as opposed to "Basic". I am confused.

HTML:

<label class="plan-name">Plan name: <b id="somii-plan">Basic</b></label>

JavaScript/AJAX:

var somiiPlan = document.getElementById('somii-plan').innerHTML;
var request = $.ajax({
     type: "POST",
     url: "somii-pay.php",
     dataType: "json",
     data: {
        "somiiPlan" : somiiPlan,
        "email" : email,
     }
  });

PHP:

$somiiPlan = ['somiiPlan'];
$email = $_POST['email'];

$email_to = "******";
$email_subject = "Somii Test Charge";
$email_message = "Your plan is: " . $somiiPlan;
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email_to."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

Your JS looks fine as dataType is used to set what type of response will be ,not request.

Your PHP has problem

$somiiPlan = ['somiiPlan'];

will be

$somiiPlan = $_POST['somiiPlan'];

Here you were creating an array on $somiiPlan , not getting the post param so why its returning array.

Also note as you are not sending any response back and you are not handling the response in JS,so it is not required to set any dataType. And if you are sending any response make sure you send it on JSON encoded form.

Remove this:

dataType: "json",

that's what giving you the array.

JSON encodes things into an array

So remove the dataType line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM