Send data between php and dart - php

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

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)

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.

this is not sending data between dart and php. this is sending data from dart to php!!!

Related

Dynamically get data from database using Ajax without a refresh interval

I have been working with jquery/ajax requests. I have successfully got a ajax request which will retrieve data from a database, the problem is, that i'm constantly serving window.setInterval() to refresh this function every x amount of seconds.
How would I change this to keep the ajax request alive, so it updates the html content without having to serve multiple requests to my ajax script.
My code follows:
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'Ajax.php'+SearchTerm, dataType: 'json', success: function(rows)
{
$('#NumberOfVotes').empty();
for (var i in rows)
{
var row = rows[i];
var QuestionID = row[0];
var Votes = row[1];
$('#NumberOfVotes')
.append(Votes);
}
}
});
});
}, 500);
A lot of this depends on how your server would be able to update it's content dynamically. That said, what you are looking for is websockets. Websockets are designed to replace the long-polling paradigm.
EDIT: Since you use mainly php for your server technology, look at Ratchet. I've heard good things about it http://socketo.me/
Here is an excellent article on using websockets with HTML
http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/
.NET has a great socket library in SignalR
http://signalr.net/
There is a myriad of php documentation on sockets out there
http://php.net/manual/en/book.sockets.php
look into using web sockets - you could send the client a message anytime they need to go an look for new data - that way your not making any unnecessary requests. Try checking out pubnub -service is cheap and could handle everything you need.
You could set xhr.multipart = true and modify server code. see Multipart Responses Example Code. Alternative way is to use websockets as mentioned
You need something server side that keeps the request alive until it has something to return. This is usually called "Comet", "Long-polling" or "Push".
The principle is :
You send a request client-side via AJAX
Your server receives the request, and doesn't return a response yet. It sleeps/waits until it has something to return
A new entry in your database ! Your server now has something to return : it returns some JSON data for the waiting request
Your receive the response server side, display what you have to display, and go back to step 1 sending another request.
Now, the implementation server side will depend on the language/framework you are using.
Edit :
Some examples using PHP :
Comet and PHP
Simple Comet Implementation Using PHP and jQuery

HTTP get request communication js to PHP doesn't return a result?

So I have a little js program running in a HTML5 canvas and I have a little http get request function in my js. The function itsself works(tested it with quite a few examples on the internet and it worked), but my own webserver doesnt return the right stuff when a request is sent to it.
my PHP looks like this:
<?php echo VVV::getUser()->userID ?>
When I open it in my browser it returns me the correct values the getUser()->userID returns. However when I send a Http request from my js it gets an empty result, however it works when used on various testing pages in the internet, so it must be my PHP or my server that cause this problem. any ideas?
This sounds like a cross-domain AJAX request problem. To solve this you really have just two options:
Have PHP make the cross-domain request. So whatever site that uses your AJAX will make a request to it's own server (like to its own ajax.php script) which then makes a request to your server and then returns it to the client.
Try to use something like easyXDM JavaScript library for cross-domain AJAX requests and see if that helps.
Here is a little sample for a simple cross-domain request (JSONP style):
1) On your server side, change the response to something like:
<?php echo( 'callbackFunc(' . VVV::getUser()->userID . ');' ) ?>
2) On the client side do something like:
function callbackFunc( userId )
{
// Do something with the userId
}
// Create a script tag which will load the call to the callback function
// with the user ID generated by the PHP code.
var s = document.createElement( "SCRIPT" );
s.src = "http://yourserver/yourpath/yourscript.php?maybesome=params";
document.body.appendChild( s );
The code loaded from your server will call callbackFunc() with the user ID.

Using JavaScript for RPC (Remote Procedure Calls)

Whats the best way to do a RPC (Remote Procedure Call) from a webpage or from JavaScript code? I want to keep it in JavaScript if possible so that I can do live updates to the webpage without having to do anything in PHP in case my server goes down I still want the JavaScript to handle page updates... possibly even sending a request to a python shell script running locally... Is this legal from JavaScript?
I prefer having remote machines handling the requests. I see a lot of talk about how XMLRPC or JSONRPC can do this however, I haven't seen any good examples. I guess Microsoft suggests using their XMLhttprequest however, I haven't seen anything that doesn't use their ActiveX call or require special code for Internet Explorer... I just want some simple way of passing a command to some python/ruby/c++ code from a webpage.
Python Server Code (Waiting for a RPC Request):
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
def my_awesome_remote_function(str):
return str + "awesome"
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.serve_forever()
EXAMPLE JavaScript Code:
var client = rpc.server("http://localhost:8000/");
var my_local_variable = client.my_awesome_remote_function(param);
Is there a good JSON/JavaScript example someone can point me to that sends a request to a server and gets some data back from that server?
Thanks!
Hardly it will work this way: client.my_awesome_remote_function. There's no magic in js like __call in php. Also remote calls are done in js mostly asynchronously using idea of callback - function which is called after finishing of some task.
var client = rpc.server("http://localhost:8000/");
var my_local_variable;
client.rpc('my_awesome_remote_function', [param], function(result) {
my_local_variable = result;
});
You can easily find tutorials about that calls. Just google "ajax tutorials".
E.g.: http://www.w3schools.com/ajax/ajax_intro.asp (event though w3schools isn't the best site and have errors in some details, it is still good for beginners).
All ajax implementations use both modern both XMLHttpRequest and ActiveX control for older IE.
It is possible to run those requests synchronously, but is considered very bad from the point of user experience. Also, you'll need to deal with concept of callbacks anyway.

PHP web response

I have a program that will make a web request to a php page (there will not be a browser involved here), and I need to send some data using php back to the program... how do I do this?
Just use echo to echo the thing you want sent back.
<?php
echo "thing that i want to send back";
?>
Have you considered a webservice? It might be overkill. Otherwise.. a POST or GET and echoing the response with PHP..?
What you're describing is basically a website.
You should echo what you want to return, like the others said.
for c# application, you should wait for response, and read the response stream to get the echos.
public GetResponeFromPHP()
{
HttpWebRequest request = null;
HttpWebResponse resp = null;
try
{
request = (HttpWebRequest)WebRequest.Create("http://www.URL_of_php.php");
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
// execute the http request and get the response
resp = request.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
//read the response stream
String responseText;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
responseText = sr.ReadToEnd();
}
// Now use respones text to get the echos //
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (resp != null)
resp.Close();
}
}
post and get really seem like the solution here. Although I am not very comfortable with the technique because it is prone to errors if parameters in the URL are incorrect or not validated. Maybe consider something other than the PHP? but hey the answer is that it would work like the others said above :)
Depending on the type of data you need returned from PHP, and assuming you have control of both the C# application and the PHP application, you will most likely use something such as the WebClient class, which allows you to make an HTTP call to a URL, which you would point to your PHP application. Once the request is made, you do whatever processing is necessary in your PHP application, and then most likely echo it back to the C# application (also, depends on the type of data you're using)
A simple HTTP response consist of headers and body.
The headers are not displayed in your web browser, but take place in the client(browser) server communication (web server) - simply said.
The web server will return to your program also so named headers, for which you will have to take care about.
Using your php script you can sent your output with echo:
<?php
echo 'Responding to the program...';
?>

How to activate PHP file in JavaScript function

I am trying to write some information into my database when I activate a javascript function.
I use PHP and MySQL. How can I open the .php file, execute it and return to .js file in order the function to continue its operation?
Thanks in advance.
I think you may be a bit confused. Javascript runs in the browser, on the client's computer. Php/MySQL runs on the server, responds to HTTP requests, and creates the content for the browser to display/run.
In order to get the two to communicate dynamically, you need to look at how to send/receive HTTP requests from javascript on the client to your php script on the server. You'll also need to be able to process responses in javascript. This practice is known as AJAX. The simplest way to do this is in my experience to use JSON and jQuery, http://api.jquery.com/jQuery.getJSON/
First of all, it is not possible to call PHP functions directly from JavaScript, or vice versa. This is because PHP is a server-side script, running on the server, and JavaScript is a client-side script, running on the browser.
But there is a solution, however, using a technique called "AJAX" (Asynchronous JavaScript and XML), which can be used to send a request to a server from JavaScript.
For instance, using a "user" page that the user sees, and a "request" page that is called from the JavaScript code, I could write the following code:
userpage.php:
<!-- JavaScript code -->
<script type="text/javascript">
function sendRequestToServer()
{
// The XMLHttpRequest object is used to make AJAX requests
var ajax = new XMLHttpRequest();
// The onreadystatechange function will be called when the request state changes
ajax.onreadystatechange = function()
{
// If ajax.readyState is 4, then the connection was successful
// If ajax.status (the HTTP return code) is 200, the request was successful
if(ajax.readyState == 4 && ajax.status == 200)
{
// Use ajax.responseText to get the raw response from the server
alert(ajax.responeText);
}
}
// Open the connection with the open() method
// (the third parameter is for "asynchronous" requests, meaning that
// JavaScript won't pause while the request is processing).
ajax.open('get', 'requestpage.php', true);
// Send the request using the send() method
ajax.send();
}
</script>
<!-- HTML code -->
<button onclick="sendRequestToServer();">Send request!</button>
requestpage.php (the output of this page will be returned to your JavaScript code):
<?php
echo "Hello World!";
?>
This example would, when the button is pressed, send a HTTP request to the server requesting requestpage.php, where the server would execute some server-side code and echo the result. The browser would then take the data it received from the server and use it in the script - in this case, alert() it.
Some resources:
AJAX wikipedia page
AJAX tutorials on Mozilla Developer Center and w3schools.com.
You might also want to check out JSON encoding, which is very common method of sending objects and arrays between clients and servers (especially when using AJAX):
JSON tutorial on MDC
json_encode() and json_decoder() PHP functions
(Sorry for such a long answer, hope it helped though)
You will need AJAX, there http://www.ajaxf1.com/tutorial/ajax-php.html a simple tutorial for AJAX using PHP server
look up AJAX... also think about using jQuery it has a simple and easy to use ajax() function.
If you're not already using an AJAX enabled framework (e.g. jQuery), you could just use a really lightweight XHR implementation to make a HTTP request. This request could have any PHP resource (performing the desired DB updates) as destination.
The smallest code I know of is found here: http://dengodekode.dk/artikler/ajax/xmlhttprequest_wrapper.php (Danish, sorry)
<script type="text/JavaScript">(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()</script>
And the request:
var oHttp = new XMLHttpRequest();
oHttp.open("post", "http://www.domain.dk/page.php", true);
oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
oHttp.send("id=123&noget=andet");

Categories