0

Hey all i am trying to figure out how to go about getting my forms values that are sent via ajax json in the php script.

$.ajax
({
    type: "POST",
    url: "http://www.xxx.com/cart/gateway",
    dataType: 'json',
    async: false,
    contentType: "json",
    data: JSON.stringify({ "unique_id": $("#order_unique_id").val(), "name_on_card" : $("#name_on_card").val(), "card_number" : $("#card_number").val(), "expiry_date" : $("#expiry_date").val(), "cvv_code" : $("#cvv_code").val() }),
    success: function (data) {
        if (data && data != null && data["success"] != null && data["orderid"]) {
                processSuccess(data["orderid"]);
            } else if (data && data != null && data["error"] != null) {
                processError(data["error"]);
            } else {
                processError('unknown');
            }
            processing = false; 
    }
})

Currently it has an error but thats only because its looking for a POST value from a form. Here is that code:

 public function __construct(&$page, $params) {
    $page->cart = new theCart();
    $page->cart->set_form();

    switch($action){
        case 'gateway':
            $this->checkoutCart($page);
            break;

 ...}

 function set_form()
{
$this->setFormValue('b_email');
$this->setFormValue('b_first_name');
$this->setFormValue('b_last_name');
.....etc etc
//ADDED 7/25/2012
$this->setFormValue('name_on_card'); 
$this->setFormValue('card_number'); 
$this->setFormValue('expiry_date'); 
$this->setFormValue('cvv_code'); 
$this->setFormValue('order_unique_id'); 

$this->verified = false;
 }

 function setFormValue($name){
   if(isset($_POST[$name])){
     $this->$name = trim($_POST[$name]);
   }
 }

 private function checkoutCart(&$page){
    $page->part->body->content_html = $this->pPay($page, $this->getPay());
}

 private function getPay(){
    //echo 'getP== ' . json_decode( $_POST[ 'unique_id' ], true );
    echo 'getP== ' . $_POST['unique_id'];

    return array(
        'unique_id' => $_POST['unique_id'],
        'name_on_card' => $_POST['name_on_card'],
        'card_number' => $_POST['card_number'],
        'expiration_date' => $_POST['expiry_date'],
        'cvv_code' => $_POST['cvv_code']
    );
}

I am not getting any value for $_POST['unique_id'] above.

The original post code was this:

$.post("http://www.xxx.com/cart/gateway",
        {
            unique_id:$("#order_unique_id").val(),
            name_on_card:$("#name_on_card").val(),
            card_number:$("#card_number").val(),
            expiry_date:$("#expiry_date").val(),
            cvv_code:$("#cvv_code").val()   
        },
        function(data) {
            if (data && data != null && data["success"] != null && data["orderid"]) {
                processSuccess(data["orderid"]);
            } else if (data && data != null && data["error"] != null) {
                processError(data["error"]);
            } else {
                processError('unknown');
            }
            processing = false;
        },
        "json"
);

But that did not work as it could not be formatted correctly (its looking for a json response.. that seemed to put it in ?blah=blah&blah=blah.... **BUT that did produce the values it was looking for in the $.POST part of the code.. but its worthless if the error goes to not being in the wanted format (json).

How can i correct this from happening?

UiUx
  • 967
  • 2
  • 14
  • 25
StealthRT
  • 10,108
  • 40
  • 183
  • 342
  • Cross domain ajax request ? Walking against Same Origin policy ? – Shyju Jul 25 '12 at 19:20
  • Is there a reason you aren't simply using [`.serialize()`](http://api.jquery.com/serialize/)? – PeeHaa Jul 25 '12 at 19:21
  • @PeeHaa: Because it seems that **http://www.xxx.com/cart/gateway** is looking for data in the form of **json** because if i just visit that url it says **{"error":"invalid_order"}** – StealthRT Jul 25 '12 at 19:27
  • why `async: false` when making an _Asynchronous_ JavaScript and XML (AJAX) call? The browser can be unresponsive during the operation – MrOBrian Jul 25 '12 at 19:40
  • Have you confirmed that `$("#order_unique_id").val()` returns a value at that point in the code? – Kevin B Jul 25 '12 at 19:43
  • @KevinB: Yes it returns a value. – StealthRT Jul 25 '12 at 19:45
  • Additionally, I'm not positive on how jquery handles a jsonstring in the data parameter when you don't use processData:false. I would expect it to take that string, convert it to an object, and then parameterize it to send it to the server. If that were the case though, your unique ID would contain a value. Do any of the other post fields contain values? – Kevin B Jul 25 '12 at 19:47
  • @KevinB: no others contain values as well. Check the OP again, i updated it with what they were using that did not work. – StealthRT Jul 25 '12 at 19:50
  • 1
    Honestly, i'm not sure. I don't know if you can send both JSON as the request body AND separate post vars. I've always used one or the other. If you send it as JSON, i would expect all of the $_POST[] to be empty. – Kevin B Jul 25 '12 at 19:55

3 Answers3

0

If data is a string, it should be a query string. JSON.stringify converts it to JSON. You can just pass data an object and the conversion to a query string will be handled for you.

edit: In other words, change:

data: JSON.stringify({ "unique_id": $("#order_unique_id").val(), "name_on_card" : $("#name_on_card").val(), "card_number" : $("#card_number").val(), "expiry_date" : $("#expiry_date").val(), "cvv_code" : $("#cvv_code").val() }),

to

data: { "unique_id": $("#order_unique_id").val(), "name_on_card" : $("#name_on_card").val(), "card_number" : $("#card_number").val(), "expiry_date" : $("#expiry_date").val(), "cvv_code" : $("#cvv_code").val() },
Dan
  • 379
  • 2
  • 9
0

PHP expects form encoded data, (application/x-www-form-urlencoded).

Don't pass JSON as the dataType:

$.post("http://www.xxx.com/cart/gateway",
        {
            unique_id:$("#order_unique_id").val(),
            name_on_card:$("#name_on_card").val(),
            card_number:$("#card_number").val(),
            expiry_date:$("#expiry_date").val(),
            cvv_code:$("#cvv_code").val()   
        },
        function(data) {
            if (data && data != null && data["success"] != null && data["orderid"]) {
                processSuccess(data["orderid"]);
            } else if (data && data != null && data["error"] != null) {
                processError(data["error"]);
            } else {
                processError('unknown');
            }
            processing = false;
        }
        // don't do this
        // ,"json"
);
nickaknudson
  • 4,769
  • 2
  • 15
  • 16
  • I get the normal **Content Not Found (404)** when doing it that way. Its like it can not find that path if it does that. But it does have values for all $.POSTS. – StealthRT Jul 25 '12 at 20:16
  • If the values are getting passed to the PHP script then the final bit is to return _something_ from the PHP. Your PHP doesn't return anything hence the 404. – nickaknudson Jul 25 '12 at 20:42
  • If you don't need anything back, then just set [http_response_code()](http://www.php.net/manual/en/function.http-response-code.php) to 200 – nickaknudson Jul 25 '12 at 20:46
0

Since you are passing JSON in the request body instead sending post vars, you need to get the json from the request body, parse it, then pull the values out of it.

$request_body = file_get_contents('php://input');

$json = json_decode($request_body);

// use $json.unique_id

Reference: How to retrieve Request Payload

Community
  • 1
  • 1
Kevin B
  • 94,570
  • 16
  • 163
  • 180