Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 401
  • Last Modified:

jQuery ajax parse POSTed JSON values

Got the following jQuey ajax code:
    window.attendees = {};
    window.attendees.eventcode    = "GEVENT";
    window.attendees.price        = 99.00;
    window.attendees.WaitingList  = "";
    window.attendees.participants = [];

    if(waiting_list_flag) {
      window.attendees.WaitingList = "YES";
    } else {
      window.attendees.WaitingList = "NO";
    }

    $('#next_btn').click(function() {
      addParticipant(); // adds the last entered participant info to the participants object
      var url = AJAX_URL_ADD
      json_data = JSON.stringify(window.attendees); // json encode the participants

      $.ajax({async: false, 
              type:'POST',
              url: url, 
              data: json_data, 
              dataType: 'json', 
              contentType: "application/json; charset=utf-8", 
              success: function(data){
                if(data.result=='success') {
                  window.location = GOTO_URL;
                } else {
                  //display error
                  $('.error_message').html(data.message);
                } // if(data.result=='success')
              } // success function()
      }); // $.ajax
    }); // $('#next_btn').click

  // also called from another button click to add more participants
  function addParticipant() {
    var participant = {};
    participant.firstname   = $('#FirstName').val();
    participant.lastname    = $('#LastName').val();
    participant.email       = $('#Email').val();
    window.attendees.participants.push(participant);
  } // function addParticipant()

Open in new window



Now, in my AJAX_ADD_URL, I am trying to parse the results but getting nothing at all:
<?php
  // print to see if it got there...
  print_r($_POST);
  exit;

  $json_object = json_decode(stripslashes($_POST['data']), true);

  $event_code        = $json_object['eventcode'];
  $waiting_list_flag = $json_object['WaitingList'];
  // Set Price to 0.00 if this is a WaitingList registration
  if ($waiting_list_flag == 'YES') {
  	$price           = 0.00;
  } else {
    $price           = (float) $json_object['price'];
  }
  
  if($price <> 0.00) {
    foreach($json_object['participant'] as $item) {
      $sku = 'voucher';
      //set details for one item in cart
      $voucher_detail['firstname'] = $item['firstname'];
      $voucher_detail['lastname'] = $item['lastname'];
      $voucher_detail['email'] = $item['email'];
      $voucher_detail['WaitingList']   = $waiting_list_flag;
      $voucher_detail['price']         = $price;
      
      // do something with $voucher_details array values...
    } // foreach($json_object as $item)
  } else {
    $result = array('result' => 'no_price');
  }
  echo json_encode($result);

?>

Open in new window

prints
Array ( )

Open in new window


What am I doing wrong here?

0
Eddie Shipman
Asked:
Eddie Shipman
  • 6
  • 6
1 Solution
 
leakim971PluritechnicianCommented:
client side, line 16 to 21 :
      //json_data = JSON.stringify(window.attendees); // json encode the participants

      $.ajax({async: false, 
              type:'POST',
              url: url, 
              data: window.attendees, 

Open in new window


php, line 1 to 9 :
<?php
  // print to see if it got there...
  print_r($_POST);
  exit;

  //$json_object = json_decode(stripslashes($_POST['data']), true);

  $event_code        = $_POST['eventcode'];
  $waiting_list_flag = $_POST['WaitingList'];

Open in new window


data (line 21) is not the name of a parameter, it's a variable name used by jQuery.ajax
so you can pass directly your json object
or build a query string manually (field1=value1&field2=value2)
and use : data : "field1=value1&field2=value2", // work too
0
 
Eddie ShipmanAll-around developerAuthor Commented:
Sorry leakim971, it isn't working. I still get an empty array coming back when I try to print_r() the $_POST

0
 
Eddie ShipmanAll-around developerAuthor Commented:
In fact, if I change to print the $_REQUEST global it returns a whole bunch of info but not any of the windows.attendees data.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Eddie ShipmanAll-around developerAuthor Commented:
This is how we are currently doing it with a single attendee.

I am trying to modify our current application where we can send multiple attendees at one time:
  var url = AJAX_URL_ADD + '?firstname=' + doUrlEncode(firstname)
   + '&lastname='  + doUrlEncode(lastname)
   + '&price='     + doUrlEncode(price)
   + '&eventcode=' + event_code
   + '&email='     + doUrlEncode(email)
   + '&WaitingList=';
  if(waiting_list_flag) {
    url += 'YES';
  } else {
    url += 'NO';
  } // if(waiting_list_flag)
  
  $.ajax({async: false, type:'POST',url: url, dataType: 'json', success: function(data){

Open in new window


The problem with doing it this way is the URL length limitations. We may have 20 or even more attendees at a time and this is only a subset of all the data that gets sent. There are 7 more values for each participant that are being sent.
0
 
leakim971PluritechnicianCommented:
0
 
Eddie ShipmanAll-around developerAuthor Commented:
Those aren't going to help me if the POST isn't actually available in the PHp script.
0
 
leakim971PluritechnicianCommented:
ok, give me some time to make some tests. I'll be back on this (or someone else :))
0
 
leakim971PluritechnicianCommented:
ok you just need to comment this line : contentType: "application/json; charset=utf-8",
$('#next_btn').click(function() {
			addParticipant(); // adds the last entered participant info to the participants object
			var url = AJAX_URL_ADD;
			//json_data = JSON.stringify(window.attendees); // json encode the participants
			
			$.ajax({async: false, 
				type:'POST',
				url: url, 
				data: window.attendees, 
				dataType: 'json', 
				//contentType: "application/json; charset=utf-8", 
				success: function(data){
					if(data.result=='success') {
						window.location = GOTO_URL;
					}
					else {
						//display error
						$('.error_message').html(data.message);
					} // if(data.result=='success')
				} // success function()
			}); // $.ajax
		}); // $('#next_btn').click
	});

Open in new window

0
 
Eddie ShipmanAll-around developerAuthor Commented:
I am sure I already tried that and it still didn't work. Will be able to test it tomorrow.
0
 
leakim971PluritechnicianCommented:
if you place an alert in the succes function : alert(data)
Array
(
    [eventcode] => GEVENT
    [price] => 99
    [WaitingList] => YES
    [participants] => Array
        (
            [0] => Array
                (
                    [firstname] => leakim
                )

        )

)

Open in new window

0
 
Eddie ShipmanAll-around developerAuthor Commented:
For some reason, it seems to be working now. Guess I wasn't holding my mouth correctly. ;-)
0
 
leakim971PluritechnicianCommented:
cool! thanks for the points, see you later
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 6
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now