Jeditable not working with Ajax imported data - javascript

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:

Related

Read and write to json via html with out php

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!

PHP not able to read JSON but writes extra lines in SQL

I have an HMTL form with 3 fields on it, Firstname, Lastname and image upload file. When submit is pressed it calls the following JS script.
//main function to be called on submit
function processData() {
var firstName = document.querySelector('#first-name'),
lastName = document.querySelector('#last-name'),
imageUser = document.querySelector('#image-user');
var formSubmitData = {
'firstName': firstName.value,
'lastName': lastName.value,
'imageUser': imageUser.value
};
var dataString = JSON.stringify(formSubmitData);
if (navigator.onLine) {
sendDataToServer(dataString);
} else {
saveDataLocally(dataString);
}
firstName.value = '';
lastName.value = '';
imageUser.value = '';
}
//called on submit if device is online from processData()
function sendDataToServer(dataString) {
var myRequest = new XMLHttpRequest();
//new code added so data is sent to server
//displays popup message - data sent to server
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
console.log('Sent to server: ' + dataString + '');
window.localStorage.removeItem(dataString);
} else if (myRequest.readyState == 4 && myRequest.status != 200) {
console.log('Server request could not be completed');
saveDataLocally(dataString);
}
}
myRequest.open("POST", "write_test.php", true);
//Send the proper header information along with the request
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequest.send(dataString);
alert('Sent: ' + dataString + ''); //remove this line as only for example
}
As you will see it sends a POST request to the php page. The "datastring" is encoded as JSON.
I use the following PHP code to send the data to the SQL server, but all it does is create a blank record with no data but it does create a new record.
<?php
//TRYING NEW CODE TO EXTRACT DATA FROM dataString
$json = json_decode(file_get_contents("php://input"), true);
$data = json_decode($json, true);
echo '<pre>' . print_r($data, true) . '</pre>';
// INSERT into your contact table.
$sql="INSERT INTO contacts (firstName, lastName)VALUES('$firstName','$lastName')";
How do I get it to create records in SQL with data that has been submitted from the form??
I have no final solution as I don't have the form code. Hope you are ready to learn.
I'm worried about user image - don't send any image for testing, but a string (like path) or nothing, please.
js - change for double quotes:
var formSubmitData = {
"firstName" : firstName.value,
"lastName" : lastName.value,
"imageUser" : imageUser.value
};
php - leave only this
<?php
$data = json_decode(file_get_contents("php://input")); // test only version
print_r($data); // test only version
/*
and close the rest as a comment - SQL is fine, don't worry
$data = json_decode(file_get_contents("php://input",true)); // final ver
echo print_r($data, true); // final ver
...
*/
If you receive the right output, delete the trial version and good luck.
If not - go back to var formSubmitData to the values on the right - they are so naked ... without any quotes
And of course, take care of security (injection) and order, set the required at the inputs - you don't need empty submits

send content of dynamically changing div to database

I have a Server Send Event working and updating a webpage. I then assign the contents of the div receiving the SSE to a var so as to send it to a php file to insert into a database. The div's data is constantly changing in sseReceiving.php page, but how to send it and it's changing values to the database dynamically. Now it is only sending the div content to the database when the page is re-submitted. How to do it continually?
sseTriggering.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//generate random number for demonstration
$new_data = rand(0, 1000);
//echo the new number
//echo "data: New random number:". $new_data. "\n\n";
echo "data:".$new_data."\n\n";;
flush();
sseReceiving.php
<body>
<div id="serverData">Here is where the server sent data will appear</div>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("sseTriggering.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
var MyDiv = document.getElementById("serverData").innerHTML;
window.location.href = "findpair.php?pair=" + MyDiv;
};
}
</script>
</body>
findpair.php
$pair = $_GET['pair'];
$qX = "UPDATE product SET prod_name = '$pair' WHERE id = 1";
$rrr = mysqli_query ($dbc, $qX) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
I have researched this issue at the links below and some have helped me get it to the stage it is at now.
http://www.coderslexicon.com/the-basics-of-passing-values-from-javascript-to-php-and-back/
send javaScript variable to php variable
Get content of a DIV using JavaScript
Detect element content changes with jQuery
I have also put header('Refresh: 5'); in the php part of the various files and no change.
You should be able to send the request via AJAX for your main function which will allow the sse events to come to your client and then go to your findpair.php function.
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("sseTriggering.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
//Send AJAX request.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//Do something with 'xmlhttp.responseText' if you want.
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
} else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "findpair.php?pair=" + event.data, true);
xmlhttp.send();
};
}
More info here on submitting AJAX requests with javascript.

How to pass large array value from javascript to php

My requirement is to make multiple xml request and to store the data in an array so that if i get say for example 4000 records I can display 40 records in a page and can do pagination. So if i goto page2 I can get the data from the array instead of making the xml request again.
Currently I am using a php array variable to store large amount of data and on click a button javascript function will call the same php page again using ajax request through query string. The problem is that the query string can't hold large arrays.
Here is my code -
Passing php array to javascript variable
echo '<script type="text/javascript">/* <![CDATA[ */';
echo 'var allProd = '.json_encode($allProd);
echo '/* ]]> */</script>';
Using form calling javascript function through button click
<form id="new_page" name="new_page" method="post" action="" >
<td> Jump to page <input name="neggPage" id="neggPage" class="pageText" style="height:20px; width:40px"/></td>
<input type="hidden" name="hideProd" value="<?php echo htmlentities(serialize($allProd)); ?>" />
<td><input type="Submit" name="neggBut" value="Go" class="pageButton" onClick="get_results(document.getElementById('neggPage').value, <?php echo $sInd; ?>, <?php echo $rndTot; ?>, <?php echo $totEnt; ?>, allProd);">
Total pages <?php echo $rndTot; ?></td>
<td height="40"> </td>
</tr></table>
</form>
Javascript function
<script>
function get_results(PageNo, SelIndex, totPage, totEnt, allProd)
{
var allProd1 = '';
for (i=0; i < allProd.length; i++)
{
allProd1 += '&q[' + i + ']=' + encodeURIComponent(JSON.stringify(allProd[i]));
}
if (PageNo > totPage || isNaN(PageNo))
{
alert ('Please enter the available pages');
}
else
{
var neggProd = sessionStorage.getItem('Product1');
var cntryCode = sessionStorage.getItem('Cntry');
var sortType;
var ordType;
if (SelIndex == 0) {sortType = 'bestmatch';}
else if (SelIndex == 1) {sortType = 'bestseller';}
else if (SelIndex == 2) {
sortType = 'pricehigh';
ordType = 'dsc';
}
else if (SelIndex == 3) {
sortType = 'pricelow';
ordType = 'asc';
}
document.getElementById("sl_api").innerHTML="";
document.getElementById("sl_api1").setAttribute("style","background: url('KartEazy/loading.gif') #edeeee no-repeat center center; background-size:20px 20px;");
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("sl_api").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET",'KartEazy/Skimlinks/Skimlinks.php?PageNum=' + PageNo + '&neggProd=' + neggProd + '&cntryCode=' + cntryCode + '&sortType=' + sortType + '&ordType=' + ordType + '&totEnt=' + totEnt + allProd1, true);
xmlhttp.send();
setInterval(function() {
document.getElementById("sl_api1").setAttribute("style","background: #edeeee;")},4500);
}
}
</script>
In the same page now I am trying to get the array
if(isset($_REQUEST['q']))
{
$totEnt = $_REQUEST['q'];
}
I tried using hidden form variable but even $_POST also not accepting large arrays. Could any of you please give me a solution or suggestion. It will be very helpful for me.
Even storing the data in database or session variable will not solve my requirement. Because if I use database I can't retrieve data for multiple queries and even php session variable will be overwritten if the user uses multiple tabs for the same url.
I was in a similar situation where I was passing several MEG of data from Javascript to PHP.
I don't have the code with me, so I can only give you a p-code solution, but it will give you the idea.
// JavaScript:
var bigstring = "...."; the data to pass
var chunkSize = 100*1024;
// http://stackoverflow.com/questions/7033639/javascript-split-large-string-in-n-size-chunks
var chunks = splitString(bigstring);
var chunkIdx = -1; // Prime the pump
function sendNextChunk() {
chunkIdx++;
if (chunkIdx < chunks.length) {
// Your AJAX call here
var data = {
piece: chunkIdx
ofpieces: chunks.length;
}
// set your onsuccess method to call
// sendNextChunk again
}
}
sendNextChunk(); // start it.
Now, for your PHP code:
// Read in each chunk, and the piece number.
// The way I've got the code written, then come in sequentional order
// so open up a temporary file and append the data.
// when piece === ofpieces
// you have the whole file and you can then process it.

How to display this message within the correct row, not within all rows

Below is the code where it is displaying the delete message but it is displaying it in each row, this is incorrect, it should on;y be displayed in the row the file was deleted from:
var counter = 0;
function stopImageUpload(success, imagefilename){
var result = '';
counter++;
if (success == 1){
result = '<span class="imagemsg'+counter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$(".imagemsg" + counter).html(data);
});
$(this).parent().remove();
});
return true;
}
The result variable is called here in the imageupload.php:
CALLBACK:
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result ? 'true' : 'false'; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');</script>
Here is the link to the application here.
Please do this, click on the "Add" button twice, in both rows use the file inputs to upload an image. In both rows it will state that file upload was a success and it will display a name of both file at the bottom of their respective rows. Now delete a file by clicking on the delete button, you will see that the message (File was Deleted) is displayed in both rows, it should only be displayed within the row the file was deleted from
Because you are initializing counter inside the function it will be a local variable, therefore the value will be ZERO every time. You need to initialize it outside of the function.

Categories

Resources