Get GET variables from url using JavaScript jQuery Ask Question

I want to read out a GET variable from an url using jquery

The domain is displayed like this

http://example.com/p/kT2Rnu35

And the original is :

http://example.com/php/page.php?id=kT2Rnu35

I want to get that id using jQuery from the page with the domain http://example.com/p/kT2Rnu35

I’ve tried window.location and other functions i found on stack overflow but nothing worked. Is it because i’m changing the url using htaccess ?

Calling Javascript function defined in external file through PHP Ask Question

I have a web page on which i have a simple login form consisting of username and password text fields.

I validate the login form using javascript external file and if javascript code returns true, login form is submitted otherwise an error message is displayed via javascript function named displayErrorBlock() that i wrote.

If the form is submitted then using PHP, i verify username and password. If username/password combination is incorrect or doesn’t exists in database, i want to call the same javascript function (displayErrorBLock) from PHP code.

To do this, i echo this

else { // if username/password combination is incorrect
     echo '<script>displayErrorBlock("Incorrect Username/Password")</script>';
}

but this gives me displayErrorBLock undefined error because javascript is loaded at the end of the body tag of my web page.

Question

How can i call javascript function (displayErrorBlock) that is defined in an external file ?

This is the displayErrorBlock function defined in an external js file

function displayErrorBlock(errorMsg) {
    'use strict';
    let errorBlock = document.querySelector('.error-msg-block');
    errorBlock.style.display = 'block';
    errorBlock.firstElementChild.textContent = errorMsg;

    setTimeout(function () {
        errorBlock.style.height = '48px';
    }, 10);
}

Edit

Here my entire web page

<?php

    require 'DbConnection.php';

    // if login button is clicked
    if(isset($_POST['login-btn'])) {
        $username = $_POST['username-field'];
        $password = $_POST['password-field'];

        verifyLoginCredentials($username, $password);
    }

    // verify admin login credentials
    function verifyLoginCredentials($username, $password) {
        global $dbConnect;
        $query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
        $statement = $dbConnect->prepare($query);

        if($statement) {
            $statement->bind_param('s', $username);
            $statement->execute();
            $resultSet = $statement->get_result();

            // since there will be only one row returned at max, no need of a loop
            $row = $resultSet->fetch_assoc();

            if($row != null) {
                $adminFullName = $row['full_name'];
                $adminUsername = $row['username'];
                $adminPassword = $row['password'];

                // if username/password is correct start session and store
                // username, password, full name in the session and login
                // admin to his account
                if($username === $adminUsername && password_verify($password, $adminPassword)) {
                    session_start();
                    $_SESSION['current_admin_fullname'] = $adminFullName;
                    $_SESSION['current_admin_username'] = $adminUsername;
                    $_SESSION['current_admin_password'] = $adminPassword;

                    //take current admin to admin dashboard
                    header('Location:admin dashboard.php');
                }
                else { // if username/password combination is incorrect
                    echo '<script>displayErrorBlock("Incorrect Username/Password")</script>';
                }
            } else { // if username doesn't exists in the database
                echo '<script>displayErrorBlock("Entered Username isn't registered")</script>';
            }
        }

    }

?>

<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="../Resources/Bootstrap v4.1/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="../CSS/admin login.css"/>
    <link rel="stylesheet" href="../CSS/common.css"/>
    <title>Admin Login</title>
  </head>
  <body>
    <div class="container-fluid">

      <div class="row">
        <div class="col-sm-12 navbar-container">
          <nav class="top-navbar">
            <img src="../Resources/images/logo.png" alt="logo"/>
            <p>Admin Panel</p>
          </nav><!--end of navbar-->
        </div><!--end of first column-->
      </div><!--end of first row-->

      <div class="row">
        <div class="col-sm-4 login-form-container">

          <p class="error-msg-block">
            <span></span>
          </p>

          <form class="login-form" method="post" action="admin login.php" onsubmit="return validateForm()">
            <p>Welcome Back!</p>

            <div class="form-group username-group">
              <label for="username-field">Username</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <div class="input-group-text">
                    <img src="../Resources/images/envelope.png" alt="envelope image"/>
                  </div>
                </div>
                <input class="form-control" id="username-field" type="text" name="username-field" id="username-field" placeholder="Username"/>
              </div>
            </div><!--end of first form group-->

            <div class="form-group password-group">
              <label for="password-field">Password</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <div class="input-group-text">
                    <img src="../Resources/images/lock.png" alt="lock image"/>
                  </div>
                </div>
                <input class="form-control" id="password-field" type="password" name="password-field" id="password-field" placeholder="Password"/>
              </div>
            </div><!--end of second form-group-->

            <input type="submit" class="btn" id="login-btn" name="login-btn" value="Login"/>
          </form><!--end of login form-->

        </div><!--end of first column-->
      </div><!--end of second row-->

    </div><!--end of container-->

    <!--CDN versions of JQuery and Popper.js-->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
    <script src="../Resources/Bootstrap v4.1/js/bootstrap.min.js"></script>
    <script src="../Javascript/admin login form validation.js"></script>
  </body>
</html>

Updated Question

I am facing a couple of problems.

  1. I am getting whole web page as a response when i try to log to log .responseText to console inside .onLoad method.

  2. When form is submitted via ajax, main if statement in php file

    if(isset($_POST['login-btn'])) {....}

    never evaluates to true, hence php code isn’t executing.

What am i doing wrong here?

Here’s my php code

<?php

    require 'DbConnection.php';

    // if login button is clicked
    if(isset($_POST['login-btn'])) {
        $username = $_POST['username-field'];
        $password = $_POST['password-field'];
        echo '<script>alert('form submitted')</script>';   <---- this alert is never invoked
        verifyLoginCredentials($username, $password);
    }

    // verify admin login credentials
    function verifyLoginCredentials($username, $password) {
        global $dbConnect;
        $query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
        $statement = $dbConnect->prepare($query);

        if($statement) {
            $statement->bind_param('s', $username);
            $statement->execute();
            $resultSet = $statement->get_result();

            // since there will be only one row returned at max, no need of a loop
            $row = $resultSet->fetch_assoc();

            if($row != null) {
                $adminFullName = $row['full_name'];
                $adminUsername = $row['username'];
                $adminPassword = $row['password'];

                // if username/password is correct start session and store
                // username, password, full name in the session
                if($username === $adminUsername && password_verify($password, $adminPassword)) {
                    session_start();
                    $_SESSION['current_admin_fullname'] = $adminFullName;
                    $_SESSION['current_admin_username'] = $adminUsername;
                    $_SESSION['current_admin_password'] = $adminPassword;
                }
                else { // if username/password combination is incorrect
                    echo 'Incorrect Username/Password Combination';
                }
            } else { // if username doesn't exists in the database
                echo 'Entered username isn't registered';
            }
        } else {
            echo 'Error while preparing sql query';
        }
    }

?>

Here’s my relevant javascript code

let loginForm = document.querySelector('.login-form');
let usernameField = document.getElementById('username-field');
let passwordField = document.getElementById('password-field');

// submit login form to server using ajax
function ajaxFormSubmit() {
    'use strict';
    let ajaxRequest = new XMLHttpRequest();
    let url = 'admin login.php';

    // login form submitted on server successfully
    ajaxRequest.onload = function () {
        if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
            console.log(ajaxRequest.responseText);
            displayInfoMessage(ajaxRequest.responseText, 'success');
        }
    };

    // error while login form submission on server
    ajaxRequest.onerror = function () {
        if (ajaxRequest.status !== 200) {
            console.log(ajaxRequest.responseText);
            displayInfoMessage(ajaxRequest.responseText, 'error');
        }
    };

    ajaxRequest.open('POST', url, true);
    ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajaxRequest.send(new FormData(loginForm));
}

function validateForm(e) {
    'use strict';

    // prevent form submission
    e.preventDefault();

    if (anyEmptyField()) {
        displayInfoMessage('Please fill all the empty fields', 'error');
        highLightEmptyFields();
        //return false;
        return;
    }

    // check if username is in right format
    if (!(regexTester(/^[A-Za-z0-9_]+$/g, usernameField.value))) {
        displayInfoMessage('Username not valid', 'error');
        highLightTextField(usernameField);
        //return false;
        return;
    }

    // check if username is atleast 3 characters long
    if (usernameField.value.length < 3) {
        displayInfoMessage('Username should contain atleast 3 characters', 'error');
        highLightTextField(usernameField);
        //return false;
        return;
    }

    // check if password is in right format
    if (!(regexTester(/^[A-Za-z0-9_]+$/g, passwordField.value))) {
        displayInfoMessage('Password not valid', 'error');
        highLightTextField(passwordField);
        //return false;
        return;
    }

    // check if password is atleast 6 characters long
    if (passwordField.value.length < 6) {
        displayInfoMessage('Password should contain atleast 6 characters', 'error');
        highLightTextField(passwordField);
        //return false;
        return;
    }

    //return true;
    // submit form information to server via ajax
    ajaxFormSubmit();
}

// add submit event listener on login form
loginForm.addEventListener('submit', validateForm);

Run Javascript on Woocommerce if page equals X and number of cart items equals Y Ask Question

I am trying to run javascript (Sweet Alert) on Woocommerce archive shop pages to execute only if there are 5 items in the cart & the page is equal to ‘url/leanshop/’.

My add to cart functionality is using AJAX. The below code, sort of works…but I can’t get it to trigger for the above conditions. It currently only triggers each time a product is added to the cart via AJAX.

My code so far:

add_action( 'wp_footer', 'items_in_cart_trigger' );
function items_in_cart_trigger() {

        global $woocommerce;
        // Set the minimum number of products in cart
        $maximum_num_products = 5;
        // Get the Cart's total number of products
        $cart_num_products = WC()->cart->cart_contents_count;

        // Compare values and if required amount of items in cart, display popup.
        if( $cart_num_products == $maximum_num_products && is_page( '/leanshop/' ) ) {

    ?>
      <script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
        <script type="text/javascript">
            (function($){
                $('body').on( 'added_to_cart', function(){
                    // Test output on JS console
                    console.log('added_to_cart'); 
                    // Call Sweet Alert PopUp Here
                  swal(
                    'You added all the items!',
                    'Proceed to checkout?',
                    'success')
                });
            })(jQuery);
        </script>
    <?php
}
}

UPDATE:
The Javascript works with the following is_page() IF statement. So the problem is the logic above where I am trying to count the amount of items in the shopping cart and see if they are equal to a value, whilst on the shop archive page. Can anyone suggest the correct Woocommerce code logic in order to do so?

if( is_page('leanshop'))    {

Laravel Javacript – Check if theme exists in session, add class Ask Question

I’m working on a system where the user can select a product and go to the next page. This product then gets saved in the session using laravel sessions. When the user decides to go to the next page and come back. The chosen product is indeed saved in the session, but the is no way for them to see what product they have chosen because the class isn’t applied to the product that was chosen.

The code may clarify it better:

@foreach($themes as $theme)
    <div class="col-md-4 mb-4">
        <div class="card theme-card card-hover depth-2 border-0" id="theme-id-{{$theme->id}}">
            <a href="" class="theme-link" data-toggle="modal" data-target="#theme{{ $theme->id }}">
               <div class="card-image" style="height: 200px; background-image: url('/uploads/{{ $theme->thumbnail }}'); background-size: cover; background-position: center center;"></div>
               <div class="card-body">
                    <div class="row">
                        <div class="col-md-2 vertical-center">
                            <i class="fab fa-magento fa-lg"></i>
                        </div>
                        <div class="col-md-10">
                            <p class="m-0">{!! str_limit($theme->name, $limit =  32, $end = '...') !!}</p>
                            <small class="text-muted">{{ $theme->productable_type }}</small>
                        </div>
                    </div>
                </div>
            </a>
            <div class="card-footer bg-white border-0 text-right pt-0">
                <div class="row">
                    <div class="col-md-6 text-left">
                        <input type="hidden" class="theme-name" name="theme[{{$theme->id}}]">
                        {{--<input type="hidden" value="{{ $theme->composer_package }}">--}}
                        <button data-card-id="{{$theme->id}}"  class="btn btn-orange btn-sm btn-theme-choice">Kiezen</button>
                    </div>
                    <div class="col-md-6 text-right">
                       <span style="font-size: 20px;" >€ {{ $theme->price }} EUR</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endforeach

In the above code, I for each trough every so-called “Theme” and I’m giving the ID of the theme as a data target and as ID. Then in my Javascript code, I do the following:

$('.btn-theme-choice').on('click', function (event) {

    event.preventDefault();
    newSelectedCardId = $(event.target).data('card-id');

    if(cardId === null) {
        cardId = newSelectedCardId;
    } else if (cardId !== newSelectedCardId) {
        $('#theme-id-' + cardId).removeClass('theme-chosen').find("input[name='theme["+cardId+"]']").val('');
        cardId = null;
    }

    var card = $('#theme-id-' + cardId );
    card.toggleClass('theme-chosen');
    selectedCardInput = card.find("input[name='theme["+cardId+"]']");

    if( !$('.theme-card').hasClass('theme-chosen') ) {
        selectedCardInput.val('');

    } else if ( $('.theme-card').hasClass('theme-chosen') ) {
        selectedCardInput.val('selected');
    }

    console.log(selectedCardInput);
});

Here I add the class to the card so the user can See which card they’ve selected. This choice then gets saved in the session using some PHP code in the controller

if( $theme == null ) {

    return redirect('plugins');

} elseif( $theme != null ) {

    foreach($this->predefinedArray as $value) {
        $request->session()->put('chosen_theme.' . $value, $theme->$value);
    }

    $request->session()->put('chosen_theme.composer_package', $theme->productable->composer_package);

    return redirect('plugins');
}

problem

How can I read the session and add the class to the card with the IDs that were stored in the session so if the person leaves the page and comes back, they can see what cards they’ve selected?

Thanks in advance

How to save content from textarea as array, and save in another php file? Ask Question

I have two files: index.php (also contains JS)
And page2.php.

I have in index.php a textarea:

<textarea id="url" rows="1" class="form-control" style="color: white; width:20%; height:3.50%; text-align:center; background-color:#2c2c2d; resize:none;" placeholder="url here"></textarea>

<input type="submit" class="btn btn-primary" onclick="enviar();" value="Start"/>

And in page2.php i have:

$url = "$url";
$data = file_get_contents($url, false, $context);

I want to actually create a connection between them, with the help of js.

That as soon as I write in the textbox the url (index.php) and press submit,

page2 will accept the $url from the textbox.

Google Analaytics and multilanguage site Ask Question

I have a multilanguage site in PHP but I don´t have subdirectories
for the different languages. All the views are translated based on a PHP session

so instead of having mysite.com/es/about I just have mysite.com/about
and based on a PHP session I display the content in one language or another.

how can I deal with google analytics? is there a way to set a pageLanguage?

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'XXX');
gtag('pageLanguage', '<?php echo $language?>');

is this correct? thank you

Display a message if a page break occurs when printing HTML? Ask Question

I’m working on an web application that generates quotes. At the end of a quote, there’s a « Details & Conditions » block that I don’t want to be split upon printing. To that end, I use this CSS code:

@media print {
    #conditions {
        page-break-inside: avoid;
    }
}

However, when the block is moved to the next page, it may not be clear for the client that there’s more to read on the other side of the page.

Thus, I’d like to add a message on the main page when this happens. Something like « Details & conditions on the next page ». But I can’t think of a way to know when to display this message, for this I would need to know that a page break occurred and I can’t find a way to do that since it’s a browser thing.

The HTML code is generated by a mix of PHP (server-side) and JavaScript (client-side) code, so I have quite some flexibility.

Any idea?

Sending to checked checkbox which is linked to email [closed] Ask Question

So I’m new to coding such as Javascript and PHP, I need to create a form that will be hosted on a site which on a submit will send an email dependent on which checkbox is ticked, the different checkboxes will go to different emails, would I need to use a PHP post for this and is there any need for Jquery at all? or could I just use PHP? would love the help. Thank you

<?php  
    $mail1 = "test@test.com";
    $mail2 = "test2@test.com";
    $mail3 = "test3@test.com";
    if(isset($_POST["MainCB"])) {
        $mail1 = $_POST["MainCB"];
    }
    if(isset($_POST["ITCB"])) {
        $mail2 = $_POST["ITCB"];
    }
    if(isset($_POST["CateCB"])) {
        $mail3 = $_POST["CateCB"];
    }
    if(isset($_POST['submit'])){
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $MainCB = $_POST['MainCB'];
    $ITCB = $_POST['ITCB'];
    $CateCB = $_POST['CateCB'];
    $subject = "Form submission";
    $message = $first_name . " " . $last_name . " " . $MainCB . " " . $ITCB . " " . $CateCB;
    }
?>
<html>
    <head>
        <title>Form submission</title>
    </head>
    <body>
        <form action="" method="post">
            First Name: <input type="text" name="first_name"><br>
            Last Name:  <input type="text" name="last_name"><br>
            Maintenance:<input type="checkbox" id="MainCB"><br>
            IT:         <input type="checkbox" id="ITCB"><br>
            Catering:   <input type="checkbox" id="CateCB"><br>
            <input type="submit" name="submit" value="Submit">
        </form>
    </body>
</html>