Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a PHP file contain some calculation. Now, I want to integrate the calculation into javascript in another file. How i can pass the variable in javascript to do calculation inside php?
this is my javascript code:
$("#upload").on("click", function(){
var csv = $('#csv');
var csvFile = csv[0].files[0];
var ext = csv.val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) === -1){
alert('upload csv');
return false;
}
if(csvFile != undefined){
reader = new FileReader();
reader.onload = function(e){
csvResult = e.target.result.split(/\r|\n|\r\n/);
var temp=[];
for(i=0;i< csvResult.length; i++){
if(csvResult[i] != "" && csvResult[i] != null){
var data = csvResult[i].split(",");
var rssi = data[0];
var distance = data[1];
var rssisample = 8;
if(distance == 1){
//need to insert calculation method from php
temp.push(rssi);
}
}
}
I have php file name myphpfile.php. So, I want to use variable and value from javascript to perform calculation in php file and return back to javascript. Please help me on this
This is my some part of php file. eg: myphpfile.php
<?php
// $arrTimeRSSI will read from javascript before perform this calculation
//calculate mean X using array_sum() method
$avgRSSI = array_sum($arrTimeRSSI)/($num_of_elements);
function StandardDeviation($arrTimeRSSI){
global $num_of_elements;
global $avgRSSI;
$variance = 0.0;
foreach($arrTimeRSSI as $x){
//sum of squares of difference between all numbers and mean X
$variance += pow(($x - $avgRSSI), 2);
}
$newElements = $num_of_elements - 1;
return (float)sqrt($variance/$newElements);
} ?>
It is not that simple because PHP is executed on the server and JavaScript by the client. You have to use ajax to send your request with data to a php script (to the server) and get the response back to the client.
This is an example how your JavaScript can look like:
$("#upload").on("click", function(){
var csv = $('#csv');
var csvFile = csv[0].files[0];
var ext = csv.val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) === -1){
alert('upload csv');
return false;
}
if(csvFile != undefined){
reader = new FileReader();
reader.onload = function(e){
csvResult = e.target.result.split(/\r|\n|\r\n/);
var temp=[];
for(i=0;i< csvResult.length; i++){
if(csvResult[i] != "" && csvResult[i] != null){
var data = csvResult[i].split(",");
var rssi = data[0];
var distance = data[1];
var rssisample = 8;
if(distance == 1){
$.ajax({
url: '/path/to/phpfile.php',
type: 'post',
// transmit your data
data: {number1: '15', number2: '15'},
success: function (response) {
// handle the response
// response should contain 225 in this example
}
});
temp.push(rssi);
}
}
}
}
}
});
And this is how your PHP file at /path/to/phpfile.php could look like:
// do your calculations here and echo it
echo intval($_POST['number1']) * intval($_POST['number2']);
Another method is to make a php file and embed your javascript in it.
But this solution does not allow you to transfer data from javascript to php. Because the php function is executed on the server and the javascript (with the calculated part) is send to the client after that. Like this example:
<?php
// declare your php function here
function calculate() {
return;
}
?>
<script>
$("#upload").on("click", function(){
var csv = $('#csv');
var csvFile = csv[0].files[0];
var ext = csv.val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) === -1){
alert('upload csv');
return false;
}
if(csvFile != undefined){
reader = new FileReader();
reader.onload = function(e){
csvResult = e.target.result.split(/\r|\n|\r\n/);
var temp=[];
for(i=0;i< csvResult.length; i++){
if(csvResult[i] != "" && csvResult[i] != null){
var data = csvResult[i].split(",");
var rssi = data[0];
var distance = data[1];
var rssisample = 8;
if(distance == 1){
var calculation = <?php echo calculate(); ?>
temp.push(rssi);
}
}
}
}
}
});
</script>
this can be done by creating a formdata and pass it to the php file which on it returns values.
In my experience it is best to pass json values and return them from the php file as well.
javascript function:
function example(){
var form_data = new FormData();
form_data.append("Variable1ToPass","test1");
form_data.append("Variable2ToPass","test2");
$.ajax({
url: '/ThePhpFileYourReferTo.php',
type: 'POST',
dataType: 'json',
cache: false,
async: false,
data: form_data,
contentType: false,
processData: false,
error: function(ReturnData){
//here do the error handling
console.log(ReturnData);
return;
},
success: function(ReturnData) {
console.log(ReturnData.ResultOfCalculation);
return;
}
});
}
In the php file (ThePhpFileYourReferTo.php):
$DataToReturn = [];
$DataToReturn['SubmittedValue'] = $_POST;
$Variable2ToPass = $_POST['Variable2ToPass'];
$Variable2ToPass = $_POST['Variable2ToPass'];
//here do the calculation and write in the return variable
$DataToReturn['ResultOfCalculation'] = "OK DONE";
header('Content-type: application/json');
echo json_encode($DataToReturn);
Related
I have two files: one file contains php code (and it works properly) and the other one contains javacript.
The problem is in javascript page:
function calcDist() {
var citta = $("#txtpartenza").val();
$.ajax({
type: "POST",
url: 'mostraPartenze.php',
dataType: "json",
success: function (data) {
$.each(data, function (index) {
var partenza = data[index];
trovaGeo(citta, partenza);
});
}
});
}
function trovaGeo(partenza, destinazione) {
var latPartenza;
var lonPartenza;
var latDestinazione;
var lonDestinazione;
console.log(partenza); // for test
console.log(destinazione); // for test
var xmlhttpPart = new XMLHttpRequest();
var xmlhttpDest = new XMLHttpRequest();
xmlhttpPart.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+partenza+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpPart.send();
xmlhttpDest.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+destinazione+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpDest.send();
xmlhttpPart.onreadystatechange = function () {
if (xmlhttpPart.readyState == 4 && xmlhttpPart.status == 200) {
xmlhttpDest.onreadystatechange = function () {
if (xmlhttpDest.readyState == 4 && xmlhttpDest.status == 200) {
var resPart = JSON.parse(xmlhttpPart.responseText);
latPartenza = resPart.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
lonPartenza = resPart.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
var resDest = JSON.parse(xmlhttpDest.responseText);
latDestinazione = resDest.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
lonDestinazione = resDest.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
lonDestinazione = resDest.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
console.log(latPartenza);
}
};
}
};
}
Ajax works correctly; I can call trovaGeo(citta, partenza) without problems but in trovaGeo(partenza, destinazione) function, XMLHttpRequest "part" doesn't work properly: in console the variable latPartenza is never printed and obviously all codes in xmlhttpPart.onreadystatechange = [...] it's never executed.
For completeness this is the heart of php file:
$i = 0;
$citta = array();
while ($rows = $result->fetch_assoc()) {
$citta[$i] = $rows['partenza'];
$i=$i+1;
}
echo json_encode($citta);
I find the problem.
I have to use preventDefault in the first line of the event of on('submit'...
This is the solution:
$('form').on('submit', function (e) {
e.preventDefault();
[...]
The problem might be with nested onreadystatechagestatements , there might be a delay in responses. But I can see that second request is dependent on first request response.try the below change
xmlhttpPart.onreadystatechange = function() {
if (xmlhttpPart.readyState == 4 && xmlhttpPart.status == 200) {
xmlhttpDest.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext=" + destinazione + "&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpDest.send();
xmlhttpDest.onreadystatechange = function() {
// your code
console.log(latPartenza);
}
};
}
};
I'm currently reading csv headers using following js code -
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
contents = contents.split(/\r\n|\n/);
var i = 0,
flag = false,
headers;
while (i < contents.length && flag == false) {
if (contents[i] != '') {
headers = contents[i]
flag = true;
}
i++;
}
vm.fileHeaders = headers.split(",").map(function(item) { return item.trim() && item.replace(/['"]+/g, ''); });
return true;
};
r.readAsText(item);
This code reads the whole file first & then returns headers. But it takes more time for large sized files. I want to modify this code that will only read the header & not the whole data, So that it'll take less time for large files too.
Found PapaParse as a quick solution!
Papa.parse(item, {
worker: true,
skipEmptyLines: true,
step: function(results, parser) {
parser.abort();
vm.fileHeaders = results.data[0] || undefined;
results = null;
return vm.fileHeaders;
},
complete: function(results){
results = null;
}
});
This is the javascript for a simple multifile upload.
This javascript works on my development server no problem. But when I put it on my production server I get a 500 error on the AJAX Post. Could this be because I have to edit php.ini more? or are there other problems?
var app = app || {};
(function(o){
"use strict";
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState ===4){
if(this.status===200){
//console.log('here');
uploaded = JSON.parse(this.response);
if(typeof o.options.finished==='function'){
o.options.finished(uploaded);
}
}else{
if(typeof o.options.error ==='function'){
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event){
var percent;
if (event.lengthComputable ===true){
percent = Math.round((event.loaded / event.total)*100);
//console.log(percent);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for( i=0;i<source.length;i=i+1){
data.append('file[]',source[i]);
}
data.append('ajax',true);
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined){
o.options.progressBar.style.width=value? value + '%': 0;
}
if(o.options.progressText !== undefined){
o.options.progressText.innerText=value? value + '%': '';
}
};
o.uploader = function(options){
o.options = options;
if(o.options.files!== undefined){
ajax(getFormData(o.options.files.files));
}
};
}(app));
giorgio helped me get on the right track
I was using $uploaded = []; in my php, if I am not mistaken this is old PHP and the correct way is $uploaded = array(); I am using about 5 array and I guess that XAMP is so lenient that it will run what ever I give to it.
I have following two methods that uploads an image to a remote servlet. For some reason the second parameter which is the arraybuffer is not written to the post request and I am trying to figure out why this is happening. Could some one assist me on this.
setupBinaryMessage = function(metadata) {
log(metadata);
var msglen = metadata.length;
var localcanvas =document.getElementById("image");
var fullBuffer;
var myArray;
if(localcanvas){
var localcontext = localcanvas.getContext('2d');
//FOLLOWING 2 LINE OF CODE CONVERTS THE IMAGEDATA TO BINARY
var imagedata = localcontext.getImageData(0, 0, localcanvas.width, localcanvas.height);
var canvaspixelarray = imagedata.data;
var canvaspixellen = canvaspixelarray.length;
var msghead= msglen+"";
var fbuflen = msglen +canvaspixellen+msghead.length;
myArray = new ArrayBuffer(fbuflen);
fullBuffer = new Uint8Array(myArray);
for (var i=0; i< msghead.length; i++) {
fullBuffer[i] = msghead.charCodeAt(i);
}
for (var i=msglen+msghead.length;i<fbuflen;i++) {
fullBuffer[i] = canvaspixelarray[count];
count++;
};
return myArray;
} else
return null;
};
upladlImageWithPost= function() {
var message =JSON.stringify(this.data);
var fullBuffer = this.setupBinaryMessage(message);
var formdata = {command : "post", imagedata : fullBuffer,};
alert(jQuery.isPlainObject( formdata ));
var imgPostRequest = $.post( "http://localhost:8080/RestClient/RestClientPOST",fullBuffer, function(response) {
response = response.trim();
console.log(response);
if(response == "SERVER_READY"){
alert(response);
try {
}catch (error) {
alert("Web Socket Error "+error.message);
}
} else {
alert("SERVER ERROR");
}
}.bind(this))
Alright After some help from a GURU I figured the issue. Apparently ARRAYBUFFER is obsolete and real solution is to post the unisinged buffer as it is. But even for that I need to set the AJAX response type to ARRAYBUFFER and then not use JQuery $.post but
use original pure XHTTPRequest.
Source
I am developing a html application for Android and I am trying to load images in a list view. Data specific to list items is being served by multiple xml files. I am using ajax to load xml files and populate the list items. Problem I am facing here is that there are 164 list items. Hence, 164 images and 10 xml files to load. my loader function exhausts after two iterations. It does read the xml files but it's unable to dynamically create list items and populate them with images after two iterations. I believe it's due to stack limitations. I can't think of alternate solution. If somebody could suggest an alternate solution that will be highly appreciated. Below is my loader function. It's a recursive function:
function loadChannels() {
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){ console.log('Error Loading Channel XML'); },
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
loadChannels();
}
}
});
}
try to remove the recursion with an outer loop - something like that:
function loadChannels(){
var stopFlag = false;
// request the pages one after another till done
while(!stopFlag)
{
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){
console.log('Error Loading Channel XML');
errorFlaf = true;
},
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
// lets disable the recursion
// loadChannels();
}
else {
stopFlag = true;
}
}
});
}
}