Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

Why does this AJAX transaction not see the posted variables?

Here's my HTML:

<form method="Post" id="shippingForm"><!--<form method="Post" action="shipping_form.php">--><input type="text" name="shipping_zip" style="width:180px; margin-top:10px; margin-left:3px;"><input type="hidden" name="shipping_session_id" value="<?php echo $the_session_id;?>"><input type="image" src="images/calculate_shipping.png" style="margin-left:3px;"></form>

Open in new window


Here's my JQuery:

$("#shippingForm").submit(function(e) {// use the correct ID
	cache:false,
	e.preventDefault();// we don\'t want to submit anything until we\'ve first determined that the user\'s not get ready to duplicate something that\'s already in the database.

	var devTest = $( "#shippingForm").serialize(); //packaging all of our submitted variables into one, neat little var
	alert("Develop test, URL prams = "+devTest);// publish a little alert box that lets you see your posted variables
	$.post( "shipping_form.php", devTest) // posting all of our variables to ajax.php 
		.done(function(Drumstick) { //the "done"function is what you\'re doing when the AJAX call (in this case the ajax.php page) is "done" running and we\'re now hearing back from the server
			if (Drumstick.charAt(0) == "E") //"Drumstick.charAT(0) is just fancy code for the first letter of what you\'re getting back from the server
			{
				alert("ERROR - The submarket has been entered before");
			}
			else 
			{	
				//alert(Drumstick);
				$('#shipping_result').load('shipping_form.php');
			}
		});
	});

Open in new window


You notice the "alert."

That looks like this:

User generated image
Everything looks good, right?

Here's the error I get when I run this:

User generated image
The error message is saying that both the $_POST['shipping_zip'] and $_POST['shipping_session_id'] are unrecognized.

Here's my shipping_form.php code. I'm including it in its entirety in case you want some context to better figure out what's going on:

<?php
include("carter.inc");
$cxn = new mysqli($host,$user,$password,$database);
if($cxn->connect_errno)
{
	$err="CONNECT FAIL: "
	.$cxn->connect_errno
	. ' '
	.$cxn->connect_error
	;
	trigger_error($err, E_USER_ERROR);
}

require_once('fedex-common.php');

//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.


function addShipper(){
	$shipper = array(
		'Contact' => array(
			'PersonName' => 'Shane Doyle',
			'CompanyName' => 'KitchenCabinetCo',
			'PhoneNumber' => '615.828.8377'
		),
		'Address' => array(
			'StreetLines' => '3515 Cleburne Road',
			'City' => 'Spring Hill',
			'StateOrProvinceCode' => 'TN',
			'PostalCode' => '37174',
			'CountryCode' => 'US'
		)
	);
	return $shipper;
}

//sample code
function addRecipient($c_zip){
	$recipient = array(
		'Contact' => array(
			'PersonName' => '',
			'CompanyName' => '',
			'PhoneNumber' => ''
		),
		'Address' => array(
			'StreetLines' => array('Address Line 1'),
			'City' => '',
			'StateOrProvinceCode' => '',
			'PostalCode' => '17584',
			'CountryCode' => 'US',
			'Residential' => true
		)
	);
	return $recipient;	                                    
}

function addShippingChargesPayment(){
	$shippingChargesPayment = array(
		'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
		'Payor' => array(
			'ResponsibleParty' => array(
				'AccountNumber' => getProperty('billaccount'),
				'CountryCode' => 'US'
			)
		)
	);
	return $shippingChargesPayment;
}

function addLabelSpecification(){
	$labelSpecification = array(
		'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
		'ImageType' => 'PDF',  // valid values DPL, EPL2, PDF, ZPLII and PNG
		'LabelStockType' => 'PAPER_7X4.75'
	);
	return $labelSpecification;
}

function addSpecialServices(){
	$specialServices = array(
		'SpecialServiceTypes' => array('COD'),
		'CodDetail' => array(
			'CodCollectionAmount' => array(
				'Currency' => 'USD', 
				'Amount' => 150
			),
			'CollectionType' => 'ANY' // ANY, GUARANTEED_FUNDS
		)
	);
	return $specialServices; 
}

function addPackageLineItem1($height, $width, $depth, $weight){
	$packageLineItem = array(
		'SequenceNumber'=>1,
		'GroupPackageCount'=>1,
		'Weight' => array(
			//'Value' => 50.0,
			'Value' => $width,
			'Units' => 'LB'
		),
		'Dimensions' => array(
			/*'Length' => 108,
			'Width' => 5,
			'Height' => 5,*/
			'Length' => $depth,
			'Width' => $width,
			'Height' => $height,
			'Units' => 'IN'
		)
	);
	return $packageLineItem;
}

function getCart($the_session_id, $c_zip) {
	$amount="";
//echo $the_session_id;	
global $cxn;

 $sql="select cart.product_id, cart.quantity, products.height, products.width, products.depth, products.weight from cart INNER JOIN products on cart.product_id=products.id where cart.session_id='$the_session_id' AND cart.product_cost>0 AND cart.product_id<>'392' AND cart.product_id<>'393'";
	 $query=$cxn->query($sql);
	while($row=$query->fetch_assoc())
	{
		// this part is retrieving the shipping cost
		
		$path_to_wsdl = "fedex/wsdl/RateService_v18.wsdl";

		ini_set("soap.wsdl_cache_enabled", "0");
		 
		$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information

		$request['WebAuthenticationDetail'] = array(
			'ParentCredential' => array(
				'Key' => getProperty('parentkey'),
				'Password' => getProperty('parentpassword')
			),
			'UserCredential' => array(
				'Key' => getProperty('key'), 
				'Password' => getProperty('password')
			)
		); 
		$request['ClientDetail'] = array(
			'AccountNumber' => getProperty('shipaccount'), 
			'MeterNumber' => getProperty('meter')
		);
		$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request using PHP ***');
		$request['Version'] = array(
			'ServiceId' => 'crs', 
			'Major' => '18', 
			'Intermediate' => '0', 
			'Minor' => '0'
		);
		$request['ReturnTransitAndCommit'] = true;
		$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
		$request['RequestedShipment']['ShipTimestamp'] = date('c');
		$request['RequestedShipment']['ServiceType'] = 'GROUND_HOME_DELIVERY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
		$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
		$request['RequestedShipment']['TotalInsuredValue']=array(
			'Ammount'=>100,
			'Currency'=>'USD'
		);
		$request['RequestedShipment']['Shipper'] = addShipper();
		$request['RequestedShipment']['Recipient'] = addRecipient($c_zip);
		$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
		$request['RequestedShipment']['PackageCount'] = '1';
		$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1($row['height'], $row['width'], $row['depth'], $row['weight']);//you've got to pass in your height, width, depth and weight into this function



		if(setEndpoint('changeEndpoint'))
		{
			$newLocation = $client->__setLocation(setEndpoint('endpoint'));
		}
		
		$response = $client -> getRates($request);
			
		if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
		{  	
			$rateReply = $response -> RateReplyDetails;
			/*echo '<table border="1">';
			echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>';
			$serviceType = '<td>'.$rateReply -> ServiceType . '</td>';*/
			if($rateReply->RatedShipmentDetails && is_array($rateReply->RatedShipmentDetails))
			{
				$amount = number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",");
			}
				elseif($rateReply->RatedShipmentDetails && ! is_array($rateReply->RatedShipmentDetails))
				{
					$amount = number_format($rateReply->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",");
				}
			/*if(array_key_exists('DeliveryTimestamp',$rateReply)){
				$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
			}else if(array_key_exists('TransitTime',$rateReply)){
				$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
			}else {
				$deliveryDate='<td>&nbsp;</td>';
			}
			echo $serviceType . $amount. $deliveryDate;
			echo '</tr>';
			echo '</table>';*/
			
			//printSuccess($client, $response);
		}
		else
		{
			//printError($client, $response);
		} 
		//writeToLog($client);    // Write to log file   

		//echo $amount;
		
		//end of fedex code
		
		$the_amount=$row['quantity'] * $amount;
		//echo $amount;
		//echo "<br>";
		
		$sql_1="insert into fedex (session_id, product_id, height, width, depth, weight, quantity, shipping) VALUES ('$the_session_id', '$row[product_id]', '$row[height]', '$row[width]', '$row[depth]', '$row[weight]', '$row[quantity]', '$the_amount')";
		//echo $sql_1;
		$query_1=$cxn->query($sql_1);
	 }

}

function clearCart($the_session_id) {
	
	global $cxn;
	
	$sql="delete from fedex where session_id='$the_session_id'";
	$query=$cxn->query($sql);
	
}

function totalShipping($the_session_id) {
	
	global $cxn;
	
	$sql="select sum(shipping) as total_shipping from fedex where session_id='$the_session_id'";
	$query=$cxn->query($sql);
	$row=$query->fetch_assoc();
	
	return $row['total_shipping'];
}

//first, clear the fedex table of anything that is associated with this session id so you're starting off with a clean slate

$c_zip=$_POST['shipping_zip'];

//echo $c_zip;

$the_session_id=$_POST['shipping_session_id'];

$clear=clearCart($the_session_id);

$hit_me=getCart($the_session_id, $c_zip);

$get_total=totalShipping($the_session_id);
echo number_format($get_total, 2);



?>

Open in new window


Line 248 and line 252. Simple, right?

Yet neither one of those posted variables is "seen," and I don't understand why.

Thoughts?
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bruce Gust

ASKER

Man, Ray, this is embarrassing, but it's telling at the same time.

I was using a piece of a previous script where I was truly "loading" the content into a div.

Upon closer inspection, after looking at your code, I'm not realizing my error in that I unwittingly combined a serialization with a "load" rather than: $('#sidebar_content').html(Drumstick);

And what's embracing is that I've got several successful forms crafted throughout my app, but I'm still not hip enough to recognize when I've gone south.

Thank you!
And Slick, I just saw your post.

Here's where I made my mistake:

I copied and pasted a previous serialization of some form data and it looked like this:

      $("#theForm").submit(function(e) {// use the correct ID
            cache:false,
            e.preventDefault();// we don\'t want to submit anything until we\'ve first determined that the user\'s not get ready to duplicate something that\'s already in the database.
            
            var devTest = $( "#theForm" ).serialize();
            $.post( "ajax_relay.php", devTest)
            .done(function(Drumstick) {
                  if (Drumstick != "fail")
                  {
                        //alert(Drumstick);//here is where I need to refresh my page and set my toggled parts of my page to their appropriate setting      
                        $('#sidebar_content').load('ajax.php?session_id=<?php echo $the_session_id;?>');
                  }
                  else
                  {
                        alert("Something went wrong! Please contact Customer Service!");
                  }
            });
      });
});

Notice "$('#sidebar_content').load('ajax.php?session_id=<?php echo $the_session_id;?>');

The reason this worked in this instance is because ajax.php is nothing more than a number of if statements that display the contents of the updated database differently based on what was submitted. So, in that instance, "load" works just fine.

But, when I went to do just a normal form and I needed the actual content of the page I was submitting my data to, "load" did nothing other than do an empty GET call to the PHP Action Script (line #43 of Ray's response: (/ $('#shipping_result').load('temp_brucegust_server.php'); // THIS MAKES AN EMPTY GET-METHOD CALL TO THE PHP ACTION SCRIPT).

I needed to do $('#shipping_result').html(Drumstick); rather than $('#shipping_result').load('temp_brucegust_server.php'); and that's what made all the difference.

In short, I'm a bit of a dolt!

Thanks!
I hope this short info helps you some what, , you seem to be really struggling with all of the javascript operations I have seen you try, and there have been many. You may can find some time to get more knowledge in using javascript to do useful page changes. Learning Jquery, can also be beneficial and useful, you still have the copy and paste code lines from many previous questions ago like -
        // use the correct ID
My opinion is , that This whole javascript here, should have been Re-Built by you and not just some halfway copy and paste, fudge together code work that you have here. you have some totally inappropriate code lines like - the entire AJAX callback in your "done" method as -

           if (Drumstick.charAt(0) == "E")
                  {
                        alert("ERROR - The submarket has been entered before");
                  }
                  else
                  {      
                        //alert(Drumstick);
                        $('#shipping_result').load('shipping_form.php');
                  }

In the server code you don't seem to have ANY conditions to send back from server text starting with an "E" that is for the line -
      if (Drumstick.charAt(0) == "E")

so that line need to be changed to something that is a help, and has a worthwhile operation for the text coming from the server. This might require you to take a closer look at what the PHP server return text can be used properly for, , You are at a point in development, that you need to have a better idea of how the AJAX and Jquery, and javascript work to get the page change result you require. I have seen you try and copy and paste the same old Ajax javascript, many different times, for several different page operations, and then, you are back here at EE asking questions about why your same copied code used for something different, does not work for a different set up. As I said, you can be much more productive, and earn mo money, if you are able to do the javascript to PHP to javascript AJAX cycle, by learning just a portion of how it works.