I am able to run this successfully. I would love to accomplish the same thing with out the use of php. Main goal is to change the value of sel from the json file. Below is my php code and json code. the user.php changes the vaule of sel from the json file when a button is hit.
<?php
$jsonString = file_get_contents('sel.json'); //read contents from json file
$jsondata = json_decode($jsonString, true); //convert string into json array using this function
if(isset($_POST['button1'])) //if button is pressed?
{
$jsondata[0]['sel'] = 1; //initialise data to 1
}
if(isset($_POST['button2'])) //if button is pressed?
{
$jsondata[0]['sel'] = 2; //initialise data to 2
}
if(isset($_POST['button4'])) //if button is pressed?
{
$jsondata[0]['sel'] = 4; //initialise data to 4
}
if(isset($_POST['button6'])) //if button is pressed?
{
$jsondata[0]['sel'] = 6; //initialise data to 6
}
$newJsonString = json_encode($jsondata); //encode data back
file_put_contents('sel.json', $newJsonString); //write into file
?>
<!DOCTYPE html>
<html>
<body>
<p>json testing</p>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<button name="button1" onclick="placeorder()"> sel1:place order</button>
<button name="button2" onclick="cancleorder()">sel2:cancle order</button>
<button name="button4" onclick="unlockenotdone()">sel4:unlock UV box(notdone)</button>
<button name="button6" onclick="unlockedone()">sel6:unlock UV box(done)</button>
</form>
<p id="ui"></p>
<script>
var x = document.getElementById("ui");
function placeorder() {
console.log(1);
x.innerHTML = "Your Order has been Placed";
clear();
}
function cancleorder(){
var usrResponse=confirm('are you sure you want to cancle the order?');
if(usrResponse==true){
cancleconfirm();//call function ChangState2()
}
}
function cancleconfirm() {
console.log(2);
x.innerHTML = "Your Order has been canceled";
clear();//call function clear()
}
function unlockenotdone(){
var usrResponse=confirm('The sterilization is not done. Do you still want to unlock the book?');
if(usrResponse==true){
console.log(4);
openconfirm();
}
}
function unlockedone()
{
console.log(6);
openconfirm();
}
function openconfirm() {
x.innerHTML = "The UV book is now unlocked";
clear();//call function clear()
}
function clear()
{
setTimeout( function(){x.innerHTML="";}, 5000);
return false;
}
</script>
</body>
</html>
this is the sel.json [{"sel":1}]
Simply javascript can never do this, you must have to use of javaScript as well as php for this scenario..
You need to use XHR
step 1 -> handle file saving process as backend using php code.
step 2 -> make a method for button to hit a xhr code to excecute set1 file code
here we go
step 1
creating file with name savingJson.php
/* This is savingJson.php file */
/* here file saving code to handle */
$data = file_get_contents('php://input');
// define path for file
$file = $_SERVER['DOCUMENT_ROOT'] . '/sel.json';
// Write the contents back to the file
file_put_contents($file, $data);
step 2
calling XHR method on button click to run savingJson.php using javaScript
var jsonData = '[{"sel":1}]'
// calling method on button click
var button = document.getElementbyId("btn_id")
button.onclick = function(){
saveJsonToFile(jsonData)
}
function saveJsonToFile(jsonData) {
var xhr = new XMLHttpRequest();
var url = 'savingJson.php' /*path to savingJson.php file*/
xhr.open("POST", url, true); /* must be use POST for large data*/
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(jsonData);
}
Hope so this will help you,
Happy Coding!
Related
I have a server which I am storing standard text inputs once a submit button has been clicked, I have done this successfully and now need to recall all the inputs on a different button click. My lack of understanding of PHP starts to kick me as I have little to no idea how to retrieve this, I know that data within PHP files once ran is deleted so I need to create some sort of "storage" ( I found the use of $_SESSION to be the go to thing for this).
I then need to use my JS file to somehow recall the data that is temporarily stored but again have no idea how I can get an array that is stored on a PHP file across to a JS file.
Any brief explanation oh how this is done would be greatly appreciated as I am extremely new to PHP!
For reference I currently have:
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("Form Was Submitted");
// var returnData = xhttp.responseText;
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("Data retrieved")
// var returnData = xhttp.responseText;
}
}
xxhttp.open("GET", "gethint.php", true);
xxhttp.send();
}
HTML:
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
PHP:
<?
session_start();
echo $_SESSION["input_data"] = $_POST;
print_r($_POST);
echo "Text Submitted". $_POST["input"];
print_r($_REQUEST);
echo "Text Retrieved" . $_REQUEST["input"];
?>
In your php you can encode the post data as json like so:
$_SESSION['input_data'] = json_encode($_POST);
And in your js you can the get the data by decoding it like so:
var data = JSON.parse('<?php echo $_SESSION["input_data"]; ?>');
This will give you a js object that you can access using the name you gave your input tags in your html.
ex: data.textInput would get that value of the textarea.
To easily access the php data in js , you can store the data in session.also use json format to throw data to js and access it in js via jeson array key value format if you have multiple form field to store and access.
Use json_encode() to throw from php to js.
Also you can save this data in cookie. Session and cookie are temporary way to store data. For permanent storage use a database like mysql and call this from js with json.
Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.
i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>
I am trying to make table data cells editable. I am using a jQuery plugin called Jeditable to try and achieve this. Currently, I am using Ajax to get the necessary table data. My problem is when I try to edit the data nothing happens. I have tried using a table without ajax and it seems to work fine. Can anyone help me sort out this problem?
My Code:
<!DOCTYPE html>
<html>
<head>
<title>Attendance Alpha</title>
<?php require_once('header.php'); ?>
</head>
<script>
$('.status').editable('http://www.example.com/save.php', {
indicator : 'Saving...',
tooltip : 'Click to edit...'
});
</script>
<body onload="getStudents()">
<div id="studentData"><p class="loading">Loading student data...</p></div>
</body>
<script>
// START OF AJAX FUNCTION
function getStudents() {
// AUTO SETTING STR TO 1 (THIS IS FOR THE GET IN GET.PHP PAGE)
var str = "1";
// DEFINE XHTTP
var xhttp;
// CHECKS IF DATA HAS BEEN LOADED. THEN REMOVED THE "LOADING DATA" ALERT
if (str == "") {
document.getElementById("studentData").innerHTML = "";
return;
}
// STARTS NEW REQUEST (AJAX)
xhttp = new XMLHttpRequest();
// ONCE AJAX DATA HAS LOADED DEFINES WHERE TO PUT THE DATA
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("studentData").innerHTML = xhttp.responseText;
}
};
// BELOW HITS PAGE
xhttp.open("GET", "GET.php?main_page="+str, true);
xhttp.send();
}
// SETS INTERVAL ON HOW OFTEN THE PAGE SHOULD FETCH NEW DATA
setInterval(getStudents, 50000);
</script>
</html>
And on the GET page:
<?php
// REQUIRE NESSARY FILES
require_once('connection.php');
// QUERY STUDENTS
$query_results = $db_server->query("SELECT * FROM studentdata WHERE current = 1 ORDER BY firstname");
?>
<?php
// CHECKS IF GET VAR FOR DATA
if($_GET["main_page"] === "1") {
// PRINTING START OF TABLE OUTSIDE OF WHILE
print "<table>";
print "<th>Name</th>";
print "<th>Pr.</th>";
print "<th>Status</th>";
print "<th>Return</th>";
// GOING THROUGH STUDENT NAMES
while($row = $query_results->fetch_array()) {
// CONVERTS FIRST & LAST NAME INTO A SINGLE VARIABLE
// I WILL MAKE A FUNCTION FOR THIS SOON
$NN_first = $row["firstname"];
$NN_last = substr($row["lastname"], 0, 1);
$NN_full = $NN_first.' '.$NN_last;
// PRINTING TABLE ROW
print '<tr>';
// PRINTS FULL NAME VARIABLE
print '<td class="p_button"><span>'.$NN_full.'</span></td>';
// PRINTS P BUTTON
print '<td><input type="submit" value="P"></td>';
// PRINTS CURRENT STATUS
print '<td class="status">Field Trip</td>';
// PRINTS CURRENT STATUS RETURN TIME
print '<td class="return">EST. 11:45 am</td>';
// PRINTS END TABLE ROW
print '</tr>';
// BELOW CLOSES WHILE LOOP
}
// CLOSING TABLE
print "</table>";
// BELOW CLOSES CHECKING FOR GETTING DATA
}
?>
Here is what output.php returns:
My goal is to upload some images to a server and provide them with a description.
On clicking an upload button, this is what I want to happen:
1) a javascript function dynamically adds a form to get a description
of the images.
2) on submitting the form:
a) the description entered in the form must be available $_POST['description'] at server side.
b) the images are sent to the server using an XMLHttpRequest
In the code I wrote the description is not available $_POST['description'].
When i remove the check if(!isset($_POST['description'])), the imagefiles are perfectly uploaded.
This is my code:
javascript code
upload.onclick = uploadPrompt;
// dynamically add a form
function uploadPrompt () {
// fileQueue is an array containing all images that need to be uploaded
if (fileQueue.length < 1) {
alert("There are no images available for uploading.");
} else {
var inputDescription = document.createElement("input");
inputDescription.className = "promptInput";
inputDescription.type = "text";
inputDescription.name = "description";
var inputButton = document.createElement("button");
inputButton.id = "promptInputButton";
inputButton.type = "submit";
inputButton.innerHTML = "Start uploading";
var promptForm = document.createElement("form");
promptForm.method = "post";
promptForm.action = "upload.php";
promptForm.onsubmit = uploadQueue;
promptForm.id = "promptForm";
promptForm.appendChild(inputDescription);
promptForm.appendChild(inputButton);
document.body.appendChild(promptForm);
}
}
function uploadQueue(ev) {
ev.preventDefault();
elementToBeRemoved = document.getElementById("promptForm");
elementToBeRemoved.parentElement.removeChild(elementToBeRemoved);
while (fileQueue.length > 0) {
var item = fileQueue.pop();
// item.file is the actual image data
uploadFile(item.file);
}
}
function uploadFile (file) {
if (file) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('image',file);
xhr.upload.addEventListener("error", function (ev) {
console.log(ev);
}, false);
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(fd);
}
}
php code upload.php
<?php
session_start();
if (!isset($_POST['description'])) {
echo "upload:fail\n";
echo "message:No scene was specified";
exit();
}
if (isset($_FILES['image'])) {
if(!move_uploaded_file($_FILES['image']['tmp_name'], "uploads/" . $_POST['description'] . "/" . $_FILES['image']['name'])) {
echo "upload:fail\n";
}
else {
echo "upload:succes\n";
}
exit();
}
exit();
?>
I'd really advise against creating your own asynchronous file upload functionality when there is a plethora of developers who have already programmed the same thing better. Check out these options:
Blueimp's jQuery file uploader
Uploadifive (Uploadify's HTML5 implementation)
I've used these two before and they work very well. For BlueImp, you can use this option to send additional form data:
$('#fileupload').fileupload({
formData: $('.some_form').serialize()
});
The above captures a form and serializes its inputs. Alternatively, you can populate an array or object using specific values (i.e. from specific elements in your DOM):
var array = new Array();
$('.description').each(function() {
array[this.id] = this.value;
});
You'd use IDs to link your files and descriptions.