Dealing with Laravel and AJAX - Issue with Loading DIV

I find myself in a perplexing situation. Despite not encountering any errors in my apache logs or browser (chrome), I am faced with an issue that has left me baffled.

On a specific page (localhost/admin/networks), I can click on an item from a database-generated list, which opens a CSS popup div allowing me to add a database entry. This functionality works seamlessly. However, the problem arises when using a live search box to input a partial network and see the results. Upon clicking one of the displayed results, the CSS popup appears empty, almost as if it fails to locate the necessary file - even though everything functions perfectly before conducting a search. At one point, this feature was working well, but after adding a route prefix, I suspect the problem lies in the interaction between my JS file and route prefixes. Unfortunately, I'm uncertain where to start investigating, as the functionality breaks only post-search.

Constructive criticism is welcome. I acknowledge that I am still learning, so any feedback on how I can improve is highly appreciated!

Edit 2:

Narrowing down the issue, I have identified the third argument of the .load method in my JavaScript file as the culprit. After reintroducing my route prefixes, here is a snippet of my current js.js file.

current js.js file

var baseURL = "https://localhost/";
var admURL = "https://localhost/admin/";

//DIV View Toggle
function toggle(div_id)
{
    var el = document.getElementById(div_id);
    if(el.style.display == 'none')
    {
        el.style.display = 'block';
    }
    else
    {
        el.style.display = 'none';
    }
}

function togglePopBox(windowname)
{    
    toggle('popBox');
    toggle('popBackground');
}
$(document).ready(function()
{
    // Add Networks Button
    $("#addNet").on('click', function()
    {
        $("#popBox").load(admURL + 'addnetwork', setupInternalPopBoxNetworks);
    });

    // Function to handle popup closure
    function setupInternalPopBoxNetworks()
    {
        $("#cancelNet").on('click', function()
        {
            $("#popBox").load(baseURL + 'blank', setupInternalPopBoxNetworks);
        });
    }

    // Network Search Function
    $('#searchNetworkID').keyup(function(e){
        $("#networkBox").load(baseURL + 'network.search' + '?networkSearch=' + $('#searchNetworkID').val());
    });

    // Add Subnets Button
    $(".addSubnet").on('click', function()
    {
        var netID = $(this).attr('id');
        $("#popBox").load(admURL + 'addsubnet' + '?network=' + netID, setupInternalPopBoxNetworks);
    });

    // View Subnets Button
    $(".viewSubnet").on('click', function()
    {
        var netID = $(this).attr('id');
        $("#subnetBox").load(baseURL + 'viewsubnet' + '?network=' + netID, setupInternalPopBoxNetworks);
    });

    // Subnet Search
    $('#searchSubnetID').keyup(function(e){
        $("#subnetBox").load(baseURL + 'subnet.search' + '?subnetSearch=' + $('#searchSubnetID').val());
    });

});

Edit 1:

In an attempt to resolve the issue, I removed the route group I previously defined. Reverting back to a state before creating another popUp DIV, suspicion arose regarding a potential conflict. Although unsure about the root cause, further exploration led me to believe that the issue resides within my js.js file.

The concern seems to be related to async operations since I am utilizing the http://api.jquery.com/load/ method. Modifying the subnets button code below resulted in loading a popup successfully. However, it continued to display the previously loaded content because the div did not reset upon closure.

Progress is evident, yet a significant piece of the puzzle remains elusive.

$(".addSubnet").on('click', function()
{
    var netID = $(this).attr('id');
    $("#popBox").load(baseURL + 'addsubnet' + '?network=' + netID);
});

routes.php

# Route Prefix for administration
Route::group(array('prefix' => 'admin', 'before' => 'auth'), function()
{
    # Network Management Page - Add, Edit, Delete
    Route::get('networks', function()
    {
        $userGroups = implode(',', Auth::user()->groups);
        $userGroups = ''.$userGroups.'';
        $userGroups = explode(",", $userGroups);
        $CanIVisit = Link::whereIn('linkGroup', $userGroups)->count();
        if($CanIVisit > 0){
            return View::make('networks');
        }else{
            return Redirect::intended('landing');
        }
    });

    # Adds a Network
    Route::get('addnetwork', array(
        'as' => 'network.add',
        'uses' => 'NetworksController@add'
    ));

    # POSTS added network data
    Route::post('networks', array('before' => 'csrf', 
        'as' => 'network.create',
        'uses' => 'NetworksController@create'
    ));

    # Adds subnet to specified network
    Route::get('addsubnet', array(
        'as' => 'subnet.add',
        'uses' => 'NetworksController@addSubnet'
    ));

    # POSTS subnet information to database
    Route::post('subnets', array('before' => 'csrf', 
        'as' => 'subnet.create',
        'uses' => 'NetworksController@createSubnet'
    ));
});

NetworksController.php

public function search()
{
$lineNumber = 1;
$network = Input::get('networkSearch');
$networks = IPv4Network::where('easyNet', 'LIKE', "$network%")
    ->orWhere('route', 'LIKE', "$network%")
    ->orderBy('network', 'asc')
    ->get();
$networksCount = IPv4Network::where('easyNet', 'LIKE', "$network%")
    ->orWhere('route', 'LIKE', "$network%")
    ->orderBy('network', 'asc')
    ->count();

if($networksCount == 0){
    echo("No networks matched the criteria entered.");
}else{
    echo("<div id=\"networkListHead\">");
    echo("<div class=\"networkID\">Network</div>");
    echo("<div class=\"networkMask\">Mask</div>");
    echo("<div class=\"networkPath\">Route Path</div>");
    echo("<div class=\"networkSubnets\">Subnets</div>");
    echo("<div class=\"networkHosts\">Hosts</div>");
    echo("<div class=\"networkMaxHosts\">Max Hosts</div>");
    echo("</div>");

    foreach($networks as $foundNet){
        $findSubnets = IPv4Subnets::where('networkID', '=', $foundNet->networkID)
            ->get();
        $findSubnetsCount = IPv4Subnets::where('networkID', '=', $foundNet->networkID)
            ->count();


        $mask = (32 - $foundNet->mask);
        $MaxHosts = (pow(2, $mask) - 2);

        if($lineNumber == 1){
            echo("<div class=\"networkListA\">");
            echo("<div class=\"networkID\"><a href=\"#\" onclick=\"togglePopBox('popBox')\" class=\"addSubnet\" id=\"{$foundNet->networkID}\">".long2ip($foundNet->network)."</a></div>");
            echo("<div class=\"networkMask\">{$foundNet->mask}</div>");
            echo("<div class=\"networkPath\">{$foundNet->route}</div>");
            echo("<div class=\"networkSubnets\"><a href=\"#\" class=\"viewSubnet\" id=\"{$foundNet->networkID}\">{$findSubnetsCount}</a></div>");
            echo("<div class=\"networkHosts\">");
            if($findSubnetsCount == 0){
                echo("0");
            }else{
                $hostCount = IPv4Hosts::all()
                    ->count();

                if($hostCount == 0){
                    echo("0");
                }else{
                    echo $hostCount;
                }
            }
            echo("</div>");
            echo("<div class=\"networkMaxHosts\">");
            echo $MaxHosts;
            echo("</div>");
            echo("</div>");
            $lineNumber = 2;
        }else{
            echo("<div class=\"networkListB\">");
            echo("<div class=\"networkID\"><a href=\"#\" onclick=\"togglePopBox('popBox')\" class=\"addSubnet\" id=\"{$foundNet->networkID}\">".long2ip($foundNet->network)."</a></div>");
            echo("<div class=\"networkMask\">{$foundNet->mask}</div>");
            echo("<div class=\"networkPath\">{$foundNet->route}</div>");
            echo("<div class=\"networkSubnets\"><a href=\"#\" onclick=\"togglePopBox('popBox')\" class=\"viewSubnet\" id=\"{$foundNet->networkID}\">{$findSubnetsCount}</a></div>");
            echo("<div class=\"networkHosts\">");
            if($findSubnetsCount == 0){
                echo("0");
            }else{
                $hostCount = IPv4Hosts::all()
                    ->count();

                if($hostCount == 0){
                    echo("0");
                }else{
                    echo $hostCount;
                }
            }
            echo("</div>");
            echo("<div class=\"networkMaxHosts\">");
            echo $MaxHosts;
            echo("</div>");
            echo("</div>");
            $lineNumber = 1;
        }
    }
}
}

js.js

var baseURL = "https://localhost/";
var admURL = "https://localhost/admin/";

// DIV View Toggle

function toggle(div_id)
{
    var el = document.getElementById(div_id);
    if(el.style.display == 'none')
    {
        el.style.display = 'block';
    }
    else
    {
        el.style.display = 'none';
    }
}

function togglePopBox(windowname)
{
    toggle('popBox');
    toggle('popBackground');
}

$(document).ready(function()
{
    // Add Subnets Button
    $(".addSubnet").on('click', function()
    {
        var netID = $(this).attr('id');
        $("#popBox").load(admURL + 'addsubnet' + '?network=' + netID, setupInternalPopBoxNetworks);
    }); 

    // Kills popup
    function setupInternalPopBoxNetworks()
    {
        $("#cancelNet").on('click', function()
        {
            $("#popBox").load(baseURL + 'blank', setupInternalPopBoxNetworks);
        });
    }

    // Network Search Function
    $('#searchNetworkID').keyup(function(e){
        $("#networkBox").load(baseURL + 'network.search' + '?networkSearch=' + $('#searchNetworkID').val());
    });
});

Answer №1

I managed to solve the problem after realizing that I was binding to a different element than intended in my page structure. By making some adjustments to my js.js file, I was able to resolve the issue successfully. Below is an outline of how my updated js file looks.

js.js

var baseURL = "https://localhost/";
var admURL = "https://localhost/admin/";
//DIV View Toggle

function toggle(div_id)
{
    var el = document.getElementById(div_id);
    if(el.style.display == 'none')
    {
        el.style.display = 'block';
    }
    else
    {
        el.style.display = 'none';
    }
}
function togglePopBox(windowname)
{
    toggle('popBox');
    toggle('popBackground');
}    
$(document).ready(function()
{
    //Add Networks Button
    $("#addNet").on('click', function()
    {
        $("#popBox").load(admURL + 'addnetwork', togglePopBox);
    });

    //Kills popup
    $("#popBox").on('click', '#cancelNet', function()
    {
        $("#popBox").load(baseURL + 'blank', togglePopBox);
    });

    //Network Search Function
    $('#superDuperBox').on('keyup', '#searchNetworkID', function(){
        $("#networkBox").load(baseURL + 'network.search' + '?networkSearch=' + $('#searchNetworkID').val(), null, null);
    });

    //Add Subnets Button
    $('#superDuperBox').on('click', '.addSubnet', function()
    {
        var netID = $(this).attr('id');
        $("#popBox").load(admURL + 'addsubnet' + '?network=' + netID, togglePopBox);
    });

    //View Subnets Button
    $('#superDuperBox').on('click', '.viewSubnet', function()
    {
        var netID = $(this).attr('id');
        $("#subnetBox").load(baseURL + 'viewsubnet' + '?network=' + netID);
    });

    //Subnet Search
    $('#superDuperBox').on('keyup', '#searchSubnetID',function(){
        $("#subnetBox").load(baseURL + 'subnet.search' + '?subnetSearch=' + $('#searchSubnetID').val());
    });

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connecting text boxes with JavaScript and JSON for gaming experience

I am currently developing a game and have encountered a slight issue. Currently, there is a text box in the game that prompts the player to run into it to progress to the next level. When the player does so, the next level loads seamlessly, which works per ...

Sending an array via formdata in an ajax request to an MVC action: A guide

When attempting to send an array along with form data to an action using an Ajax request, I am encountering an issue where both the form data and the array are being received empty. $scope.SubmitForm = function () { var sLangs = $("#supportedLangu ...

Issues with retrieving the scope attribute within a directive

I am currently facing an issue where I am unable to access the values stored in $scope.photoRes within my directive. When I use console.log(scope.photoRes) in the directive, it only displays an empty object. Here is the output from the console: Object {fi ...

Maximizing the efficiency of Java Script code

I am struggling with optimizing this JavaScript code that adds and removes classes based on the presence of a specific class in the next rows of a table. Can anyone provide some guidance on how to make this code more efficient? $(".showTR").click(functi ...

Troubleshooting issues with cross-domain jQuery ajax requests

Struggling with this code and unable to make it work. This call consistently returns a "Failed to load resource: the server responded with a status of 401 (Unauthorized)" error message. $('#btnZendesk').click(function () { $.ajax({ ...

Transfer the selected value from the initial dropdown menu to the second dropdown menu seamlessly without the need to

My website features a repair pricing calculator that allows users to select a brand from a dropdown menu and then choose the specific model from a second dropdown. Currently, after selecting an option from the first dropdown, the page reloads and passes th ...

Why does my ajax call always send a GET request instead of a POST?

$.ajax({ type:"post", url: server_url, dataType: "jsonp", jsonpCallback: callback, data:req_json, cache: false, timeout: 60000, success: succeeded, error: got_error }); I've ...

AngularJS url update event

In order to gather statistical data, I am interested in tracking how many times the URL has been changed. To achieve this, I have set up a counter that will increment each time the URL is modified. Does anyone have a solution for this? ...

Is there a way to shift a background image pattern?

After searching extensively, I came up empty-handed and am seeking guidance on how to achieve a specific effect. Specifically, I am in need of a JavaScript or jQuery script that can smoothly shift a background image to the right within a designated div con ...

Guide on centering an unfamiliar element in the viewport using HTML, CSS, and JavaScript

In the process of developing my VueJS project, I have successfully implemented a series of cards on the page. However, I am now facing a challenge - when a user selects one of these cards, I want it to move to the center of the screen while maintaining its ...

Generate a JSON (Jquery) structured table matrix outlining various roles and corresponding permissions such as read, write, delete, and write special

I would like to create a table matrix that displays roles and permissions (read, write, delete, write special) using jQuery with JSON data. The table should contain checkboxes for each permission type, and the checkboxes for read, write, delete, and write ...

Utilize the PHP variable HTTP_USER_AGENT to identify and analyze the user's browser

As I embark on creating a webpage, my goal is to have it display different content based on the user's browser. The SERVER [HTTP_USER_AGENT] variable initially seemed promising for this purpose, but upon inspecting the page in Chrome, I encountered: ...

Tips on utilizing CSS modules in React without changing class names

After starting to use css modules in my react project, I quickly realized the struggle of changing classnames to fit the requirements of css modules. For example, if we have a component using regular css: import React from 'react' import ". ...

Tips for implementing event handlers on dynamically generated li elements in VueJS

Creating multiple ul elements using v-for in the following way <div v-for="item in info"> <ul> <li><a>{{item.number}}</a></li> <li><a>{{item.alphabet}}</a></li> </ul> </div&g ...

How can we sort an array based on the inner HTML values of its children elements in JavaScript?

Can you arrange a JavaScript array based on the innerText values of its HTML elements? I am generating a div element (class="inbox" id="inbox${var}") with a number as its innerText, then adding all these divs to an array (numArr). I wan ...

A helpful guide on extracting JSON data using AJAX POST method within Django views

I am currently working on parsing JSON data within a Django view, however I have encountered an issue. Below is the code snippet that I am using: $(document).ready(function(){ $("#mySelect").change(function(){ selected = $("#mySelect option:s ...

Activating a link without clicking will not trigger any javascript functions

I have been attempting to display an image when I hover over a link, but for some reason, the .hover() event is not functioning as expected. Initially, I am just aiming to have an alert pop up. Once I have that working, I can proceed with fading elements i ...

PHP fails to retrieve data from a JavaScript Ajax function using the FormData object (specifically, when

I'm facing an issue where my file is not being detected when I send a FormData object using AJAX and PHP code. Both the `$_FILES` array and the `$_POST` array appear to be empty. However, the browser does send the file with the AJAX request. <inpu ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

Creating a dynamic cascading dropdown list with Vue.js: Step-by-step guide

I successfully implemented a dropdown list using Vue.js, but now I want to add another similar list. How can I set this up? Here are the codes for both dropdown lists: var addUserVue = new Vue({ el: "#app", data: { heading: "Vue Select Cas ...