How to make an Alert in php

Asked

Viewed 1,496 times

0

Do an Alert or other type of message after the user misses the password on the login page for example ? I tried to do it this way:

    unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header('location:index.html');
echo '<script language="javascript">';
echo 'alert("Erro ao fazer Login")';
echo '</script>';

but it didn’t work, it goes back to the screen, but it doesn’t have any

  • 2

    Your line header("Location") redirects the user to the page index.html and the entire code stream will be ignored by the browser. If the intention is to display the alert and not redirect, remove this line.

  • Even, it’s good to totally eliminate Alert. Put a time interval in Location as a temporary solution. <meta http-equiv="refresh" content="5; url=http://example.com/">, so your Alert remains intrusive (like all Alert) but works

1 answer

4


Send parameters with query string to index.html and in index add the Alert script.

<?php
unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header('location:index.html?info=error&msg=1');

And in index.html add the script:

<script>
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }

    if(getParameterByName('info') === 'error' && getParameterByName('msg') === '1') {
        alert('Erro ao fazer Login');
    }
</script>

The function getParameterByName was extracted from here: https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript

Your code does not execute because when redirecting the page with the Location header in PHP the code below in javascript is not executed by the browser

  • It worked, but I found it very complex, and n understood this script to get the url of the page

  • 1

    When you redirect javascript retrieves the variables in the url, search for regular expressions (it’s the black magic part), it always does, but what matters is that you understand what happened, PHP does not run javascript it forwards to the client’s running browser, what we did was just forward variables to javascript to treat them and display the alert or not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.