Question

AJAX to PHP

Asked by: Aus2Srq

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

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-03-30 at 14:59:20ID22483965
Tags

php

,

ajax

,

javascript

Topics

PHP Scripting Language

,

JavaScript

Participating Experts
3
Points
500
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. AJAX and PHP
    Hi i am developing a shoppping cart and already have quite a few things running. I ahve this cart page where i am dispaying shipping, base price tax and stuff. For tax i am using Ajax with the staes and taxes stoer in database. Here is the code where i have one err...
  2. PHP AJAX
    Ive been trying to learn AJAX for about a week now, and getting very confused! All Im looking for is a way to set a 'drop-down' box once data is entered in another. For example:- User Building Area When a user selects the user from the drop down, th...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: rdivilbissPosted on 2007-03-30 at 15:10:16ID: 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?

 

by: Aus2SrqPosted on 2007-03-30 at 16:44:18ID: 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

 

by: b0lsc0ttPosted on 2007-03-30 at 17:20:10ID: 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

 

by: b0lsc0ttPosted on 2007-03-30 at 17:23:22ID: 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

 

by: stanscott2Posted on 2007-03-30 at 18:21:41ID: 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.

 

by: Aus2SrqPosted on 2007-03-30 at 18:34:22ID: 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

 

by: b0lsc0ttPosted on 2007-03-30 at 18:39:40ID: 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

 

by: b0lsc0ttPosted on 2007-03-30 at 18:49:31ID: 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

 

by: Aus2SrqPosted on 2007-03-30 at 20:52:05ID: 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

 

by: b0lsc0ttPosted on 2007-03-30 at 21:21:22ID: 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

 

by: Aus2SrqPosted on 2007-04-02 at 05:54:04ID: 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

 

by: Aus2SrqPosted on 2007-04-02 at 05:58:21ID: 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

 

by: b0lsc0ttPosted on 2007-04-02 at 16:27:39ID: 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

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...