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>

OR

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

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;
    document.write("
        <form method="post">
            <input type="hidden" value=""+target_value+""></input>
        </form>
    ");
</script>
</script>

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

 Answers

100

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" />
  </form>

  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'
  alert(results);
});
Wednesday, March 31, 2021
 
StampyCode
answered 7 Months ago
18

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

Demo here: http://jsfiddle.net/g6LyK/ — 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 = 'http://fonts.googleapis.com/css?family=Vast+Shadow';
document.getElementsByTagName('head')[0].appendChild(link);

// Trick from https://stackoverflow.com/questions/2635814/
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
 
JustSteveKing
answered 7 Months ago
60

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
 
bumperbox
answered 5 Months ago
47

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('0.0.0.0',port,'NetworkRole','Server');
fopen(tcpipServer);
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');
  end
end
%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()));

out.println(image.getWidth());
out.println(image.getHeight());
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
 
Yoshi
answered 2 Months ago
82

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() {
        super.viewDidLoad()

        createWebView()
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
        locationManager.requestWhenInUseAuthorization()
    }

    override func didReceiveMemoryWarning() {
        super.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

        self.view.addSubview(webView)

        // 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 {
                print(error)
                return
            }
        }
    }
}

And my_page.html:

<!DOCTYPE html>
<html>
<head>
    <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'];
    }
    </script>
</head>
<body>
    <p id="location">Last location:</p>
</body>
</html>

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
 
DMTintner
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 :