Josh Connerty 20 Unverified User

Thanks for the reply.
I'm not actually looking to build gutenberg blocks. I'm trying to understand how from a React perspective how it actually functions.
Sorry for the confusion.
Josh

Josh Connerty 20 Unverified User

Hello All,

I have a question regarding Gutenberg React. I'm familiar with React which is what leads me to not understanding how the process works.

React can only render JSX but Gutenberg seems to render HTML (presumably by setting inner html dangerously), however it also adds event listeners to the newly rendered "block". How does it do this?

Many Thanks,
Josh

Josh Connerty 20 Unverified User

Glad to hear it :)

Josh Connerty 20 Unverified User

Form:

<form id="myform" method="post" action="">
<input type="checkbox" class="ids" name="ids[]" value="1">
<input type="checkbox" class="ids" name="ids[]" value="2">
<input type="checkbox" class="ids" name="ids[]" value="3">
<input type="checkbox" class="ids" name="ids[]" value="4">
</form>

<div id="response"></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
 $(document).ready(function() {
     $('.ids').click(function() {
        var state = ($(this).is(':checked')) ? '1' : '0';
        var myobj = {}
        console.log($(this).serialize())
        $.ajax({
            url: "test.php",
            type: "post",
            data: $(this).serialize() + "&state=" + state
        }).done(function(data) {
            $('#response').html(data);
        });
    });
 });
</script>

Endpoint:

<?php

    if (isset($_POST['ids'])) {
        $id_value = $_POST['ids'];
        $state = (int)$_POST['state'];
        $sql_check = "UPDATE toggle SET status= '$state' WHERE id = '$state' ";
        $result_check = mysqli_query($conn,$sql_check);

        if($result_check){
            echo "sucess";
        } else{
            echo "failure";
        }
    }

?>
Josh Connerty 20 Unverified User

I tested this while in a meeting so fingers crossed it works for you:

<?php

$ip_ranges = "63.119.179.0/24, 23.119.180.0/24,154.119.181.0/24,193.119.182.0/24,133.119.183.0/24";
    function multiCidrToRange($cidrs)
    {
        $return_array = array();
        $cidrs = explode(",",str_replace(" ","",$cidrs));
        foreach($cidrs as $cidr)
        {
            $begin_end = explode("/",$cidr);
            $ip_exp = explode(".",$begin_end[0]);
            $range[0] = long2ip((ip2long($begin_end[0])) & ((-1 << (32 - (int)$begin_end[1]))));
            $range[1] = long2ip((ip2long($range[0])) + pow(2, (32 - (int)$begin_end[1])) - 1);
            unset($ip_exp[3]);
            $ip_prefix = implode(".",$ip_exp);
            $count = str_replace($ip_prefix . ".","",$range[0]);
            $ncount = 0;
            while( $count <= (str_replace($ip_prefix,"",$range[0]) + str_replace($ip_prefix . ".","",$range[1])) )
            {
                $return_array[] = $ip_prefix . "." . $count;
                $count++;
                $ncount++;
            }
            $begin_end = false;
            $ip_exp = false;
            $range = false;
            $ip_prefix = false;
            $count = false;
        }
        return $return_array;
    }

    var_dump(multiCidrToRange($ip_ranges));

?>
matei_ commented: Thank you very much! You saved me. It works in the way I want it to. +0
Josh Connerty 20 Unverified User

Got meetings for the next couple of hours. I'll post something as soon as I get chance

Josh Connerty 20 Unverified User

OH I see. That won't work then. Let me look up the calculations for the range

matei_ commented: Any updates? Can't we work something from cidrToRange function? +0
Josh Connerty 20 Unverified User

You could create a custom plugin for this. Would need to know more about where the files are hosted and where you retrieve the student number from.

Josh Connerty 20 Unverified User

So if you var_dump the text field and it's an empty array it implies it has nothing in the textfield. I need to see more of how it's implemented

matei_ commented: I solved the error, but the problem is now that I get only the IPs only to .24 and I should get until .255 +0
Josh Connerty 20 Unverified User

What does $pluginData hold? if you pass a list of comma separated range values to the function it will return an array of ip addresses from all of the ranges

matei_ commented: The $pluginData -> ipAddresses is the actual text area that holds all the CIDR ranges. +0
Josh Connerty 20 Unverified User

That's becuase the trigger is bound to the FORM element so when you use $(this) a little later on, you're refering to the form and not the checkbox.

The form only send the ID's of checkboxes that have been checked if this helps? Alternatively you need to bind the trigger on the checkbox and use it's state to update a hidden field that can contain the states and then serialized with the form data

KnowledgeMan commented: Thanks. I kinda understand what you mean. Can you please provide an example or guide on how to do it? +0
Josh Connerty 20 Unverified User

I adapted you ajax method to this and it works:

    $.ajax({
        url: "test.php",
        type: "post",
        data: $(this).serialize() + "&state=" + state
    }).done(function(data) {
        $('#response').html(data);
    });
KnowledgeMan commented: Thank you it is showing success but the database is not getting updated. I think the issue with state: var state = ($(this).is(':checked')) ? '1' : '0 +0
Josh Connerty 20 Unverified User

$state = (int)$_POST['state']; Refers to a post variable that has not been passed

KnowledgeMan commented: So how do I resolve it? Sorry for asking again I am new to programming +0
Josh Connerty 20 Unverified User

Did you put it outside of this logic?

var_dump($_POST); // Here
if (isset($_POST['ids'])) {
       $id_value = $_POST['ids'];
       $state = (int)$_POST['state'];

        foreach($id_value as $check) {

          $sql_check = "UPDATE toggle SET status= '$state' WHERE id = '$check' ";
          $result_check = mysqli_query($conn,$sql_check);

         if($result_check){
             echo "sucess";
         }else{
             echo "failure";
         }
        }
KnowledgeMan commented: No sorry my mistake, yeah now it generating array(1) { ["ids"]=> array(1) { [0]=> string(1) "1" } } when I click the first checkbox +0
Josh Connerty 20 Unverified User

Try var dumping the $_POST object

var_dump($_POST);

If this returns nothing then you know there is an issue with the reference back to the data that was sent

KnowledgeMan commented: Yes it does return nothing +0
Josh Connerty 20 Unverified User

Yep so what does the response on the "Network" tab say?

You should be able to click the request and it'll open another panel with headers and you want the one which reads "Preview" or "Response".

This is the data that your endpoint returns

KnowledgeMan commented: Yes so on request I get this value ids[]:[..] 0:"1",1:"2" and for reponse nothing +0
Josh Connerty 20 Unverified User

You can use console.log() within the trigger call

$('#myform').click(function() {
    console.log("Click event triggered");

in order to see if the trigger is ran through the console. If you click the "Network" tab in the "Inspect" you can see if the XHR/AJAX request is being sent.

KnowledgeMan commented: Ok, I am getting the message "Click event triggered", status code "200". So the form is getting submit +0
Josh Connerty 20 Unverified User

Something like that

<?php

    $ip_ranges = "32.89.178.30/24, 63.119.179.0/24, 23.119.180.0/24,154.119.181.0/24,193.119.182.0/24,133.119.183.0/24";
    function multiCidrToRange($cidrs)
    {
        $return_array = array();
        $cidrs = explode(",",str_replace(" ","",$cidrs));
        foreach($cidrs as $cidr)
        {
            $begin_end = explode("/",$cidr);
            $ip_exp = explode(".",$begin_end[0]);
            $range[] = $begin_end[1];
            $range[] = $ip_exp[3];
            unset($ip_exp[3]);
            $ip_prefix = implode(".",$ip_exp);
            $count = $range[1];
            while( $count <= ($range[0] + $range[1]) )
            {
                $return_array[] = $ip_prefix . "." . $count;
                if($count == 255)
                { exit; }
                $count++;
            }
            $begin_end = false;
            $ip_exp = false;
            $range = false;
            $ip_prefix = false;
            $count = false;
        }
        return $return_array;
    }

    var_dump(multiCidrToRange($ip_ranges));

?>
matei_ commented: Using "var_dump($pluginData -> ipAddresses)" it shows me this: "array(0) { }"... +0
Josh Connerty 20 Unverified User

Give me an 20 mins and I'll write something for you. Just got to finish what I'm on and push to live

matei_ commented: Sure, thank you very much! +0
Josh Connerty 20 Unverified User

$cidrs is not defined yet. This would be for instance explode(",",$my_form_field) passing an array of ranges

matei_ commented: I get only the CIDR, e.g.: 88.39.88.0/24, 89.33.88.0/24 etc.. I want to retrieve a list with IPs from all the CIDRs that I have in my textarea. +0
Josh Connerty 20 Unverified User

What results have you had so far?

KnowledgeMan commented: Thanks for the relpy. Well I get no errors on the page and nothing in inspector as well. +0
Josh Connerty 20 Unverified User
function cidrToRange($cidr) {
    $range = array();
    $split = explode('/', $cidr);

    if(!empty($split[0]) && is_scalar($split[1]) && filter_var($split[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $rangeStart = ip2long($split[0]) & ((-1 << (32 - (int) $split[1])));
        $rangeStartIP = long2ip($rangeStart);
        $rangeEnd = ip2long($rangeStartIP) + pow(2, (32 - (int) $split[1])) - 1;

        for($i = $rangeStart; $i <= $rangeEnd; $i ++) {
            $range[] = long2ip($i);
        }
        return $range;
    } else {
        return $cidr;
    }
}

$ip_arr = array();

foreach($cidrs as $cidr)
{
    array_merge(cidrToRange($cidr),$ip_arr);
}
echo '<ul>';
foreach($ip_arr as $ip)
{
    echo '<li>'.$ip.'</li>';
}
echo '</ul>';
matei_ commented: "Notice: Undefined variable: cidrs on line 41 && Warning: Invalid argument supplied for" - Line 41" foreach($cidrs as $cidr) +0
Josh Connerty 20 Unverified User

If theres discrepencies with spaces etc. I'd consider

$ips = explode(",",str_replace(" ","",$field)); // Gives IP's
foreach($ips as $key => $ip) {
    $range = explode("/",$ip);
    $ips[$key] = $range;
}

which will strip spaces out and then create an array of ip addresses

[0] => [[0] => 192.168.0.0, [1] => 30]
[1] => [[0] => 192.168.10.0, [1] => 10]
matei_ commented: Your function works as you said, but what I am trying to do is to retrieve a full list with IPs from the CIDR ranges that I have. +0
Josh Connerty 20 Unverified User

Because React does not carry out a page refresh the cookie storage that React has access to is outdated.

The best method for React & PHP authentication is to use token authentication:
Click Here

Josh Connerty 20 Unverified User

What did you change?

Josh Connerty 20 Unverified User

The usual way of achieving this functionality is to store a reference to the current player through a token/cookie and use that to refer to the related row in the database. For example:

  ________players________
  id  |    name    | gold
  25  | "Player 1" |  0

Being the database structure, if I wish to update "Player 1"'s gold count I would take the cookie value $_COOKIE['player_id'] to update the row in the database

<?php

    $player_id = $_COOKIE['player_id'];
    $new_gold = $old_gold + 2;

    $sql = mysqli_connect(HOST,USERNAME,PASSWORD);
    mysqli_select_db(DATABASE,$sql);

    $sql->query("UPDATE `players` SET `gold` = '" . $new_gold . "' WHERE `id` = '" . $player_id . "'");

?>

This poses a number of security concerns but the principle is the same.

I hope this is of some help.

Josh Connerty 20 Unverified User

This is quite an ambiguous question. Can you elaborate on exactly what you're trying to achieve?

Josh Connerty 20 Unverified User

From what I can see, you're short a closing <div> tag.

Josh Connerty 20 Unverified User

I don't have access to my suppliers database however each part will be populated from their website listing of that product, so when I add that product to the database I will do so with the website address of that part on my suppliers website. Periodically a CRONJOB will run to keep the table updated with price fluctuations. I'd prefer to have them stored in my database then have to reference my suppliers website every time a users goes to select a repair. Saves page load time.

The issues I am having is how to structure my tables. I get how I can use the information and what not I'm just strugling to figure out how many tables and their relationships to one another.

Thanks for the swift replies.

Josh Connerty 20 Unverified User

Like @minitauros said, change the header("Location: $file \r\n"); line with something like: echo '<script type="text/javascript">window.open(' . $file . ')</script>';

See if that works.