Browser does not response to header redirect - javascript

please help... i am new to php. Thanks
php1 is to send a data ('1234') via method Post to php2. php2 is supposed to redirect using Header Location to php3 with a data ('invalid').
Developer Tools of Chrome indicate that everything went well (Post data sent and received. Get data sent and received).
Somehow, the browser does not response and stay at php1. I have tried Safari and Firefox. No response.
Would be really grateful if you could advise. Thanks
The 3 php files are:
php1
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
}
);
});
});
</script>
</head>
<body>
<div>
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>
php2
<?php
session_start();
ob_start();
error_reporting(E_ALL);
if (!empty($_POST)){
$Email = $_POST['email'];
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
header('Location: php3.php?m=invalid');
exit();
}
} else {
header('Location: php1.php?m=nodata');
exit();
}
ob_end_flush();
?>
php3
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<?php echo $M; ?>
</div>
</body>
</html>
Here is a screenshot of chrome developer:

You should change the code for php1.php like this
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
$("#content").html(data); // <----- ADDED
}
);
});
});
</script>
</head>
<body>
<div id="content">
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>

Related

jquery ajax not sending data in code igniter

I'm new to Codeigniter MVC framework. when i send data through ajax from views to controller this error shows click here to view the image
here is my code :
views/ajax_post_view.php :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$(".submit").click(function(e){
e.preventDefault();
var user_name = $("input#name").val();
var password = $("input#pwd").val();
//alert(user_name);
//alert(password);
$.ajax({
type:'POST',
url:'<?php echo base_url();?>'+'index.php/ajax_controller/submit',
dataType:'json',
data:{name:user_name,pwd:password},
success:function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<div class="main">
<div id="content">
<h2 id="form-head">Pavan Code Igniter Ajax</h2>
<hr>
<div id="form_input">
<?php
echo form_open();
echo form_label('User Name');
$data_name = array(
'name'=>'name',
'class'=>'input_box',
'placeholder'=>'Please enter name',
'id'=>'name'
);
echo form_input($data_name);
echo "<br>";
echo "<br>";
echo form_label('Password');
$data_name = array(
'type'=>'password',
'name'=>'pwd',
'class'=>'input_box',
'placeholder'=>'Please enter Password',
'id'=>'pwd'
);
echo form_input($data_name);
?>
</div>
<div id="form_button">
<?php echo form_submit('submit','Submit','class="submit"');?>
</div>
<?php
echo form_close();
?>
</div>
</div>
</body>
</html>
controller : controllers/Ajax_controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_controller extends CI_Controller {
// Show view Page
public function index(){
$this->load->helper('form');
$this->load->helper('url');
$this->load->view("ajax_post_view");
}
// This function call from AJAX
public function submit() {
$data = array(
'username' => $this->input->post('name'),
'pwd'=>$this->input->post('pwd')
);
echo json_encode($data);
}
}
?>
KINDLY HELP ME THANKS IN ADVANCE
In the controller, set Access-Control-Allow-Origin at the top of your php script :
header('Access-Control-Allow-Origin: *');

PHP fails to get $_POST from JS

I have created an HTML page and am attempting to use AJAX via JS to echo from a PHP page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>User Retrieval</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function getid(){
var userid = document.getElementById('userid').value;
$.post('Users2.php', {postname:userid},
function(data){$('#results').html(data);});
};
</script>
</head>
<body>
<h1>User Retrieval</h1>
<p>Please enter a user ID:</p>
<input type="text" id="userid" placeholder="Please insert user ID" onkeyup="getid()" />
<div id="results"></div>
</body>
</html>
I have tested the JS and see that userid indeed gets the information from the HTML.
I then wrote the following PHP:
<?php
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
echo name;
}
else
{
echo "There is a problem with the user id.";
}
?>
However, I am always getting the else echo statement.
What am I missing here?
I am using XAMPP for local host checks.
Try this, It might help
<?php
if ($_POST[]) {
$name = $_POST['postname'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
var userid = $("#userid").val();
$.ajax
({
type:'post',
url:'user2.php',
data:{
get_id:"user2.php",
userid:userid,
},
success:function(data) {
if(data){
$("#results").html(data);
}
});
Php File
<?php
if (isset ($_POST['userid'])) {
$name = $_POST['userid'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>

How to enable javascript in my website?

I am doing a project to remotely display the data on the P10 Modules. I made the website for it, but whenever I want to retrieve data from the specific webpage on my website I get the error that is mentioned below;
The error I get when I try to retrieve data from the webpage1
The URL for the webpage is http://haider.paks.pk/test1/newfile.txt
<html>
<body>
<script type="text/javascript" src="/aes.js" ></script>
<script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("b2a5a77ff21b1f1b4e9b8d9099c2f834");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://haider.paks.pk/test1/newfile.txt?i=1";</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
</body>
</html>
How can I possibly solve this issue? How to enable javascript in the coding? Where I would do it?
The codes for the web pages are;
Index page (Main Page)
<?php
//include auth.php file on all secure pages
include("auth.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome Home</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<form action="get_msg.php" method="post">
<p>Select Department </p>
<br>
<select name="dept">
<option value="cs">CS</option>
<option value="ee">EE</option>
<option value="btn">BTN</option>
</select>
<p>Enter your message:<br />
<textarea name="sms" rows="10" cols="40"></textarea></p>
<p><input type="submit" value="Send it!" onclick="show()"></p>
</form>
<script>
function show() {
alert("Message send successfully");
}
</script>
<input type="button" name="b1" value="Show History"onclick="location.href='history.php'">
<p>This is secure area.</p>
<p>Dashboard</p>
Logout
</div>
</body>
</html>
get message page (The page that retrieves the sent message from the server
<html>
<body>
<?php
require_once('db_con.php');
?>
<?php
//echo $_POST["sms"];
//$sms = $_POST["sms"];
session_start();
$_SESSION["favcolor"] = $sms;
//echo $_SESSION["favcolor"];
//echo $_POST["sms"];
$sms = $_POST["sms"];
$dept=$_POST["dept"];
echo $dept;
if($dept=="cs"){
$sql_query = "INSERT INTO cs VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="ee"){
$sql_query = "INSERT INTO ee VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="btn"){
$sql_query = "INSERT INTO btn VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if(mysqli_query($con,$sql_query))
{
}
else
{
echo " Data insertion error.. ".mysqli_error($con);
}
$sql = "SELECT * FROM message";
$iid=last_insert_id($sql);
echo "here";
echo $iid;
?>
</body>
</html>
**Index2 webpage (The webpage that retrieves the message from get message webpage and sends it to the text file **
<html>
<body>
<?php
require_once('db_con.php');
?>
<?php
//echo $_POST["sms"];
//$sms = $_POST["sms"];
session_start();
$_SESSION["favcolor"] = $sms;
//echo $_SESSION["favcolor"];
//echo $_POST["sms"];
$sms = $_POST["sms"];
$dept=$_POST["dept"];
echo $dept;
if($dept=="cs"){
$sql_query = "INSERT INTO cs VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="ee"){
$sql_query = "INSERT INTO ee VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="btn"){
$sql_query = "INSERT INTO btn VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if(mysqli_query($con,$sql_query))
{
}
else
{
echo " Data insertion error.. ".mysqli_error($con);
}
$sql = "SELECT * FROM message";
$iid=last_insert_id($sql);
echo "here";
echo $iid;
?>
</body>
</html>
I have resolved the issue. There is nothing wrong with the code. The only thing due to which this issue raised was that I was using free domain for my website. When I uploaded the same files on a paid hosting service, the issue was resolved and my arduino was able to retrieve the data from the web server.

php - Session Not Carrying Over but Variables Are

I have a page (index.php) which has a login form. When a user logs in, it checks the credentials and if correct, creates a session, sets two variables, auth to yes and user to the username, and redirects to another page(pihome.php) via echoing a javascript window.location.href command. This is where the problem starts. On this page if I run session_start() it used to say session has already been created, ignoring but I was able to access the variables from the previous page. Now using an if condition with session_status() it session_start() works. I have a Logout button on this page which goes to another page (Logout.php). On that page when I try to run session_destroy() it says a session has not been started and when I try to echo the variables it says they have not been defined.
While browsing SO for solutions I saw certain solutions that applied to variables not being carried over but I can access them on the pihome.php page but logout.php doesn't let me access them or execute session_destroy(). I would like to know if I'm using the sessions correctly and if I should place session_start() at the beginning of every page and how to correctly access the variables. Thanks!
index.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body id="override-background">
<?php
session_start();
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] == "yes"){
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
}
else{
}}
else{
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<img src="piHome.png" alt="piHome_logo" class="img-rounded" style="display:block;"></img>
<h3 class="text-center">Login</h3>
<form role="form" action="index.php" method="post">
<div class="form-group">
<label for="user">Username</label>
<input type="text" class="form-control" id="email" name="user">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="pass">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<input type="submit" class="btn btn-primary btn-block" value="Login">
<form>
</div>
</div>
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "pihome_users";
//Database Connection
$conn = mysqli_connect($server, $user, $pass, $db);
//Check Connection
if($conn->error){
die("Connection Failed: "+ $conn.error);
}
if(isset($_POST['user'])){
//echo "Set<br>";
//User Authentication
$inputuser = $conn->escape_string($_POST['user']);
$inputpass = $conn->escape_string($_POST['pass']);
//echo $inputuser."<br>";
//echo $inputpass."<br>";
$sql = 'SELECT * FROM users WHERE username="'.$inputuser.'"';
//echo $sql;
//Execute
$result = $conn->query($sql);
if($conn->error){
echo "Load Error";
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if($inputpass == $row["password"]){
echo '<div class="alert alert-success fade in">
x
Your credentials are correct
</div>';
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
$_SESSION["Auth"] = "yes";
$_SESSION["User"] = $inputuser;
}else{
echo '<div class="container-fluid"><div class="alert alert-danger fade in">
x
Your username or password is incorrect!
</div></div>';
$_SESSION["Auth"] =false;
//echo "Success";
}
} else {
//echo "Failed";
}
}
else{
//echo "Not Set";
}
?>
</body>
</html>
pihome.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body>
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
}
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] != "yes"){
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
echo "You are logged in as: ".$_SESSION["User"];
}else{
echo "Auth Passed";
$_SESSION["Auth"] = "yes";
}
}else{
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<h3 class="text-center">Status</h3>
<div id="status">
</div>
</div>
<script>
function AJAX_JSON_Req( url )
{
var AJAX_req = new XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function()
{
if( AJAX_req.readyState == 4 && AJAX_req.status == 200 )
{
var response = JSON.parse( AJAX_req.responseText );
//document.write( response.controls[0].type );
document.getElementById("status").innerHTML = response.controls[0].type + " " + response.controls[0].state;
}
}
AJAX_req.send();
}
AJAX_JSON_Req( 'status.json' );
</script>
Logout
</div>
</body>
<html>
logout.php
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
session_unset();
}
else if($sessionstate == 2){
session_destroy();
echo "destroyed";
}
/*echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';*/
?>
I solved this by using session_start() before any output including <!DOCTYPE html> as suggested by rjdown in the comments above.

Ajax Jquery Passing variable to PHP file

Hey Im having an issue in accessing the variable from JQuery Ajax. I ve tried everything. I even added cdn script tag to both files. but I keep getting this error of undefined index
Notice: Undefined index: head in C:\xampp\htdocs\Project\View.php on line 20
Anyone has any idea wats wrong with the syntax. I have attached both my files below.
SearchProjects.php
<html>
<head>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$('#assign tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
});
$('td').on('click',function() {
var heading=$(this).text();
alert(heading);
$.ajax({
url: "View.php",
type: "POST",
data: {head: heading},
success: function(data){
alert("success");
}
});
});
</script>
</head>
<body>
<div>
<div class="col-md-12"><br/></div>
<?php
session_start();
$No="Not Assigned";
require("DB.php");
$query="SELECT `ID`, `Assigned_By`, `name`, `path`, `heading`,`Assigned_to`, `Completed`, `Date`, `Due_Date`, `Price` FROM `assign` where `Assigned_to`='Not Assigned' order by Date Desc";
$result=mysqli_query($PDB,$query);
if ($result->num_rows > 0) {
echo "<table class=table table-hover id=assign>"
."<thead>"
. "<tr> "
. "<th>ID</th>"
. "<th>Assigned_By</th>"
. "<th>Name</th>"
. "<th>Path</th>"
. "<th>Heading</th>"
. "<th>Assigned_To</th>"
. "<th>Completed</th>"
. "<th>Due_Date</th>"
. "<th>Submission_Date</th>"
. "<th>Price</th>"
. "</tr> </thead> ";
while($row = $result->fetch_assoc()) {
echo "<tr>"
. "<td>".$row["ID"]."</td>"
. "<td>".$row["Assigned_By"]."</td>"
. "<td>".$row['name']."</td>"
. "<td>".$row['path']."</td>"
. "<td>".$row['heading']."</td>"
. "<td>".$row['Assigned_to']."</td>"
. "<td>".$row['Completed']."</td>"
. "<td>".$row['Date']."</td>"
. "<td>".$row['Due_Date']."</td>"
. "<td>".$row['Price']."</td>"
. "<td><a class=btn btn-default href=View.php role=button>Show More!</a></td>"
. "</tr>";
}
echo "</table>";
}
else {
echo "0 results";
}
?>
</div>
</body>
View.php
<html>
<head>
<title>TODO supply a title</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<?php
session_start();
if(isset($_POST['head'])){
echo $_POST['head'];
}
$filename="CV.docx";
// $filename=$_SESSION['filename'];
//echo $filename."<br/>";
require("DB.php");
$query="SELECT `heading` FROM `assign` where `name`='$filename'";
$result=mysqli_query($PDB,$query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$heading=$row['heading'];
$_SESSION['heading']=$heading;
}
}
else {
echo "0 results";
}
$dir = "Assigns/";
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if(!($file=="." || $file=="..")){
$f=explode(".",$file);
if(strcmp($f[0],$heading)){
if(!file_exists("Assigns/$file")) {
die("File not found");
}
else{
$my_file = "Assigns/$file";
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));
}
}
}
}
closedir($dh);
}
}
if($_SERVER['REQUEST_METHOD']== 'POST'){
if (isset($_POST['save'])) {
$assigned_to=$_SESSION['username'];
echo $assigned_to;
echo $filename;
$query="UPDATE `assign` SET `Assigned_to`='$assigned_to' WHERE `name`='$filename'";
$result=mysqli_query($PDB,$query);
if($result){
echo "wohooo";
}
else{
echo "nooo";
}
}
else if (isset($_POST['submit'])) {
// echo "submit";
header('location: Solution.php');
}
}
?>
<div class="container">
<form action="View.php" method="post">
<h1 style="clear:both;"><?php echo $heading."<br/>" ?> </h1>
<div class="form-group">
<?php echo $data; ?>
</div>
<div class="col-md-12 col-md-offset-6">
<input type="submit" name="submit" value="Submit Solution">
<input type="submit" name="save" value="Save Changes">
</div>
</form>
</div>
</body>
Always check the existence of a variable/array index before using it:
$head = isset($_POST['head']) ? $_POST['head'] : null;
//may check nullity of $head
There seem to be two things going on: First of all, the click handler for the td is not attached because the DOM was not ready, wrap your jQuery code in
$(function() {
//your code
})
Also, the click event on the tr and on the td are both fired...

Categories

Resources