Asked  7 Months ago    Answers:  5   Viewed   42 times

How do I go about passing data from JavaScript code to PHP and back. Right now, I do this is a round about way:
PHP to JavaScript: I would simply use the inline echo to send the data:

<script type="text/javascript">
    var data = <? echo $target_variable ?>


<script type="text/javascript">
    var data = <?= $target_variable ?>

JavaScript to PHP: I would create a form element in the JavaScript that would sumbit the data for me to the php file:

<script type="text/javascript">
    var data = targetData;
        <form method="post">
            <input type="hidden" value=""+target_value+""></input>

Are there any better ways to do this? Best practices sort of thing.



If you wish to submit this data via a form, you don't need to create the form with Javascript. Simply create an invisible form with HTML, populate the hidden field with Javascript, and automatically submit whenever you're ready.

  <form method="post" action="process.php">
    <input type="hidden" name="data" id="data" />

  document.getElementById("data").value = "foo";

If you want to send this in an ajax-style fashion, I would suggest implementing jQuery, which makes this extremely easy. Note the previous case converted to a jQuery solution:

$.post("process.php", {data:"foo"}, function(results){
  // the output of the response is now handled via a variable call 'results'
Wednesday, March 31, 2021
answered 7 Months ago

Use this trick and bind an onerror event to an Image element.

Demo here: — works on the latest Chrome.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = '';

// Trick from
var image = new Image;
image.src = link.href;
image.onerror = function() {
    ctx.font = '50px "Vast Shadow"';
    ctx.textBaseline = 'top';
    ctx.fillText('Hello!', 20, 10);
Wednesday, March 31, 2021
answered 7 Months ago

If the browser doesn't have the file in cache, "skipping" causes the browser to send a new request, with a "range" header. Your PHP file needs to handle this header.

this means:

  1. get and parse the range header
  2. respond to the request with status code 206 and corresponding range headers
  3. output only necessary bytes
Saturday, May 29, 2021
answered 5 Months ago

You might be able to use client/server sockets. I haven't tried this on Android, but I assume it would work as long as you have internet access. Matlab client-server and Java client-server should be compatible, in that you should be able to run a server in Matlab and connect to it from a Java client on android. The Matlab server could look like:

tcpipServer = tcpip('',port,'NetworkRole','Server');
imageSize = fread(tcpipServer, 2, 'int32');
image = zeros(imageSize(1), imageSize(2), 3);
for x=1:imageSize(1)
  for y=1:imageSize(2)
    image(x, y, :) = fread(tcpipServer, 3, 'double');
%Process image
fwrite(tcpipServer, results, 'double'); %or 'char'

And the Java client could be something like:

Socket s = new Socket(<Server IP>, port);
out = new PrintWriter(s.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));

for (int x = 1; x < image.getWidth(); x++) {
  for (int y = 1; y < image.getHeight(); y++) {
    //Write the RGB values. I can't remember how to pull these out of the image.

String results = in.readLine();

I'm not exactly sure how things will work with datatypes. Maybe something other than PrintWriter would be better, or you might have to send everything as char[] and then parse it at the other end.

Friday, August 20, 2021
answered 2 Months ago

You should ask the Location Manager to update the location for you instead of setting up a 1-second NSTimer to do it yourself. And to pass data to Javascript, you can use evaluateJavaScript method of WKWebView:

import UIKit
import WebKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
    weak var webView: WKWebView!
    let locationManager = CLLocationManager()

    override func viewDidLoad() {

        locationManager.delegate = self

    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

    func createWebView() {
        let url = NSBundle.mainBundle().URLForResource("my_page", withExtension: "html")!

        let webView = WKWebView()
        webView.loadFileURL(url, allowingReadAccessToURL: url)
        webView.translatesAutoresizingMaskIntoConstraints = false


        // Auto Layout
        let views = ["webView": webView]
        let c1 = NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: [], metrics: nil, views: views)
        let c2 = NSLayoutConstraint.constraintsWithVisualFormat("V:[webView]|", options: [], metrics: nil, views: views)
        let c3 = NSLayoutConstraint(item: webView, attribute: .Top, relatedBy: .Equal, toItem: self.topLayoutGuide , attribute: .Bottom, multiplier: 1, constant: 0)
        NSLayoutConstraint.activateConstraints(c1 + c2 + [c3])

        // Pass the reference to the View's Controller
        self.webView = webView

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let lastLocation = locations.last!

        let dict = [
            "lat": lastLocation.coordinate.latitude,
            "long": lastLocation.coordinate.longitude
        let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
        let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding)!

        // Send the location update to the page
        self.webView.evaluateJavaScript("updateLocation((jsonString))") { result, error in
            guard error == nil else {

And my_page.html:

<!DOCTYPE html>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width; initial-scale=1.0">
    <title>This is a test page</title>
    <script type="text/javascript">
    function updateLocation(data)
        var ele = document.getElementById('location');
        ele.innerHTML = 'Last location: lat = ' + data['lat'] + ', long = ' + data['long'];
    <p id="location">Last location:</p>

If you are testing this in the Simulator, choose Debug > Location > City Run to see it update continuously (as if you are running through a park).

Wednesday, September 8, 2021
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :