Redirect and popup when sql is done - javascript

I want to get my application when a item is deleted pop up a messege and redirect to another page. I used javascipt for the popup and php header for the redirection. Now its only doing or the popup or the redirect depending which one is listed first. how do i fix this?
<?php
session_start();
require_once('../../includes/mysql_config.php');
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: ../../login.php');
$Cursist = mysqli_query($con, "SELECT id FROM users WHERE id =".$_SESSION['id']);
if(!$Cursist){
header('location: ../login.php');
}
$test = $_GET['id'];
$sql = "DELETE FROM cursus WHERE id = $test";
$result = mysqli_query($con, $sql);
if ($result) {
echo "<script type='text/javascript'>alert('Verwijdert!')</script>";
header("Location: ../cursussen.php?destoyed=true&destroyed_id=".$_GET['id']);
}else {
echo "mislukt";
}
?>

If you send sometrhing before header will not work. You can use only header before sending sometrhing to the client.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
http://php.net/manual/en/function.header.php
You could do with javascript but It not recommended because the user could have javascript disabled:
echo "<script type='text/javascript'>";
echo "alert('Verwijdert!')";
echo "document.location.href='index.html'";
echo "</script>";
The best way is to use session and header, you can save a var in session and show a message when the var is true and when you show the messasge delete the session var
delete.php
$_SESSION['deleted'] = true;
header("Location: index.php);
index.php
<?php if($_SESSION['deleted']){ ?>
<?php unset($_SESSION['deleted']) ?>
<div>Item was deleted</div>
<?php } ?>

Well, the problem is that the redirect immediately moves you to a new page, so any javascript on the old page becomes irrelevant. You might be able to use a delay before redirect so that the javascript alert can display.
Otherwise, introduce a variable that you send to the redirect destination page, and use this variable to trigger a javascript popup there.

Related

PHP get information from database when echoed html code is clicked

In my code, I am retrieving data from the database using a while loop so i can have all the $FormData['fullname'] in the db.
What i want to do is, have each name display on the page and also have clickable so when someone clicks a name, it gets their user_id and pulls up information about them.
The problem i am having is that I can't figure out a way to make a it so where i can get the user_id when the user clicks a name. I tried putting a "name" in the button attribute and I checked if isset() but that didn't work.
If someone can properly figure out a way for me to basically, display all the fullnames in my database and when someone clicks a name, it pulls up information about them that is stored in the database. Here is my code
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch()){
echo "<button name='name'>$formData[fullname]</button>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(isset($_POST['name'])){
echo "ok";
}else{
echo "bad";
}
}
}
As far i can see you are trying hit a button inside the while loop , i would not say its a bad approach , but i will suggest you not to do that . and from your code i can see you have lack of understanding post and get request learn from here . and other than this you need to know the transition of web url . how its actually works . anyway , i have given a sample code without . i hope it will help you understanding this concept.
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch(PDO::FETCH_ASSOC)){
$id = $formData['formdataid'];
echo "<a href='somepagename.php?infoid={$id}'>". $formData['fullname']."</a></br>";
}
now in the somepagename.php file or in the same page you can actually show the details information for instance
if(isset($_GET['infoid'])){
$stmt = $handler->prepare("select * from formdata where formdataid='"$_GET['infoid']"'");
$qry = $stmt->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
echo "<p>id =".$row['formdataid']."</p></br>";
echo "<p>id =".$row['name']."</p></br>";
echo "<p>id =".$row['email']."</p></br>";
echo "<p>id =".$row['address']."</p></br>";
code is not executed , it may have semicolon or comma error warning . you have to fix those on your own . this example above shown you only the way it works .
if still you have problem ask , or see the documentation
I should stress that this is not production code and you should totally validate the data input coming in before posting queries to your DB. You can do something like this.
<?php
// Connect
$connection = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Grab all users
$sql = 'SELECT * FROM users';
$users = mysqli_query($connection, $sql);
if (($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['user_id'])) {
$query = "SELECT * FROM users WHERE user_id = {$_POST['user_id']};";
$user = mysqli_fetch_assoc(mysqli_query($connection, $query));
}
?>
// This only runs if our $user variable is set.
<?php if (isset($user)) : ?>
<?php foreach ($user as $key => $value) : ?>
<span><?= print_r($value) ?></span>
<?php endforeach; ?>
<?php endif; ?>
// Display all users in a dropdown and when the button is clicked
// submit it via post to this page.
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select name="user_id">
<?php foreach ($users as $user) : ?>
<option value="<?= $user['user_id'] ?>"><?= $user['name'] ?></option>
<?php endforeach; ?>
</select>
<button type="submit">Submit</button>
</form>
This is going to refresh your page every time. If you want to have an interactive page you are going to need to use JavaScript/AJAX to update the page elements without reloading the page. This example just demonstrates how you can achieve this with PHP and HTML.
you need to know about server-side language(php) and client-side language(javascript).
php runs before page loaded. it cannot runs when click something by itself(with ajax, it can).
most interactions without page move runs with javascript.
in your case, there are two methods.
store all information into hidden input or button's attribute. and get them by user_id via javascript.
use ajax to call another php that can select informations you need by user_id.
both use javascript or jquery. so you must learn about them.

Redirect only after script Completes it's execution in codeigniter

I want to redirect to view with script in codeigniter. Script first and then page redirection.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function login()
{
$this->load->view('login');
}
}
I tried this code but it's not working because page is redirected before script completes it's executions. So, How to show notification in alert.
echo "<script>";
echo "alert('User not Found');";
echo "</script>";
redirect('home/login');
I tried with this also,
echo "<script>";
echo "alert('User not Found');";
echo "</script>";
echo "<script>setTimeout(\"location.href = 'http://localhost/dealsnow/index.php/home/login';\",300);</script>";
Second way is working for me but i think it's not good way. So is there any other option available for redirection to view after script completes it's execution.
Example : If i insert Form Data and then I want to show user that data is inserted properly in script and then i want the page to redirect.
Script first and then page redirection.
Solve my question,
If we want to execute script first and then after some timeout.
Ex. : if we want to show user that data is inserted properly in script and then i want the page to redirect.
echo "<script>";
echo "alert('Data Insereted Properly..!');";
echo "</script>";
$url = base_url().'/index.php/home/login';
header("refresh:3;url=$url");
use flash data in your code.
// Set flash data
$this->session->set_flashdata('error', 'User not Found');
// After that you need to used redirect function instead of load view such as
redirect("home/login");
// Get Flash data on view
$this->session->flashdata('error');
Hope it will help.

javascript alert box not showing on php after header redirect

I am trying to display an alert box before redirecting to another page, here is my code, when I remove the header function it works properly but when it is here it will just redirect to the page without showing the alert box.
<html>
<body>
<?php
include("dbconfig.php");
$tempid = mysqli_real_escape_string($dbconfig, $_POST['tempid']);
$sql_query = "DELETE FROM Visits
WHERE visitid = '$tempid'";
$result = Mysqli_query($dbconfig, $sql_query);
if ($result) {
echo '<script language="javascript">';
echo 'alert("visit deleted successfully")';
echo '</script>';
header("location:../SearchCountry/search.php");
}
?>
</body>
</html>
PHP is executed at the server side. It renders HTML/JS/CSS and sends it to the web browser, the web browser then parses and executes the JavaScript (In your case, show the alert dialog.)
However, once you call
header ("location:../SearchCountry/search.php");
The browser will be informed to redirect the user to ../SearchCountry/search.php immediately, without a chance to parse and execute the JavaScript. That's why the dialog will not show up.
Solution: redirect your user to another page with JavaScript instead of PHP.
<html>
<?php
include("dbconfig.php");
$tempid = mysqli_real_escape_string($dbconfig,$_POST['tempid']);
$sql_query = "DELETE FROM Visits
WHERE visitid = '$tempid'";
$result = Mysqli_query($dbconfig,$sql_query);
if($result){
echo '<script language="javascript">';
echo 'alert("visit deleted successfully");\n';
echo 'window.location.href="../SearchCountry/search.php"'; //Redirects the user with JavaScript
echo '</script>';
die(); //Stops PHP from further execution
}
?>
</body>
</html>
echo "<script>
alert('visit deleted successfully');
window.location.href='SearchCountry/search.php';
</script>";
and get rid of redirect line below.
You were mixing up two different worlds.

php javascript redirection issue

i have 2 php pages page1.php and page2.php
page1.php redirects to page2.php with an id paramater
page2.php?id=8923423672222
page1.php code
<?
$id = "4556745767";
echo "<script language=\"javascript\">function gopage2(){top.window.location.href=\"http://www.example.com/page2.php?id=".$id."\";}setTimeout('gopage2()',1000);</script>";
?>
page2.php code
<?
$id = $_GET['id'];
if($id!='')
{
section = "section1";
}
else
{
section = "section2";
}
echo "<script language=\"javascript\">function gosite(){top.window.location.href=\"http://www.example.com/".$section."/\";}setTimeout('gosite()',1000);</script>";
?>
in some cases page1.php doesn't redirect to page2.php
the reason of using javascript here that i want to be sure the user has javascript enabled, but in my tracking systems its report that page1 not redirecting in about 40% of requests and this is not reasonable , most of request comes from real hits
any help if there is any syntax or semantic wrong here

How do i reload the page after the sql statement has been submitted

I am using the following code to try and insert data into my database. The data works fine and i do this using a form. The form has a submit button that i will but the code in bellow the following code. I am using localhost to run my web application.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO PRODUCTS (P_Name, P_Description, P_Price) VALUES ('$_POST[Name]', '$_POST[description]', '$_POST[Price]' ) ";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
the submit button:
<div id="theSubmit">
<input type="submit" name="submit">
</div>
At the moment when i click submit i get taken to a page display the text New record created successfully. However I would like it to reload the page.
I am aware of the javascript location.reload(); is this what I have to use, if so where?
You should reload after execution of your sql like this.
$_SESSION['msg'] = "New record created successfully";
header("Location: $url"); // tell the client to load $url
exit(); // stop further execution of the current script
the $msg should be set via session to be able to show the msg after reload.
If you do it like that it is no problem if the user klicks the back button or do a page reload.
After reload do:
if(isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
Use:
header("Location: $_SERVER[REQUEST_URI]");
exit;
This will redirect the user to the the same page using a GET method, reloading it.
If you are not displaying any DOM Elements, or doing any Header requests prior that PHP Script you can always use the php function
header('Location: your-url.com');
exit();
to reload a website.
if there are header requests prior that header function this solution wont work so you can add that JS code at the bottom of your script so it gets fired after you have dealt with the form.

Categories