How to get HTML form data into PHP function Arguments?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aveeva
    New Member
    • Apr 2019
    • 33

    #1

    How to get HTML form data into PHP function Arguments?

    The Business Logic is: If product is already purchased, upgrade the product

    I have a customer input form to get information, along with some fields which should be auto populated based on what the customer chooses.

    Screen Shot:

    https://i.stack.imgur.c om/Fkyim.png
    Note: Price and Shipping Weight are done with Ajax,

    When we come to the shipping cost I am getting it from Magento, using a PHP function.

    form :

    https://paste.ofcode.or g/335FVUhpBGbazQt rcPLVQUs
    PHP :

    sp_cost.php

    https://paste.ofcode.or g/hvG2sP9TW9CEPgM MuKXNuw
    From the above code I am given the predefined value,

    $results = getShippingEsti mate('14419','1 ',"IN","642001" );

    How can i get country and zipcode from the user entry and return the shipping cost?
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    in the code here:



    you can easyly see that at the bottom are 3 script-elements that basically do assign an event-handler (onchange) to the element with the id="new" - and all 3 handlers invoke a request each with passing the exact same data to different endpoints:

    Code:
        var old_val = $("#old option:selected").val();
        var new_val = $("#new option:selected").val();
        
        // ...
    
        data: { old: old_val, new: new_val},
    this means that you simply need to retrieve the data from the fields correctly in your javascript sections and pass it in the data-object of the ajax call to the endpoint(s) that should receive it. For optimization of all that it would even be preferable to just send 1 request and not fire 3 in parallel.

    Comment

    • aveeva
      New Member
      • Apr 2019
      • 33

      #3
      @gits : Okay, with my code how can i use input form values in PHP function arguments,

      as said,

      sp_cost.php


      From the above code I am given the predefined value,

      Code:
      $results = getShippingEstimate('14419','1',"IN","642001");
      How can i pass my zip code & country from form and pass by using ajax.

      i know the following is wrong, how can i write the right code,

      Code:
      <script>
      		$(document).ready(function(){
      		$('#new').on('change',function(){
      
      		var old_val = $("#old option:selected").val();
      		var new_val = $("#new option:selected").val();
      
      		$.ajax({
      		type: "POST",
      		// url: "ajax_ship_cost_data.php",
      		url: "sp_cost.php",
      		dataType: "text",
      		data: { old: old_val, new: new_val},
      		success: function(data)
      		{
      			// Check the output of ajax call on firebug console
      			 //console.log(data);
      			$('#findata').html(data);
      			$('#shipping_cost').val(data);
      		
      		}
      });
      
      });
      });
      </script>
      Last edited by gits; Apr 26 '19, 11:21 AM. Reason: added code tags

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        as i said - you need to retrieve the correct values from the form elements and pass it to the data object in the jQuery ajax call. I suggest to read the jQuery API docs if you don't know how to do it - i probably won't write the code for you - basically its easy changes and considered as the minimum knowledge when working with jQuery. you can start from here:



        for example and then go on from there.

        Comment

        • aveeva
          New Member
          • Apr 2019
          • 33

          #5
          Using this -> http://api.jquery.com/val/ i did my couple of fields as you see [Price & weight]. Here shipping cost field is not predefined value, actually it gets from Magento [PHP CMS]. I need some help regarding how to pass my value which is getting from Magento and insert into shipping cost field, for me, it's quite tough,

          workout :

          My PHP function :

          Code:
          <?php
          ob_start();
          // require_once(__DIR__ . '/app/Mage.php');
          require_once('./../app/Mage.php');
          umask(0);
          ini_set('display_errors',true); 
          ini_set('memory_limit', '1024M');
          Mage::app()->loadArea('frontend');
          
          function getShippingEstimate($productId,$productQty,$countryId,$postcode ) {
          
              // $quote = Mage::getModel('sales/quote')->setStoreId(Mage::app()->getStore('default')->getId());
          	$quote = Mage::getModel('sales/quote')->setStoreId(Mage::app()->getStore('english')->getId());
              $_product = Mage::getModel('catalog/product')->load($productId);
          
              $_product->getStockItem()->setUseConfigManageStock(false);
              $_product->getStockItem()->setManageStock(false);
          
              $quote->addProduct($_product, $productQty);
              $quote->getShippingAddress()->setCountryId($countryId)->setPostcode($postcode); 
              $quote->getShippingAddress()->collectTotals();
              $quote->getShippingAddress()->setCollectShippingRates(true);
              $quote->getShippingAddress()->collectShippingRates();
          
              $_rates = $quote->getShippingAddress()->getShippingRatesCollection();
          
              $shippingRates = array();
              foreach ($_rates as $_rate):
                      if($_rate->getPrice() > 0) {
                          $shippingRates[] =  array("Title" => $_rate->getMethodTitle(), "Price" => $_rate->getPrice());
                      }
              endforeach;
          
              return $shippingRates;
          
          }
          
          // echo "<pre>";
          // product id, quantity, country, postcode
          // print_r(getShippingEstimate('14419','1',"IN","642001"));
          
          // echo "</pre>";
          
          //$results = getShippingEstimate('14419','1',"IN","642001");
          
          // $results = getShippingEstimate('14419','1',"US","99501");
          
          
          
          <!-- if(isset($_POST['zip_postal_code']) && isset($_POST['country']))
              {
          	 $zip_postal_code = $_POST['zip_postal_code'];
          	 $country = $_POST['country'];
           } -->
          
          
          $results = getShippingEstimate('14419','1',"IN","642001");
          
          //$results = getShippingEstimate('14419','1',"$country","$zip_postal_code");
          
          
          $count = -1;
          echo "<select>";
          foreach ($results as $result):
          $count++;
          ?>
           <option value="<?php echo $count; ?>"> <?php echo $result["Title"]." - Rs ".$result["Price"]?>
           </option>
          
           <?php
          endforeach;
          echo "</select>"; 
          ?>

          FYI -> In PHP function :

          shipping cost calculated using :

          $results = getShippingEsti mate('14419','1 ',"IN","642001" );

          and passing the shipping cost value using,

          <option value="<?php echo $count; ?>"> <?php echo $result["Title"]." - Rs ".$result["Price"]?>
          </option>

          Note: By using $results = getShippingEsti mate('14419','1 ',"IN","642001" ); its returned the value, i need if customer enter the zip_code and country, once the customer entered those values using ajax passing value to -> $results = getShippingEsti mate('14419','1 ',"IN","642001" ); and returned to the shipping cost.

          I hope I explained well. Can I get some help?

          Comment

          • aveeva
            New Member
            • Apr 2019
            • 33

            #6
            Solved :

            Actually error in Ajax & error in passing fields,

            Code:
            	<script>
            		$(document).ready(function(){
            		$('#new').on('change',function(){
            
            		var zip = $("#zip_postal_code").val();
            		var country = $("#country").val();
            
            		$.ajax({
            		type: "POST",
            		// url: "ajax_ship_cost_data.php",
            		url: "sp_cost.php",
            		dataType: "text",
            		data: {zip_postal_code : zip, country: country},
            		success: function(data)
            		{
            			// Check the output of ajax call on firebug console
            			 //console.log(data);
            			$('#findata').html(data);
            			$('#shipping_cost').val(data);
            		
            		}
            });
            
            });
            });
            </script>

            Comment

            • gits
              Recognized Expert Moderator Expert
              • May 2007
              • 5390

              #7
              grats :) the only thing to note is that the requests are only send when the value of the select-element with id="new" is changed. so if a user only changes some other field like zip-code or something else - the request is not fired. If that's how it should work then all is good - else you would need to attach the the correct eventhandlers to the fields that are relevant for new calculations.

              Comment

              • aveeva
                New Member
                • Apr 2019
                • 33

                #8
                @gits I am facing error while select shipping cost, if i select anyone from dropdown all the values saves into db, how to modify my code.
                Output : https://snag.gy/BIJZb7.jpg

                Any help thanks.

                Comment

                • gits
                  Recognized Expert Moderator Expert
                  • May 2007
                  • 5390

                  #9
                  this screenshot doesn't tell much. your program in fact acts as you programmed it. in case the code didn't change much - you fire at least 3 requests in parallel always when you change the value of the select-element with id="new". So you need to check all entrypoints that you call and even if its necessary/correct to call them all at the same time - and see what values they get received and what they then do - i cant help much with that without seeing more of the actual code.

                  Comment

                  Working...