So i am trying to communicate between dart clientside and a php server side using AJAX. Since direct execution is not possible. I compiled the dart to javascript and then run it on a apache server.
json data is generated at client end, But there is no response from the the server
dart code
import 'dart:html';
import 'dart:json';
void main() {
query("#clicker").on.click.add(callServer);
}
void callServer(Event event) {
var data ={ 'name':"sendname"}
,jsondata=stringify(data);
print(jsondata);
var req = new HttpRequest();
req.open('post','http://localhost:8080/darttest/server.php',true);
//req.setRequestHeader('Content-type','application/json');
req.send(jsondata);
print(req.responseText);
}
php side i just echo the content received
<?php
$name = $_POST['name'];
echo $name;
?>
This is my first try at dart programming, so do let me know if this approach is even possible
To read the response, you have to put your code in a callback on readyStateChange
:
var req = new HttpRequest();
req.open('post','http://localhost:8080/darttest/server.php',true);
req.on.readyStateChange.add((e){
if (req.readyState == HttpRequest.DONE && req.status == 200){
print(req.responseText);
}
});
req.send(jsondata);
With your code the http request was not processed when you tried to read the response. You have to wait the completion of the request to read the response.
Is localhost:8080 serving both the static Dart (as JS), and the php? If not, you're likely coming across the access-control-allow-origin
issue (which is a browser security issue).
This prevents one site posting date to another site.
Work-arounds:
- Ensure that the site serving php returns the correct CORS headers: http://enable-cors.org/server.html
- Serve the static Dart/JS files from the same URL (localhost:8080)
For more information, read these:
- https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
- CORS with Dart, how do I get it to work?
- Creating a bot/crawler
Update Workaround 3 is described here (for Chrome / Dartium):
https://groups.google.com/a/dartlang.org/d/msg/misc/kg13xtD7aXA/uxeXXrw3CG8J
You can add the parameter "--disable-web-security" to chrome.exe to disable cross domain check.
(Of course, this is only useful while you are developing)
this is not sending data between dart and php. this is sending data from dart to php!!!