Solved

AJAX to PHP

Posted on 2007-03-30
15
598 Views
Last Modified: 2008-07-31
I have an ajax calculation and i need the result to be converted to a php string value. The final structure for my total in javascript is:
<script language="javascript">
<!--

...code shortened....

// get the total field
elm = $("grandTotalField")

// blank it out and set it with the total
deleteChildren(elm);
elm.appendChild(document.createTextNode(formatDecimal(total, 2)));

elm = $("x_amount");
elm.value = String(total);

//-->
</script>
How would I convert this to:

<?php
$total = ????? (ajax value here) ???????
?>

Thanks!
~Aus2Srq
0
Comment
Question by:Aus2Srq
15 Comments
 
LVL 29

Expert Comment

by:rdivilbiss
ID: 18826815
PHP runs server side. It is finished executing once your javascript executes. So if you made a calculation on the clinet side you need to post it back to the server before PHP can see the value.

Are you wanting to send the value back to the server with AJAX?
0
 

Author Comment

by:Aus2Srq
ID: 18827099
This is a shipping calculation. The user selects their ship type (ground, next day, etc) via a drop down that triggers the ajax to pull the shipping amount and recalculates the total on my checkout page. The ajax is calculating and displaying correctly now I need my form to take the x_amount value and set it to my php variable $total so I can post this amount to the payment gateway.

Is that a little more clear? Basically, I am wanting to do this:

<?php $total ?>  = <script> x_amount</script>

Obviously this doesn't work, but is the only way I can think of illustrating what I need to happen.

~A2S
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18827196
In the browser there is no PHP variable $total.  It is just html.  That is what you need to correct.  Don't worry about the PHP script because that is done and could only change this page with a refresh.  That would defeat the purpose of the AJAX script.  That was what Rdivilbiss was referring to.

Is the total in some specific html tags?  If so which and show us the html.  Basically the normal way to do what you want is to have the AJAX script "send" the result to the page with something like ...

document.getElementById('totalContainer').innerHTML = result;

That would be a line at the end of the AJAX script.  "result" is the javascript variable with the result or the xmlobject result itself.  In your page you would have the total in HTML like this ...

$ <span id="totalContainer">AMOUNT</span>

Notice the id.  That is the key and almost any element will work.  You don't have to use span.  If you need help producing that html in PHP let us know.

Let me know if you have a question.  We will need code (javascript/ajax and html for total) to be able to provide details.  This should at least get you started and will hopefully clear up how it works.

bol
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18827202
If the total is in an input (like in a form) then you can also use javascript to "fill" the input.  I doubt that is the case but let me know if you need an example of it.

bol
0
 
LVL 15

Accepted Solution

by:
stanscott2 earned 250 total points
ID: 18827360
My colleagues are right; you can't directly set the value of the PHP variable.

However, you CAN set up a hidden field on your form, "calcTotal", and populate that from your Ajax process.  Then, when you post the form back to the server, your PHP code will include this line:

$calcTotal = $_REQUEST['calcTotal'] ;

which you can then use to update your data at the server.

0
 

Author Comment

by:Aus2Srq
ID: 18827381
Thanks for clearing up some of the fog bol. I will definately need some assistance with the PHP/html. Here is the entire javascript calculation:

function myServerCallback(objResponse) {
      var obj;
      var totalChargeEstimate;
      var total;
      var elm;

      total = 0;

      obj = objResponse.parseJSON();
/*
      elm = $("errmsg");
      deleteChildren(elm);
      elm.appendChild(document.createTextNode(obj.result.substring(1)));
*/
      if (obj) {
            
            // Shipping
            totalChargeEstimate = obj.totalPrice;            

            totalChargeEstimate = Number(totalChargeEstimate) + 5;
            
            // get the shipping cost field
            elm = $("shipCostField")

            // assign the value to the shipping field
            deleteChildren(elm);
            elm.appendChild(document.createTextNode(formatDecimal(totalChargeEstimate, 2)));
            
            // set the hidden freight field
            elm = $("x_freight");
            elm.value = String(totalChargeEstimate);
            
            // save it to total
            total += Number(totalChargeEstimate);
            
            // get this discounts            
            elm = $("x_discount");
            if (elm) {
                  total = Number(total) - Number(elm.value);
            }

            // get the subtotal field and add it to the total
            elm = $("subtotal");
            total = Number(total) + Number(elm.value);
            
            // get the tax field and add it to the total
            elm = $("x_tax");
            if (elm) {
                  total = Number(total) + Number(elm.value);
            }
            
            // get the total field
            elm = $("grandTotalField")

            // blank it out and set it with the total
            deleteChildren(elm);
            elm.appendChild(document.createTextNode(formatDecimal(total, 2)));

            elm = $("x_amount");
            elm.value = String(total);
      }
}

There is another function above this one, but it just grabs the variables from a cookie that has been set with the shipping information and initiates the myServerCallback function. Here is the code with the span id that you were refering to that displays the total on the page:

$<span id="grandTotalField"></span><input type="hidden" id="x_amount" name="x_amount"  />

Then I need the following code to work to send the total (x_amount) to the payment gateway:
<?php
      $total= ???
      $curr      = "usd";
      InsertSignature($total,$curr)
?>

where $total somehow equals <span id ="grandTotalField">

This is the PHP I am needing the help/conversion for.

~A2S
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18827390
Skip the span if this uses that hidden input.  use the id in the hidden input.  Instead of innerHTML you would use value.  As long as x_amount isn't used in any other tag/element then it will work.

It seems like something is still missing for the AJAX part.  Is there a javascript file that is external to this?  We need to find out what is used to return the results.  It would usually use lines with "xmlhttp" in them.

bol
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18827414
Actually, now that I think about it, you probably want the total in both, the span and the hidden input.  Hopefully that last comment didn't just confuse this more.   If the total needs to be sent with the form then it needs to go in some input and that hidden one looks like it was made for it.  If the user should see it then the span is needed because the hidden input is HIDDEN. :)

The code above may be doing what we need but it just hard for me to understand.  It seems to be the end of the middle of a process and without other javascript and/or html it is vague.  Can you clarify?  For this question we need a variable or object's property that has the total.

I hope this helps!  Let me know.

bol

0
 

Author Comment

by:Aus2Srq
ID: 18827695
This thing has several PAGES of code. When the user selects a new ship type from the drop down, the following function is called:

<select id="selShipMethodDomestic" name="selShipMethodDomestic" onchange="recalcShipMethodDomestic(this);">

which is this:

function recalcShipMethodDomestic(selectElm) {
      var obj;
      var shipCode = selectElm.options[selectElm.selectedIndex].value;

      obj = { "cart" : cart,
            "CountryCode" : rsShip['country'],
            "ShipCode" : shipCode,
            ... the address ...
            "PostalCode" : rsShip['zip'],
            "url" : "https://eCommerce.airborne.com/ApiLandingTest.asp" // change from test
      };

      myCallServer(obj.toJSONString());
}

this runs ajaxInc.php from www.xajaxproject.org which has the myCallServer function. This creates a new variable (i think) :
<?php $Ajax = new ajax(); ?>

which calls the ajax request. This var Ajax is a javascript file to do the XMLHTTPRequest, calls the server:

var Ajax = {
      getXMLHttpRequestObject: function() {
            // Browser-nonspecific function to get an XMLHttpRequest object.
            var req = null;
            if (typeof XMLHttpRequest != "undefined")
                  req = new XMLHttpRequest();
.... etc....

loadingFunction: function() {},
      doneLoadingFunction: function() {},
      responseFunction: function(sResponse) {},

      callServer: function(ajaxargs) { ...etc...

 and returns post data (again, I think that what it looks like it does):

...
r.send(postData);
            delete r;
            return true;
}

From there the XML is parsed:

function doParseXML($xmlString) { ... etc ...

and sent for the cost of shipping to be returned via XML stream. This creates an object with the price for shipping and then dumps it into myServerCallback().

Does this clarify at all? This is my first time even looking into AJAX so I'm not really too sure any more than this. All I do know is what you said above, that $<span id="grandTotalField"></span> is where my final value is shown.

~A2S

0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18827741
Thanks for the additional details.  It was very helpful and I think I have enough now.

It seems like the number we want is in total.  Is the myServerCallback function the last of the AJAX process?  It seems like it is and that by the end of that function total has the amount you need.  If that is the case then you putting the amount in the page should be as easy as adding a line to the end of the myServerCallback function (see below) .

            elm = $("x_amount");
            elm.value = String(total);
            document.getElementById('grandTotalField').innerHTML = total;
      }
}

Let me know the result of adding that line.

bol
0
 

Author Comment

by:Aus2Srq
ID: 18835879
I understand that puts grandTotalField as a viewable element on the page, but how to I make that element a value that php will understand? What do I do to make <?php $amount ?>  = grandTotalField?

~A2S
0
 

Author Comment

by:Aus2Srq
ID: 18835918
This looks close to what I need:

However, you CAN set up a hidden field on your form, "calcTotal", and populate that from your Ajax      process.  Then, when you post the form back to the server, your PHP code will include this line:

$calcTotal = $_REQUEST['calcTotal']

Where would I set calcTotal in the Ajax?



~A2S
0
 
LVL 54

Assisted Solution

by:b0lsc0tt
b0lsc0tt earned 250 total points
ID: 18840275
So do you need the total to appear not just on this page (i.e. in the span called grandTotalField) but also in the form so the next page gets it?  If so, use you PHP to create an input like the one below.

echo '<input type="hidden" id="calcTotal" name="calcTotal" value="">';

That line has to be within the form tags on the page and would be best close to the grandTotalField span.  Then the AJAX script can use a line like the one below to put the total in the value of that hidden input.

document.getElementById('calcTotal').value = total;

That line could go right below the line that "writes" the total to the span called grandTotalField.

Your next page, the page getting the form, can have a PHP line like the one StanScott suggested to get the value from the form.

$total = $_REQUEST["calcTotal"];

All you need to use is $_POST["calcTotal"], $_GET["calcTotal"], or the line above to get the value from the form.  Remember this is on the NEXT page but it sounds like you need it there too.

Let me know how this helps or if you have a question.

bol
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now