Hi,
I tried to create four dropdown lists as main category and sub categories which depends on the above list
I tried to run it on my local host and it works fine but when i want to insert the value of the second list in my database it doesn't work
I did my coding based on the link below.
Click Here
This is my main code that im working on:

That part has to take the value from the database for each changement by calling loadsubcat.php

$(document).ready(function() {

    $("#parent_cat").change(function() {
        $(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
        $.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
            $("#sub_cat").html(data);
            $('#loader').slideUp(200, function() {
                $(this).remove();
            });
        }); 
    });

});
</script>

Here is the loadsubcat.php

<?php 
include('config.php'); 
//require 'database.php';

 $parent_cat = $_GET['parent_cat'];

//$pdo = Database::connect();
//$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = mysql_query("SELECT * FROM scorejour WHERE id_joursemaine = {$parent_cat}");
while($row = mysql_fetch_array($query)) {
    echo "<option value='$row[id_score]'>$row[score]</option>";

}
?>

Here is the get method that i use:

<?php 
    include('config.php'); 
require 'database.php';
    mysql_query("set NAMES utf8");
$query_parent = mysql_query("SELECT * FROM joursemaine") or die("Query failed: ".mysql_error());?> <form style="margin-left:400px;" class="form-horizontal" action="updateChauf2.php?id=<?php echo $id?>" method="post"> <div class="control-group"> <label style="color:white;" for="category">parent_cat:</label> <select name="parent_cat" id="parent_cat" onchange="myFunction()"> <?php while($row = mysql_fetch_array($query_parent)): ?> <option value="<?php echo $row['id_joursemaine']; ?>"><?php echo $row['joursemaine']; ?></option> <?php endwhile; ?> </select> <br/><br/> </div> <div class="control-group"> <label style="color:white;" for="sub_cat">الرصيد المضاف</label> <select  id="sub_cat" onchange="changeTest()" name="sub_cat"></select> </div> </form>

can you help me please to solve my problem

Recommended Answers

All 5 Replies

Member Avatar for diafol

This code looks very confused. It seems you started with PDO then changed your mind. The DB connection data I assume is in database.php, is it now in config.php?

IMPT

Using mysql_* functions is bad as they've been deprecated.

This will not work anyway:

echo "<option value='$row[id_score]'>$row[score]</option>";

You have to enclose array item vars in braces and enclose keys in quotes:

echo "<option value='{$row['id_score']}'>{$row['score']}</option>";

End IMPT

Aside (not v important)

Include and Require have the same pattern. You do not really need the brackets, so you could just write:

include 'config.php'; 
require 'database.php';

You do not need braces around simple vars:

$query = mysql_query("SELECT * FROM scorejour WHERE id_joursemaine = {$parent_cat}");

Could just be:

$query = mysql_query("SELECT * FROM scorejour WHERE id_joursemaine = $parent_cat");

End Aside

IMPT

HOWEVER - you are placing raw input data directly into the query. This is very very bad. You have just opened yourself to SQL injection. Fatal. You must sanitize with mysql_real_escape_string() if you insist on using prehistoric code. If you want to write good code on the other hand, use a prepared statement (PDO or mysqli).

End IMPT

Aside

You are using jQuery, yet you are using inline onChange. Why not just have an event handler?

$('#sub_cat').change(function(){
    ...
});

No need for any js attributes

You are using inline styling:

<form style="margin-left:400px;"

Get rid of this and use CSS files. Inline styling cannot be overridden very easily - so you'd probably have to change the markup to change the styling. Try to keep them all separate.

You're using inline PHP:

<?php while($row = mysql_fetch_array($query_parent)): ?> <option value="<?php echo $row['id_joursemaine']; ?>"><?php echo $row['joursemaine']; ?></option> <?php endwhile; ?>

Again, very difficult to maintain this code - especially if it isn't indented. I'll give you the benefit of the doubt here as there have been problems with the formatting with this editor, but if the lack of indentation is deliberate (or due to laziness), please give this attention as it renders the snippet almost unreadable.

The PHP code above could have been run above the DTD and stored in a variable, e.g. $options. All you'd need to do then in the middle of your markup would be to echo this out:

<select name="parent_cat" id="parent_cat" onchange="myFunction()">
    <?=$options?>
</select>

Although, again - no need to run on have inline onChange - best us an event handler.

End Aside

I'm sure there are other things, but those stood out.

with the code I posted the contents of the second list is displayed in the form, but when I want to insert the new value that appears in my database I did not find it, that's my problem but it seems that you have not responded to my question

my problem is how to recover the value of sub_cat

Member Avatar for diafol

that's my problem but it seems that you have not responded to my question

There were many issues with your code/markup. I was merely letting you know about them. You do not have to take any notice of them. In fact, now that I think of it, I may have mentioned some of these before - so OK, ignore them.

Have you used

console.log(data); 

to show what exactly is returned?

You could return the data from php as json:

$sql ="SELECT * FROM scorejour WHERE id_joursemaine = $parent_cat}";
$query  = mysql_query($sql);
$numRecs = mysql_num_rows($query);
$rows = '';
while($row = mysql_fetch_assoc($query)) $rows .=  "<option value='{$row['id_joursemaine']}'>{$row['joursemaine']}</option>";
echo json_encode(array('sql'=>$sql, 'numrows'=> $numRecs, 'options'=>$rows);

Then in your Ajax:

$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
        console.log('SQL: ' + data.sql);
        console.log('Num Rows: ' + data.numrows);
        console.log('Options: ' + data.options);

        $("#sub_cat").html(data.options);
        $('#loader').slideUp(200, function() {
            $(this).remove();
        });
}); 

Ideally the same PHP script would serve to get the default data on page load as well as to return data via Ajax.

Member Avatar for diafol

that's my problem but it seems that you have not responded to my question

It seems you have not responded to my suggestion. Heh heh

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.