EN VI

PHP variable can not get HTML option value instantly?

2024-03-16 22:30:05
PHP variable can not get HTML option value instantly

Try building a website that contains add product function with PHP code. Say we are adding a phone product, category will be Mobile Phones and the subcategory can be Samsung or iPhone. Another example would be Cars - Tesla or Toyota.

Problem facing is the php variable can't get the option value. Example: I selected the category, the subcategory option for the category can't refresh instantly like live. The way to get the subcategory option is SEARCH ALL from the category TABLE and get the subcategory that have the same SELECTED category ID. But the subcategory option can't refresh when I change the value of category ID because php is a server-side code.

I did try ajax and URL parameter but this is already inside a form and these two way need GET and POST, I don't think nesting these 2 form is a good idea. Cookie only works after I reload the page so that the php code can catch the cookie value.(Or it can, but im totally a newbie to cookie so idk). Anyone other way to let the php variable get the html option value in this case?

php

$x = $_COOKIE['scid'];
$c = getByID("scategory",$x);

Script

$('.categoryid').change(function(){
    $('#tajax').click(function(){
        var q = $('.categoryid').val();
        console.log(q);
        window.history.replaceState(null, null, "?cid="+q);
        document.cookie = "scid="+q;
    });
});

For your better understanding.
HTML category
HTML sub category
PHP structure

What I try
Category code
Sub Category code
Function Code

Form is here for the add product button on html

Solution:

You can do it like this.

First, in your frontend, change your change event listener for your #categoryid. Below is one suggestion (I'm using query parameters, and not a cookie).

$('.categoryid').on('change',function() {
    let catId = $(this).val();
    let subcategory = $('.scid');
    let options = '';
    
    $.ajax({
        url: 'your-subcategory-script.php',
        data: {'catId':catId},
        type: 'POST',
        dataType: 'json', // expected response is in json format
        beforeSend: function() {
            // whatever you need to do
            // before the ajax - disable a btn, etc
            // you can omit this entire part
            // if you don't need to do anything
        },
        success: function(data) {
            if(data.error) {
                alert(data.message);
            } else {
                // we're clearing the current subcategories
                subcategory.html('');

                // our options - subcategories - are within data.message
                // e.g data.message = [{1:"tesla",15:"samsung",....}]
                $.each(data.message, function(key,value){
                    options += `<option value="${key}">${value}</option>`;
                });

                subcategory.append(options);
            }
        },
        error: function(desc,err) {
            alert(`Error: ${JSON.stringify(err)}, desc: ${JSON.stringify(desc)}`);
        }
    });
});

Then, in your backend - your-subcategory-script.php - do something like the following.

<?php
// Include your DB connection file, and your functions
include 'your-connection.php';
include 'your-functions-file.php';

/*
Optional verification with cookies, etc
to prevent the script from being called
by unauthorized users should be placed
here. I'll leave this part to you
*/

// I'm doing this because the ID should be a positive integer
$catId = isset($_POST['catId']) ? (int)$_POST['catId'] : 0;
if($catId < 1) {
    // notify the user about the error - this could be a function as it will
    // be used later on
    echo json_encode(['error' => true, 'message' => 'Invalid category!']);
    die();
}

// I'm using your function, BUT, please consider 
// using prepared queries, to avoid SQL injection
$subcategories = getByID('subcategories',$catId);

// Did the query fail?
if(!$subcategories) {
    echo json_encode(['error' => true, 'message' => 'Error retrieving subcategories!']);
    die();
}

// Are there no results?
if(mysqli_num_rows($subcategories)) {
    echo json_encode(['error' => true, 'message' => 'No subcategories found!']);
    die();
}

$results = [];
foreach($subcategories as $row) {
    $id = $row['id'];
    $type = $row['type'];
    $results[$id] = $type;
}

// I'm using just one flag for the JSON
// more here (section flags): https://www.php.net/manual/en/function.json-encode.php
echo json_encode(["error" => false, "message" => $results],JSON_UNESCAPED_UNICODE);
?>
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login