Transfer javascript variable to external page - javascript

I need to retrieve an attribute from an image. This attribute then needs to be send to the original page. I use a .load to load the page where you click on an image, which then retrieves the attribute, on the "internal" page.
So what I basically want:
You get on the "internal page"
You click on an image from the ajax-loaded "external page".
The attribute "src" is then loaded into a variable
This variable gets send back to the "internal page"
I can use the sent variable.
This is what I got so far:
External page:
<script type="text/javascript">
$(document).ready(function() {
$(".imgid").click(function() {
var imgname = $(this).attr('src');
var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE
var url = 'internalpage.php?js_var=' + imgname;
xhr.open('GET', url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
var div = document.getElementById('update');
div.innerHTML = xhr.responseText;
}
}
xhr.send();
// ajax stop
});
});
</script>
<fieldset>
<label for="portal_id">Afbeelding Portal</label>
<?php $photos = Beeldbank::find_all(); ?>
<?php $rows=3; $cols=4;$i=1; $row_counter=0; echo '<table>'; foreach($photos as $photo): if($row_counter<$rows){
if($i==1) { echo '<tr>'; }
echo '<td>'.'<img src="../'.$photo->image_path().'" width="125" class="imgid" />'.'</td>';
echo '<td>'.'<input type="hidden" id="filename" name="filename" value="'.$photo->naam.'" />'.'</td>';
if(($i%$cols)==0){ echo '</tr><tr>'; $row_counter++; }
}
$i++;
endforeach;
echo '</table>'; ?>
</fieldset>
Internal page:
<script type="text/javascript" src="../javascripts/SelectImage.js"></script>
Afbeelding Portal<br />
<button id="select_portal" type="button">Selecteer Afbeelding</button>
<div id="dialog-form" style="display:none; position:absolute; width:auto; height:auto;"></div>
The js file:
$(document).ready(function(){
$( "#select_portal" )
.button()
.click(function() {
$("#dialog-form").css("display", "block");
$("#dialog-form").css("top", "50%");
$("#dialog-form").css("left", "50%");
$("#dialog-form").css("backgroundColor","white");
$("#dialog-form").load("externalpage.php");
});
});

If I understood your question right you need to post the result back to a php page. So you can use jQuery POST to send a value you have read using jQuery.

Related

Javascript dynamicly change DOM using PHP

PHP code
<?php
...
//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$findemail = [
"email" => $email,
"password" => $password,
];
$cursor = $collection->findOne($findemail);
if($cursor){
if($cursor['email'] == $email and $cursor['password'] == $password){
// I Know these two lines don't work but I want to show what I want to do
echo "success";
header('location: cms-view-products.html');
}
else {
echo "failed";
header('location: login.php');
}
}
?>
AND this is my HTML code
<?php include('demo2.php') ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="demo2.php" onsubmit="return false"; method="post">
Email: <input type="email" name="email" required >
name: <input type="password" name="password" required >
<button type='submit' onclick="loadContent()">Load</button>
</form>
<div id="ServerContent">
<p>Dynamically loaded content goes here</p>
</div>
<script>
function loadContent(){
var url = "demo2.php";
var email = document.getElementsByName('email').value;
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById("ServerContent").innerHTML = this.responseData;
}
else
alert("Error communicating with server");
}
var data = `JSON.stringify({
"email": "document.getElementsByName('email').value",
"name": "document.getElementsByName('name').value"
})`;
xhr.send(data);
}
</script>
</body>
</html>
I've currently tried to echo the message via JS, the specific element <p id=" feedback"></p>, nevertheless it doesn't work. With PHP the process works, nevertheless, I can't redirect users using headers. I've found $_SESSION could resolve this issue. However, my question is to use JS to open a pop-up and then redirect the user to x page?
I edited the post since comments advised me about using Ajax and so this is my first attempt. I can always achieve one of the two either redirect the user to x page or show an error massage. but I can't do both.
Also, I don't want to alert the massage, but to change HTML element dynamically.
Thanks guys for your time and comments.

Ajax is submitting the text, but not able to submit HTML data

I am working on a code that will fetch the data from textarea and submit it through ajax on button click.
In next step, PHP will create a file on server and store the ajax data into file.
I have already tried addslashes function of PHP, but that is not working.
I have tried to do it via the above method and its submitting the text data successfully. But the issue is with HTML data. I think it must be a parsing problem.
The HTML code
<textarea id="textareaCode"></textarea>
The Javascript code with Ajax
<script>
function makePage(){
var comment = document.getElementById('textareaCode').value;
alert (comment);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = comment;
xmlhttp.open("GET","makePage.php?content=" + content,true);
xmlhttp.send();
}
</script>
And Finally the PHP code
<?php
$content = $_GET["content"];
$file = uniqid() . ".html";
file_put_contents("userdata/$file", $content);
echo $file;
?>
I am not getting any error message
You should do it with POST instead of GET, like Teemu said:
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
This row set the right header.
<textarea id="textareaCode"></textarea>
test
<script>
function makePage(){
var comment = document.getElementById('textareaCode').value;
alert (comment);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = JSON.stringify({ comment: comment });
xmlhttp.open("POST","makePage.php",true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(content);
}
</script>
PHP:
<?php
$data = json_decode(file_get_contents('php://input'), true);
$content = $data['comment'];
$file = uniqid() . ".html";
file_put_contents("userdata/$file", $content);
echo $file;
?>
Post will work this way
function makePage(){
var data = document.getElementById('textareaCode').value;
$.post("makePage.php", {content: data}, function(result){
//Do something with the result
});
};
Then the php
$content = $_POST['content'] or $_REQUEST['content']

pass javascript value to php in exact page without refresh

i'm new to this so i hope you could help me.
i'm try to build one page has the ability to add and remove from sqldb.
from some reason i have to send value from js to php and i try this basic code and it doesn't work .
<html>
<head>
<script src="resources/js/jquery-2.2.3.js"> </script>
</head>
<body>
<form method="get">
<input type="button" value="submit" name="submit" class="test">
</form>
<div id="state"></div>
</body>
<script type="text/javascript">
$('.test').click(passValue);
function passValue(e){
document.getElementById('state').innerHTML="button is clicked";
var js_var = "xml recevid";
var xhr = new XMLHttpRequest();
var url = 'test.php?js_var=' + js_var;
xhr.open('GET', url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
document.getElementById('state')xhr.responseText;
}
}
xhr.send();
}
</script>
<?php
if (isset($_GET['js_var'])) $php_var = $_GET['js_var'];
else $php_var = "<br />js_var is not set!";
echo $php_var;
?>
USE $php_var ="<script type='text/javascript'>document.write('js_var');</script>";
NOTE THAT js_var shoul be a global variable, not local one.

AJAX: showing updated variable after button click

I just started to use AJAX, so I apologize if the question is very basic.
I use a simple AJAX script to update a session variable depending on which button you click, but I cant get it to update the heading with the new value when clicking the button. At the moment I got a button to reload the page, but I want to remove that and make the header update on each buttonclick.
index.php
<?php session_start(); ?>
<html>
<head>
<script type='text/javascript'>
function setSession( value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "setSession.php?variable=rider&value=" + value, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo "<h1>You selected: " . $_SESSION['rider'] . "</h1>";
echo "<button type='button' onclick='javascript:setSession(this.value)' value='Kristoff'>Kristoff</button> ";
echo "<button type='button' onclick='javascript:setSession(this.value)' value='Edvald Boasson Hagen'>Edvald Boasson Hagen</button> ";
echo "<input type='submit' value='Re-Load Page'>";
?>
</body>
</html>
setSession.php
<?php
session_start();
if(isset($_REQUEST['variable']) && isset($_REQUEST['value']))
{
$variable = $_REQUEST['variable'];
$value = $_REQUEST['value'];
$_SESSION[$variable] = $value;
}
?>
#Chris and #tej explains the procedure.This is how you do it.
setSession.php
<?php
session_start();
if(isset($_REQUEST['variable']) && isset($_REQUEST['value'])){
$variable = $_REQUEST['variable'];
$value = $_REQUEST['value'];
$_SESSION[$variable] = $value;
echo $_SESSION[$variable];
}
?>
index.php
echo "<h1 id='selection'>You selected: " . $_SESSION['rider'] . "</h1>";
function setSession( value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "setSession.php?variable=rider&value=" + value, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("selection").innerHTML = "You selected ".xmlhttp.responseText;
}
}
xmlhttp.send();
}
At the moment index.php is only loaded once. Therefore $_SESSION['rider'] has been output once and only once so it won't change. You need to use javascript to read the response from the xhr you're doing (and at the same time output $_SESSION['rider'] in the setSession.php file.
I'm not sure of what your application is trying to do but this can be achieved without any php at all.
After triggering ajax call you have to modify the h1 already displayed.
Add a class to h1 and use jQuery or JavaScript to modify the value once ajax is complete.
if(xhr.status===200){
$('.header').text(//rider text);
}
This will set the value after ajax and if user refreshes page it will automatically load from session.
But as other answer suggests this can easily be attained without php itself but I will leave application technology decision to you.

How to retain the values displayed in the HTML after it is fetch from the PHP?

I have an HTML page that takes the user input and displays the output based on the database. I have a hyperlink to the other pages. I want when I navigate from first page to other HTML page, I add a back button and it shoud return to the first page but it should show the fetched values. Here is the code below.
1st HTML:
<script>
function PostData() {
var online = navigator.onLine;
if(online){
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var userid = document.getElementById("userid").value;
var pid = document.getElementById("pid").value;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'login3.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("userid=" + userid + "&pid=" + pid);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
else{
alert("You are offline");
}
}
</script>
</head>
<body>
<form>
<label for="userid">User ID :</label><br/>
<input type="text" name ="userid" id="userid" /><br/>
<label for="pid">Password :</label><br/>
<input type="password" name="password" id="pid" /><br><br/>
<div id="div1">
<input type="button" value ="Login" onClick="PostData()" />
</div>
</form>
</body>
PHP:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
?>
2nd HTML:
<body>
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="imageid" name="image" onchange="readURL();" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
BACK
</form>
</body>
I want to retain the values fetched on the 1stHTML.html
It's best to use session. Once the user has completed the first form set a session to signal that, so when they return to the first page it will read the session and automatically redirect them to the necessary page.
You'll need to put this at the top of your 1sthtml.php and 2ndhtml.php page to signal that you want to use sessions:
<?php
session_start();
On your 1sthtml.php page you'll need to set the session information:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
// ---- SET SESSION HERE ---
$_SESSION['stage'] = 1;
}
?>
And then, on the 1sthtml.php again you'll need to check to see if that session variable exists, if it does then forward onto the page you want. So, at the top of your 1sthtml.php, next to your previous session_start():
<?php
session_start();
if (isset($_SESSION['stage'])) {
header('Location: 2ndhtml.php');
exit();
}

Categories

Resources