I'm just starting with php and I want to save the value of an HTML input to the php session.
i have tried achieving this using
<html lang="en">
<head>
<title>Log In</title>
</head>
<body>
<?php
session_start();
?>
<input id='email' type='text' placeholder='Email'>
<input type='submit' onclick='logIn()' value='Log In'>
</body>
<script>
function logIn() {
var email = document.getElementById('email')
<?php
$_SESSION['email'] = email;
?>
}
</script>
</html>
but php does not have access to the email variable i created in JavaScript.
I just want to save to the PHP session, data that was entered into an input field of a html site
Use Ajax how suggest from #Jeremy Harris
Script:
function logIn() {
var email = document.getElementById('email');
$.ajax({
url: "session.php",
type: "POST",
data: {
email:email
},
success: function(data){
window.location.href = WHERE YOU WANT;
}
}); }
PHP (session.php):
$email=$_POST['email'];
$_SESSION['email'] = $email;
Related
I have 2 button in one form. When I click the first or second button, both write example an alert, but the Ajax request doesn't run. I need a form, because i would like to upload images. I don't know what is the problem.
page.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Ajax two submit in one form</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<form id="animal-upload" method="post" enctype="multipart/form-data">
<span>Name:</span>
<input type="text" name="animalname" id="animalname">
<span>Image:</span>
<input type="file" name="imagefile" id="imagefile">
<button type="submit" name="publish" id="publish">Publish</button>
<button type="submit" name="save" id="save">Save</button>
</form>
<script>
$(document).ready(function() {
$('#animal-upload').on('submit', function() {
return false;
});
$('#publish').click(function() {
alert("Test");
});
$('#save').click(function(e) {
e.preventDefault();
$.ajax({
url: "animal-upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
alert(data);
}
});
});
});
</script>
</body>
</html>
animal-upload.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
mysqli_set_charset($connect,"utf8");
$status = '';
$animalname = $connect->real_escape_string($_POST["animalname"]);
if ($_FILES['imagefile']['name'] != '') {
$extension = end(explode(".", $_FILES['imagefile']['name']));
$allowed_type = array("jpg", "jpeg", "png");
if (in_array($extension, $allowed_type)) {
$new_name = rand() . "." . $extension;
$path = "animals/" . $new_name;
if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $path)) {
mysqli_query($connect, "INSERT INTO animals (animalname,image) VALUES ('".$animalname."','".$path."')");
$status = 'Successful!';
}
} else {
$status = 'This is not image file!';
}
} else {
$status = 'Please select image!';
}
echo $status;
?>
After trial and errors I found the script work if you change this line :
data: new FormData($("#animal-upload")[0]),
Because that selects the form object.
You may consider some security tips :
Don't divulge your password in public
Don't let your database users connect without passwords
Make a user with strict minimum privileges just for the purpose to connect to your database from PHP scripts (it's called the principle of least privileges)
Rename your uploaded file
For the file upload to work :
Make sure you have the right permissions on the directory pointed by
upload_tmp_dir in php.ini file
You may need to check that your file size doesn't exceed the memmory_limit directive too
good luck,
I am trying to import a json array from a php script in JavaScript but every time the request fails and the xhr.responseText return the html code of the template of the html template associated to it. I am using xampp.
php code:
<?php
// This script is meant to display the data from Insight sensors DB
include('includes/motebymote.html');
if ($_SERVER['REQUEST_METHOD'] == 'POST'){//Use the post method as a request method to the server
require('mysqli_connect.php');//Give information on which database to use
if(!empty($_COOKIE["mote_ID"]) || !empty($_COOKIE["std"]) || !empty($_COOKIE["end"])){
//Setting variables
$moteID=$_COOKIE["mote_ID"];
$start=$_COOKIE["std"];
$end=$_COOKIE["end"];
if(preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $start) || preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $end)) {
if(isset($moteID) && isset($start) && isset($end)){
//Building the query
$q="SELECT date_time, modality, value FROM sensor_data WHERE mote_id = $moteID and date_time BETWEEN '$start' and '$end'";
$r = #mysqli_query ($dbc, $q);//Doing the request
$numRow = mysqli_num_rows($r);
if ($r && $numRow>0){
//echo "<p>There are $numRow data points associated to mote$moteID</p><br>";
//echo"<table align ='center' width ='70%' cellpadding='4'><tr><th>Date&Time</th><th> Sensor Type</th><th> Value</th></tr>";
$moteArray = array();
while($data = mysqli_fetch_array($r, MYSQLI_BOTH)){
//echo "<tr align ='center'><td>" .$data['date_time']. "</td><td>" .$data['modality']. "</td><td>" .$data['value']. "</td></tr>";
$moteArray[] = $data;
}
//echo"</table>";
$JSONMoteArray = json_encode($moteArray);
echo $JSONMoteArray;
}
else if ($numRow==0){
echo "<h1>Sorry there are no data available</h1>
<p>There are no data available for mote$moteID</p>";
}
else{//Give an error message if the query fails
echo '<h1>System Error</h1>
<p class="error">We could not record your order due to a system error. We apologize for any inconvenience.</p>';
}
}
}
else {
echo "<h1> Wrong date format</h1>
<p>Please input the starting date in a yyyy-mm-dd format</p>";
}
}
else{
echo "<h1> Wrong input</h1>
<p> Please make sure that the mote is properly selected and that the start and end dates are entered in yyyy-mm-dd format</p>";
}
mysqli_close($dbc); //close the database
}
exit(); //exits the script
?>
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<title> Motes Data</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/mote.js" async></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body><br>
<form action="motebymote.php" method="post">
<p>Please input a mote number: <input type="text" name="moteNo" id="moteNo"></p>
<p> Please input a starting date (yyyy-mm-dd):<input type="text" name="stDate" id="stDate"></p>
<p> Please input an end date (yyyy-mm-dd):<input type="text" name="endDate" id="endDate"></p>
<p><input type="submit" name="submit" value="submit" id="submit"/></p>
<p><input type="submit" name="display" value="display" id="display"/></p>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</form>
</body>
</html>
var but = document.getElementById("submit"); //Looking for the submit button
if(but){ //if the button is clicked activate the event listener
but.addEventListener("click", moteIDDate);
}
//This function goes to fetch the different values and store them with cookies //to allow motebymote.php to use them
function moteIDDate(){
var moteID = $('#moteNo').val();
document.cookie="mote_ID = " + moteID + ";time()+3600";
var start = $("#stDate").val();
document.cookie = "std="+start+";time() 3600";
var end = $("#endDate").val();
document.cookie= "end="+ end+";time() 3600";
};
var jsonData = $.ajax({
url: "http://localhost/Insight/mote2/motebymote.php",
type:"GET",
cache: false,
dataType: "json",
success: function(xhr){
console.log(xhr.responseText);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
The php code has "if...== POST"
your javascript ajax call is sending a "GET"
I am having a problem with posting a value to my php script via jQuery/ajax. I have searched around looking for a solution but cannot seem to figure it out why i am not getting the value posted.
here's my code.
page.html
<body>
input message:<p><input type="text" id="note" name="note" placeholder="enter something that made you feel this way"></p><br />
<p><button name="submitMessage">submit</button></p>
<script src="../js/jquery-3.1.1.js"></script>
<script src="../js/welcomeScript.js"></script>
<script> $( document ).ready(function() {
$('[name=submitMessage]').on('click', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '../php/post-note.php',
data: {data: $('#note').attr('val')},
success: function(){
alert('added your note, you will now go to main app!');
window.location.href = "../home.php";
}
});
});
});
</script>
</body>
post-note.php
session_start();
$note = $_POST['data'];
if(isset($note) && isset($_SESSION['username'])){
$username = $_SESSION['username'];
$sqlMessage = "UPDATE mt_tbl SET note = '$note' WHERE userName = '$username'";
mysqli_query($conn, $sqlMessage);
echo "note: ".$note. " added to the dB!";
}
Instead of $('#note').attr('val') use $('#note').val()
Why? the reason is given below:-
console.log($('#note').attr('val'));
console.log($('#note').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "note" value = "2">
Good day to all of you Ma'am and Sir
I have a problem to my project (never mind the name of the project because it is for privately use and it is for security of the website).
The problem is I can not access or forward the PHP Variable value to the external javascript file.
this is the code in insert.php
<?php
$username = $_POST['username'];
?>
<input type="text" id="code"/>
<button id="con_btn"/>Continue</button>
this is the code in insert_auth.js
$(document).ready(function(){
$("#con_btn").click(function(){
var code = $("#code").val();
$.ajax({
method: "post",
url: "post.php",
data:{
code:code,
},
success: function(data){
$("#insertresult").html(data);
}
});
});
});
I just want to get the value of the $username from php file. Thanks in advance!
I take it as you already have the POST value : $_POST['username'];. So, I'd suggest you to store this value as a hidden input field.
<?php $_SESSION['username'] = $_POST['username']; // Store username in session ?>
<input type="text" id="code"/>
<button id="con_btn"/>Continue</button>
Now, in your JS, you can access this hidden field value:
$(document).ready(function(){
$("#con_btn").click(function(){
var code = $("#code").val();
var username = "<?php echo $_SESSION['username']; ?>" // Read username from session
$.ajax({
/* Other code */
});
});
});
I'm trying to learn how does Ajax work and how I can send data by Ajax. I'm getting no error and nothing is being echoed.
index.html
<input id="name" type="text" /><input id="button" type="button" value="Load" />
<div id="feedback"></div>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="ajax.js"></script>
page.php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
}
?>
ajax.js
$('#button').click(function(){
var name = $('#name').val();
$.ajax({
url: 'page.php',
data: 'name='+name,
success: function(data){
$('#feedback').html(data);
}
});
});
I appreciate any help
You are missing an echo in your page php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
echo $name;
}
?>
also in your javascript send an object like this
data : { name : name}
should work
data : { name : 'John'}
you can check the success method is invoked or not invoked.
Also you need to echo something from php.
echo $name