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.
Related
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 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:
So, first and foremost, I'm going to list the 3 sections of code that I'm referencing.
HTML:
<div id='newuserpage'>
<h1><font color='white'>Create New User</font></h1>
<div id='userbody'>
<div id='userfields'>
<div id='usernamelabel'>
<font color='white'>Enter Username:</font>
<input id='createfield1' type='text'>
</div>
<div id='passwordlabel'>
<font color='white'>Enter Password:</font>
<input id='createfield2' type='password'>
</div>
<div id='usertype'>
<br>
<font color='white'>User Type:</font>
<select name="typeofuser" id='type'>
<option value="2">Student</option>
<option value="1">Teacher</option>
</select>
<br><br>
</div>
<button id = 'newuserbutton' onclick='createuser()'>
Submit
</button>
<button id = 'backtomenu' onclick = 'backtomenu()'>
Back to Teacher Menu
</button>
Javascript Function
function createuser()
{
var newuser;
var newpass;
// check browser type
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
newuser = document.getElementById("createfield1").value;
newpass = document.getElementById("createfield2").value;
xmlhttp.onreadystatechange = function() {
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
if (xmlhttp.responseText == '1') { //Connected properly
var createdmessage= document.getElementById('createdmessage');
createdmessage.style.visibility= 'visible';
}
if (xmlhttp.responseText == '2') {
var loginpage = document.getElementById('loginbox');
loginpage.style.display = 'block';
}
else {
// show error message
loginlabelerror.style.visibility = 'visible';
}
}
}
// call php function
xmlhttp.open("GET","createuser.php");
xmlhttp.send("username=" + encodeURIComponent(newuser) + "&password=" + encodeURIComponent(newpass));
//var createdmessage= document.getElementById('createdmessage');
//createdmessage.style.visibility= 'visible';
}
PHP page to handle Insertion
<?php
$q=$_GET["username"];
$p=$_GET["password"];
$t=$_GET["type"];
$host="xxx"; // Host name
$username="xxx"; // Mysql username
$password="xxx"; // Mysql password
$db_name="xxx"; // Database name
// Connect to server and select databse.
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name",$link)or die("cannot select DB");
$sql="INSERT INTO users (username, password, type) VALUES('".$q."', '".$p."', 2)";
$retval = mysql_query($sql);
if(! $retval)
{
echo 2;
}
echo 1;
mysql_close($link);
?>
The problem I'm running into is that it's never actually pulling the values out of the createfield1 and createfield2 input areas. It just throws empty strings into the database.
(Ignore the drop down menu, That's something that we were toying around with but don't really need.)
As far as I can tell and can find online, what I've done SHOULD work? Unless I've completely misinterpreted something, I'm baffled as to why it's not actually retrieving the values that are entered into the input fields.
For demonstration purposes for an external source, I WANT blank fields to be allowed as essentially a "passthrough" where it doesn't actually do anything. The problem at hand is that even with an example of:
asdf
1234
entered into the two input fields, when the button calls the function to send the info over to be inserted, it doesn't pull those values, and instead just uses blank strings. I wouldn't expect value checking to be NEEDED for it to not use empty strings instead, one would think it should pull the values in the fields.
Slightly off topic, creation events should always be post, not get. http://www.w3schools.com/tags/ref_httpmethods.asp (there are more reputable sources out there but even they agree)
More importantly... Modify your send call..
xmlhttp.open("GET","createuser.php");
to be
xmlhttp.open("GET","createuser.php?username=" + encodeURIComponent(newuser) + "&password=" + encodeURIComponent(newpass));
You still need to call the send method.
Consider doing a post request instead: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
The number one reason for post/get, at least to me, is that get can be re-ran with no prompt. Post will at least warn the user and when it comes to account creation, a warning is in order.
I'm trying to insert data in a sql table using ajax and php, but it's not working. My ajax give me the result like it works, but when i look at the table, there's not in it. Doing it without ajax works fine, so i guess my php is working ok.
Here's the code:
HTML:
<form action="servico.php?p=cadUsr" method="POST" id="frmCadUsr">
Nome: <input type="text" maxlength="255" name="txtNome" id="txtNome"/>
Idade: <input type="text" maxlength="3" name="txtIdade" id="txtIdade"/>
<input type="submit" value="Enviar"/>
</form>
PHP:
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
switch($passo){
case "cadUsr":
cadUsr();
break;
default:
getRetorno();
break;
}
function getRetorno(){
echo "Este texto foi escrito via PHP";
}
function cadUsr(){
require("dbCon.php");
require("mdl_usuario.php");
$usr = $_POST["txtNome"];
$idade = $_POST["txtIdade"];
$resultado = usuario_cadastrar($con,$usr,$idade);
if($resultado){
echo "Cadastro efetuado com sucesso";
} else {
echo "O cadastro falhou";
}
}
?>
OBS: I need to pass the action of the form with the url parameter as cadUsr, so it call the function in php.
AJAX:
window.onload = function(){
var xmlhttp;
var frm = document.querySelector("#frmCadUsr");
var url = frm.getAttribute("action");
var nm = document.querySelector("#txtNome").value;
var idade = document.querySelector("#txtIdade").value;
frm.addEventListener("submit",function(e){
e.preventDefault();
try{
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("POST",url,true);
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//alert("Deu certo");
console.log(xmlhttp.responseText);
}
}
} catch(err){
alert("Ocorreu um erro.<br />"+ err);
}
});
}
The PHP function to insert the data:
function usuario_cadastrar($conexao,$nome,$idade){
if($nome == "" && $idade == ""){
return false;
}
$sql = sprintf("insert into usuario (nome,idade) values ('%s',%s)",$nome,$idade);
$resultado = mysqli_query($conexao,$sql);
return $resultado;
}
I think the problem is here servico.php?p=cadUsr. You copy the action-attribute from the form with a querystring. If you cut the querystring from it, I think it will work.
The main problem is being called by Hossein:
This :
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
Will not work. You're doing a post, you can't get GET variables.
You call value on value which will result in undefined and that will put no data in your database.
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
So remove value and add the cadUsr variable to the querystring in the send function. Update PHP to:
$passo = (isset($_POST['p'])) ? $_POST['p'] : "";
And it will work!
You can see your callback codes by adding console.log(xmlhttp.responseText); to your readystate success function.
Also you need to set the requestheader content-type to x-www-form-urlencoded when sending post.
The text file contains information that I want to use with my website for logging in purposes
Text file contains the following..line by line
user:password
user2:user2password
I have tried using blob to read the text file but variables are not getting stored so I would like to know where I am going wrong or if I am even able to read the file using this method
function readFile(){
var fileName = txtName.value;
file = login.txt;
var blob = file.read();
var readText = blob.text;
var lines = data.split("\n && : " );
//Adding the file content to the label placed
lblFileContent.setText(readText);
Ti.API.info(readText);
// dispose of file handle & blob.
file = null;
blob = null;
}
I've used this in the past to read a txt-file:
JavaScript (jQuery):
function readFile() {
$.post('path/to/php/read_file.php', {
dir: 'path/to/file',
file: 'file_name.txt',
},function(file_contents) {
if (file_contents != '') {
//your code here
}
});
}
PHP:
<?php
/* This script is invoked by 'index.html'.
* This script gets the content of the file that has been changed by
* the admin, and uses it to determine the path of the file
* that is currently set by the admin.
*/
$dir = $_POST["dir"];
$file = $_POST["file"];
$contents= '';
if ($dhandle = opendir("$dir")) {
while (false !== ($entry = readdir($dhandle))) {
if ($entry != "." && $entry != "..") {
if ($entry == $file) {
$entry_path = $dir.DIRECTORY_SEPARATOR.$entry;
$fhandle = fopen($entry_path, 'r');
$value = fread($fhandle, filesize($entry_path));
fclose($fhandle);
}
}
}
closedir($dhandle);
echo "$contents";
}
?>
You might want to try HTML 5 file API
1) To specify the text file add an input type file HTML tag (this will show a file selection dialog, if clicked).
<input type="file" id="myFileId">
2) Add a listener that will be executed when you choose a file, which triggers a 'change' event.
document.getElementById('myFileId').addEventListener('change', function(e) {
});
3) In the EventListener use FileReader to read your text file.
document.getElementById('myFileId').addEventListener('change', function(e) {
var file = document.getElementById('myFileId').files[0];
var reader = new FileReader();
reader.onload = function(e) {
var userPass = reader.result.split(" "); // split by space
// userPass is an array where each element has a user:pass
// do your stuff
} // onload
reader.readAsText(file);
});
You might want to check for file type/size before trying to read it.
Here is a solution you may be interested in.
Text file named login.txt containing I'm reading this file using JavaScript.
user
myuser
password
myuserpassword
My JavaScript code
var loadXMLDoc=function(){
var Credentials={};
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==0){
var temp=xmlhttp.responseText.split('\n');
for(i=0;i<temp.length;i++){
switch(temp[i].trim()){
case "user":
case "User":
Credentials.Username=temp[i+1];
break;
case "password":
case "Password":
Credentials.Password=temp[i+1];
break;
}
}
console.log(Credentials); //Printing the object in the console.
}
}
xmlhttp.open("GET","login.txt",true);
xmlhttp.send();
}
HTML input. Please note I'm call the js function here.
<input type="button" id="load" value="Click me!" onclick="loadXMLDoc();"/>
Print the password in console with a function getPassword("myuser").
var getPassword=function(username){ // It takes one string parameter which is the username.
var password="";
if(Credentials.Username){
if(Credentials.Username.trim()==username) password=Credentials.Password;
}
return password;
};