PHP Script help and BUG FIXES

Is there anyone here willing to help me troubleshoot my PHP scripting. I have a php code that is now using ajax ( and json ) to query an mssql database for information to be displayed on a html ( PHP ) page and I am having trouble getting certain parts of the code to work and do the things I am trying to do. I have tried a lot to fix these issues and get this working but everytime I do so it doesn’t seem to resolve or help get the parts of the script to work as they should. Anyone have some time talk talk and take a look I would really be very appreciative.

Thanks

You would need to post all the code necessary to reproduce the problem and the symptom or error you are getting.

Is there a way I can share this directly with a person that is interested in taking a look at it ? Its a lot of files and code to get my project all working as one file …

You can post in the forum or pastbin/gethub or similar.

For a larger codebase, go for a Github repository.
You can have private repositories there as well included in the free plan.
You would then push all your files to your repo and share it with the people you want.

For any specific issues with selected files / workflows and single problem, the forum might be the better option.

Either way, your code (plus a much better description of what is happening vs. what is expected) will be required.

Thank you so I added the files to a repo … how do I share them and the issues I am having now with everyone ? I really could use the help I have tried numerous times to fix some of the issues and can’t seem to get it working properly

You need to post a link to the code. You would need to post the errors or symptoms you are getting when you run the code.

OK Thank you … so this is a photo of one of the parts of code I am having issues with :


the Price you charge and price with Tax are dynamic and ( ajax / json ) and they update each other when one is updated then the other does either adding or subtracting the tax depending on the field you are updating. Right now if I change the price of either they update to match pricing and do not add or remove the tax ( that is the combined rate of all the tax rates selected to the right of the values )

here is the github for the files : the files involved are Index7.php ( fetch_data.php / scripts2a and scripts24 )

This makes little sense. What is the user entered/selected values? What is the calculated value? For a specific entered/selected value, what is the expected result and what result do you get?

so the price you charge comes from the database … then the tax rates in the database are added all together ( Tax - Tax6 plus any other taxes if active ) then that total tax is added to the value of price you charge to get the price you charge with tax … so say the price you charge is 1.00 and the tax rate is a total of 4% then the price with tax would be 1.04 and in reverse if you entered as the user 1.04 in the price with tax field the calculations are done in reverse ( extracting the tax ) to get the price as 1.00 - that would be the expected result ( right now since it was converted to AJAX /JSON ) the price you charge is updated ( by the user to say 1.00 and the price with tax also updates to 1.00 and in reverse the same happens ) somehow the totalTaxRate is not being added to or subtracted from the fields needed. If you need more clarification please let me know


this is the fields when acquired from the database ( thru the ajax query ) then when the fields are updated by the user in the form … you can see what happens here the values reflect each other like a mirror :

5.00 adding 4% tax should update the field price with tax to 5.20 not 5.00 - I hope this better explains

At the point in time when the priceChargeInput or priceTaxInput input event occurs, the existing totalTaxRate variable is empty (the code setting its value is executed when the js loads, but the field doesn’t have a value at that time), so the calculations use zero for the totalTaxRate. The solution is to get the totalTaxRate value inside each of the priceChargeInput or priceTaxInput input event handlers.

There is a lot of unnecessary and inconsistent code, mostly in the database specific code. Here are some recommendations -

  1. You are using exceptions for database statement errors - connection, query, prepare, and execute. The only time you should catch and handle database exceptions in your code are for user recoverable errors, such as when inserting/updating duplicate user submitted data. For all other query errors, all other type of queries, and for the connection, simply do nothing in your code and let php catch and handle any database exception, where php will use its error related settings to control what happens with the raw database error information, via an uncaught exception error (database statement errors will ‘automatically’ get displayed/logged the same as php errors.)
  2. If you set the default fetch mode to assoc when you make the database connection, you won’t need to specify it in each fetch statement.
  3. Only prepare and execute an actual prepared query that has values being supplied to it. For queries that don’t have any values being supplied, simply use the ->query() method. You have cases doing this, and using prepare/execute.
  4. For actual prepared queries, forget about any bindValue/bindParam calls. Simply supply an array of the data values to the ->execute([…]) call. Again, you have some cases doing this, and some using bindValue/bindParam calls.
  5. Most of the code in scripts2a.js is just setting up fields based on the response values, written out for every field. I recommend that you instead send the data as an array/object with the main index being the ‘type’ of processing needed to set the field, e.g. val, html, prop(erty), then with a sub-array of data for each type. The key in the sub-array would the id and the value would be the existing data. You would then use a switch/case statement to determine the ‘type’ of processing, then loop over the sub-arrays of keys/values to set up the fields.

Not really sure what all that means but if you could make the changes and share them so I can see how it works I would be most grateful. I will then learn from what you share

Thank You for your input

// delete the following line from here -
const totalTaxRate = parseFloat(document.getElementById('totalTaxAmount').value) || 0;

// When priceCharge is updated, calculate price with tax
priceChargeInput.addEventListener('input', () => {
    const priceCharge = parseFloat(priceChargeInput.value) || 0;
    // add it to here -
    const totalTaxRate = parseFloat(document.getElementById('totalTaxAmount').value) || 0;
    const priceWithTax = priceCharge * (1 + totalTaxRate);
    priceTaxInput.value = priceWithTax.toFixed(2); // Show total with tax
});

// When priceTax is updated, remove tax to get base price
priceTaxInput.addEventListener('input', () => {
    const priceWithTax = parseFloat(priceTaxInput.value) || 0;
    // add it to here -
    const totalTaxRate = parseFloat(document.getElementById('totalTaxAmount').value) || 0;
    const priceCharge = priceWithTax / (1 + totalTaxRate);
    priceChargeInput.value = priceCharge.toFixed(5); // Show base price
});

still is not adding the tax to the price or removing it either … when I type in a new value it makes both fields the same … see photo …

not sure why but I think the totalTaxRate is not being calculated and therefore is acting as a 0 ( zero ) hence why the values remain the same

this is the code in the fetch_data.php file from my repository that is getting the tax fields and adding them together and should be passed as the value that needs to be used :

// Fetch tax rates
    $taxQuery = "SELECT Tax1_Rate, Tax2_Rate, Tax3_Rate, Tax4_Rate, Tax5_Rate, Tax6_Rate FROM Tax_Rate";
    $taxStmt = $conn->query($taxQuery);
    $taxRates = $taxStmt->fetch(PDO::FETCH_ASSOC);

    // Calculate total tax amount
    $price = floatval($result['Price'] ?? 0);
    $totalTaxAmount = 0;
    $TaxTotalAmt = 0;
    $appliedTaxes = [];

    foreach ($taxRates as $key => $value) {
        if (strpos($key, 'Rate') !== false && is_numeric($value)) {
            $taxIndex = substr($key, 3, 1);
            $taxApplicable = isset($result["Tax_$taxIndex"]) ? (bool)$result["Tax_$taxIndex"] : false;
            if ($taxApplicable) {
                $TaxTotalAmt += floatval($value);
                $totalTaxAmount += round($price * $value, 2);
                $appliedTaxes[] = "Tax $taxIndex";
            }
        }
    }

    $result['TaxTotalAmt'] = number_format($TaxTotalAmt, 2, '.', '');
    $result['PriceWithTax'] = number_format($price + $totalTaxAmount, 2, '.', '');
    $result['TaxesApplied'] = !empty($appliedTaxes) ? implode(", ", $appliedTaxes) : "No Taxes";

Did you force a reload of the page in your browser so that the changes made to the javascript got read by the browser?

Yes and this does not work ? I think the value for the totalTaxRate is not being aquired somehow

For the fix I came up with, I created a fetch_data.php file that returns fake data for testing.

I recommend that you temporarily change the totalTaxAmount hidden form field to type='text' so that it gets displayed on the web page.

Sponsor our Newsletter | Privacy Policy | Terms of Service