javascript - Display alert message that's inside an action file, in another file

405

So I have this php action file:

<?php
session_start();
require 'config.php';
if (isset($_POST['action']) && $_POST['action'] == 'signup') {

    $stmt1 = "SELECT * FROM users where username='" . $_POST['username'] . "'";
    $ret1 = mysqli_query($conn, $stmt1);
    $rowcount1 = mysqli_fetch_assoc($ret1);
    if (empty($rowcount1)) {


        $query = "INSERT INTO users (username, password, email, cpf)VALUES( '" . $_POST['username'] . "', '" . $_POST['password'] . "', '" . $_POST['email'] . "', '" . $_POST['cpf'] . "')";
        //echo $query;exit;
        echo  mysqli_query($conn, $query);
    } else {
        header("Location:signup.php");
        echo '<script language="javascript">';
        echo 'alert("User is already registered.")';
        echo '</script>';
    }
}

This else statement becomes true because I can see it in the console, but, I'm trying to display this alert message in another file called "signup.php".

I want to display the alert message right inside this small div:

<div class="cont">

</div>

I tried to do it with "header("Location:signup.php");" as you can see but no idea on how to make it work.

Any ideas on how I can do that?

650

Answer

Solution:

Header('Location:') will redirect the user's browser. Nothing else will be displayed on the web page because the browser is being redireced. You need to add the tag to the page signup.php.

<?php
session_start();
require 'config.php';
if (isset($_POST['action']) && $_POST['action'] == 'signup') {

    $stmt1 = "SELECT * FROM users where username='" . $_POST['username'] . "'";
    $ret1 = mysqli_query($conn, $stmt1);
    $rowcount1 = mysqli_fetch_assoc($ret1);
    if (empty($rowcount1)) {


        $query = "INSERT INTO users (username, password, email, cpf)VALUES( '" . $_POST['username'] . "', '" . $_POST['password'] . "', '" . $_POST['email'] . "', '" . $_POST['cpf'] . "')";
        //echo $query;exit;
        echo  mysqli_query($conn, $query);
    } else {
    // THE BROWSER IS HAS BEEN REDIRECTED TO signup.php
        header("Location:signup.php");

    // THIS ISN'T DISPLAY IN THE BROWSER BECAUSE THE BROWSER IS BEING REDIRECTED
        echo '<script language="javascript">';
        echo 'alert("User is already registered.")';
        echo '</script>';
    }
}

People are also looking for solutions to the problem: php - Implement Ajax to load HTML depending on radio button value

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.