简体   繁体   中英

How to correctly receive a JSON response from AJAX (Javascript to PHP)

My script.php file sends a few variables (extracted from a HTML form) to my email.php file.

This file then saves all such variables to a MYSQL database, and in return also collects an "Order ID Number" (collected from mysql_insert_id), shown below:

$order_id = mysql_insert_id();

The $order_id is then passed back to script.php, which submits the product details to Paypal. Currently, I wish the Paypal's item name to read "Order ID: #$order_id".

However, I can't seem to send all the variables over to script.php, and then get the order ID back correctly.

I often receive a "Cannot read property 'order_id' of undefined" error in Google Chrome console, however now I'm triggering this piece of code from the JQuery 1.10.1 library (observed in Google Chrome console also)

// Uppercase the type
        s.type = s.type.toUpperCase();

Which then results in the following error: Uncaught Type Error: Object 1 has no method "toUpperCase".

Here's my code. I understand mysql is depreciated, but I'd like to get this implemented before I do any upgrades. ;)

SCRIPT.PHP

$('#submit').click(function(){ // Perform checks to ensure all dropdown selections have been selected. // Validations have been successful, now populate variable portions of the paypal form
$('#emailBuyer').val($('#email_paypal').val());

    var host     = $(location).attr('host');
    var protocol = $(location).attr('protocol');        
    var pathname = $(location).attr('pathname');

    var returnPath          = pathname.replace("removed","removed");
    var cancelReturnPath    = pathname.replace("removed","removed");
    var returnPathUrl       = protocol + "//" + host + returnPath + $('#email_paypal').val();
    var cancelReturnPathUrl = protocol + "//" + host + cancelReturnPath + $('#email_paypal').val();     

    $('#returnPath').val(returnPathUrl);        
    $('#cancelReturnPath').val(cancelReturnPathUrl);        

    // Send the email. It needs to have the async=false as the form is tried to redirect to paypal before the email is sent!
    jQuery.ajaxSetup({async:false});
    $.get( controllerDir + 'email.php', {
    email: $('#email_paypal').val(),
    type: 1,
    question_one: $("#question_one option:selected").text(),
    question_two: $("#question_two option:selected").text(),
    question_three: $("#question_three option:selected").text(),
    question_four: $("#question_four option:selected").text(),
    question_five: $("#question_five option:selected").text(),
    question_six: $("#question_six option:selected").text(),
    question_seven: $("#question_seven option:selected").text(),
    question_eight: $("#question_eight option:selected").text(),
    question_nine: $("#question_nine option:selected").text(),
    question_ten: $("#question_ten option:selected").text(),
    amount: $('#amount').val(),
    shipping: $('#shipping').val(),
    total: $('#total').val(),
    contentType: "application/json",
    dataType: "json",
    success: function (data) {
    var myData = jQuery.parseJSON(data);
    console.log(mydata['orderid']);
        if (myData.orderid == '0') {
            alert('FAILED');
            $('#item_name').val( order_id + 'FAILED' + '');
        } else {
        var order_id = myData.orderid;
        $('#item_name').val( order_id + 'SUCCESS' + '');
        }
    }
    });
    jQuery.ajaxSetup({async:true});
});

EMAIL.PHP

    <?php
header('Content-Type: text/html');
 //Define Variables
 //User ID for remote email server
    $user_id = "REMOVED";  // Reece
    $question_one = $_GET['question_one'];
    $q1 = ltrim($question_one, "0123456789., ");
    $question_two = $_GET['question_two'];
    $q2 = ltrim($question_two, "0123456789., ");
    $question_three = $_GET['question_three'];
    $q3 = ltrim($question_three, "0123456789., ");
    $question_four = $_GET['question_four'];
    $q4 = ltrim($question_four, "0123456789., ");
    $question_five = $_GET['question_five'];
    $q5 = ltrim($question_five, "0123456789., ");
    $question_six = $_GET['question_six'];
    $q6 = ltrim($question_six, "0123456789., ");
    $question_seven = $_GET['question_seven'];
    $q7 = ltrim($question_seven, "0123456789., ");
    $question_eight = $_GET['question_eight'];
    $q8 = ltrim($question_eight, "0123456789., ");
    $question_nine = $_GET['question_nine'];
    $q9 = ltrim($question_nine, "0123456789., ");
    $question_ten = $_GET['question_ten'];
    $q10 = ltrim($question_ten, "0123456789., ");
    $amount = $_GET['amount'];
    $shipping = $_GET['shipping'];
    $total = $_GET['total'];
    $type  = $_GET['type'];    
    $order = $_GET['order'];
    $date = date('m/d/Y');
    $email_paypal = $_GET['email'];

    // Upload to database first. All credentials are correct,
// as when the "success" part of the ajax call (script.php) is removed, everything is uploaded perfectly.
 mysql_connect("CORRECT WEBHOST", "CORRECT USER", "CORRECT PASS") or die(mysql_error()); 
 mysql_select_db("CORRECT DB") or die(mysql_error()); 
 mysql_query("CORRECT QUERY"); 
 $order_id = mysql_insert_id();

switch($type) {
        case "1" :
            $name     = "Order $order_id Placed on $date";
            $comments = "(UNPAID) $q1, $q2, $q3, $q4, $q5, $q6, $q7, $q8, $q9, $q10"; 
            break;
        case "2" :
            $name     = "Order Paid on $date";
            $comments = "(PAID) $order";
            break;
        case "3" :
            $name     = "Order Cancelled on $date";
            $comments = "(CANCELLED) $order";
            break;          
        default :
            $name     = "$email_paypal $date";
            $comments = "Form Error. Unable to process email.";
    } 
    // Then send an email.

    $payload = "user_id=$user_id&form_id=2&name=$name&email=$email_paypal&comments=$comments";

    $curl_connection = curl_init("REMOVED");
    curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36");
    curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_connection, CURLOPT_POST, true);
    curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $payload);
    // NOTE: Error messages using an echo cannot be placed anywehere in this file. It distracts JSON and will make the Order ID variable unobtainable.
    header('Content-Type: application/json');
echo json_encode(array("orderid" => "$order_id","email" => "$email_paypal"));
?>

I think you have done it right. You do not have to set header to the json you are returning. If you set the dataType as json jQuery will expect the data as json and if the data returned by the php is not json it would be handled by the error function of jQuery AJAX .

You can replace this

header('Content-Type: application/json');
echo json_encode(array("orderid" => "$order_id","email" => "$email_paypal"));

By

die( json_encode(array("orderid" => "$order_id","email" => "$email_paypal")) );

Notice that I used die it is because I do not want anything else to run after I output json , extra whitespaces or other text that might get printed after the response can mess up the json response. So just to be safe.

hence you can skip this line as well in the success function

var myData = jQuery.parseJSON(data);

it will be json

And this is not even in the question but just a sugestion that will reduce the lines of the codes

$question_one = $_GET['question_one'];
    $q1 = ltrim($question_one, "0123456789., ");
    $question_two = $_GET['question_two'];
    $q2 = ltrim($question_two, "0123456789., ");
    $question_three = $_GET['question_three'];
    $q3 = ltrim($question_three, "0123456789., ");
    $question_four = $_GET['question_four'];
    $q4 = ltrim($question_four, "0123456789., ");
    $question_five = $_GET['question_five'];
    $q5 = ltrim($question_five, "0123456789., ");
    $question_six = $_GET['question_six'];
    $q6 = ltrim($question_six, "0123456789., ");
    $question_seven = $_GET['question_seven'];
    $q7 = ltrim($question_seven, "0123456789., ");
    $question_eight = $_GET['question_eight'];
    $q8 = ltrim($question_eight, "0123456789., ");
    $question_nine = $_GET['question_nine'];
    $q9 = ltrim($question_nine, "0123456789., ");
    $question_ten = $_GET['question_ten'];
    $q10 = ltrim($question_ten, "0123456789., ");

this can be replaced by

but if it is possible to change the variables to question_1, question_2 and so on

I would do this in a loop

for( $i = 1 ; $i <=10;$i++ ) {
    $qVar = "q".$i;
    $questionVar = "question_" . $i;
    $$questionVar = $_GET[ $questionVar ];
    $$qVar = ltrim( $$questionVar, "0123456789., ");


}

This way you have you variable set up in four lines an you can access them as $q1, $q2..so on and $question_1, $question_2

But that's just me. I love loops :)

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