qt progress bar is not working properly - php

I have one problem..
I am making post request to php script. And I am getting back result as an xml. How can I make my qprogressbar working.
I have tried this:
v
oid MainWindow::init()
{
url = "http://127.0.0.1:8888/direkt_php_qt.php";
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(updateDataTransferProgress(qint64,qint64)));
connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
}
void MainWindow::updateDataTransferProgress(qint64 bytesReceived, qint64 bytesTotal)
{
ui->progressBar->setMaximum(bytesTotal + (bytesTotal * 0.25));
ui->progressBar->setValue(bytesReceived);
ui->progressBar->show();
}
But it's not working. I am getting error:
Object::connect: No such signal QNetworkAccessManager::downloadProgress(qint64,qint64)
How can I make this work with manager variable or something like that.
EDIT 2:
This is for example function that is calling init()
void MainWindow::Citanje_korisnika()
{
init();
QUrl params;
params.addQueryItem("action","Citanje_korisnika");
QByteArray data;
data.append(params.toString());
data.remove(0,1);
QNetworkRequest request;
request.setUrl(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,
QVariant("application/x-www-form-urlencoded"));
reply = manager->post(request, data);
}
I tried your code but I always get unexpectedly out from program. Can you change me my function from which I am calling post method so it can work with init()

donwloadProgress is a signal of QNetworkReply.
Try something like this:
url = "http://127.0.0.1:8888/direkt_php_qt.php";
manager = new QNetworkAccessManager(this);
QNetworkReply* reply = manager->get(QNetworkRequest(url));
connect(reply, SIGNAL(downloadProgress(qint64, qint64)),this, SLOT(updateDataTransferProgress(qint64,qint64)));

Related

gwt: send php post request

I am trying to communicate to a php server from my gwt project.
I already got a GET request to work, however, my POST request doesn't work so far.
Here's my code:
Button synchronize = new Button("synchronize ",
new ClickHandler() {
public void onClick(ClickEvent event) {
String myurl = URL
.encode("php/test.php");
RequestBuilder builder = new RequestBuilder(
RequestBuilder.POST, myurl);
JSONObject jsonValue = new JSONObject();
jsonValue.put("name", new JSONString("Abc"));
builder.setHeader("Content-Type", "application/json");
try {
Request request = builder.sendRequest(jsonValue.toString(),
new RequestCallback() {
public void onError(Request request,
Throwable exception) {
processResponse("ERROR");
}
public void onResponseReceived(
Request request,
Response response) {
if (200 == response.getStatusCode()) {
processResponse(response
.getText());
} else {
processResponse("ERROR");
}
}
});
} catch (RequestException e) {
processResponse("ERROR");
}
}
});
public void processResponse(String responseString) {
Window.alert(responseString);
}
I can see that the post request goes out and the request payload is a json-object. However, when I try to access the data in the php script, I get the error that the index name is undefined.
Here's the PHP:
<?php
echo $_POST["name"];
?>
Is there something wrong with my PHP?
Does anyone have a working example for this?
While I haven't checked the PHP documentation so far, I tend to remember, that $POST contains the post request's variables, especially useful in a x-www-form-urlencoded request. .. Checked it, yes. I am right :-)
What you actually want is to read the body of the post request and parse it's JSON content to a PHP array or hash.
To read the body see here: How to get body of a POST in php?
$entityBody = file_get_contents('php://input');
Parsing json is described here: Parsing JSON file with PHP
I will not quote the code from there, as it maybe does not exactly fit your needs, but you look for json_decode($json, TRUE).

Create a simple json response which can be accessed from webview of an android application

I have a url site.com/test.php which has the following code
<?php
$num1 = $_REQUEST['num1'] ;
$num2 = $_REQUEST['num2'] ;
$tot = $num1 + $num2 ;
?>
From an android application using POST/GET num1 and num2 parameters are passed to www.site.com/test.php
How can I make the response in such a way that the android application will be able to get the response from this request.
I tried this
header('Content-Type: application/json');
echo json_encode($response);
but all it does is echo it in the web view and im not able to get the response.Is there someway I can get the response as standard json response,which is not displayed but get it as soon as I hit the url as a response ?
** UPDATE **
#Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if(flag) {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// read inputstream to get the json..
...
...
return true;
}
return false
}
#override
public void onPageFinished (WebView view, String url) {
if (url contains "form.html") {
flag = true;
}
}
this is the java code I got from SO , which Im planning to use in the android appication
Seems to be a problem in the handling of the response, not the generation of the JSON. Are you clicking a link to the JSON on a page that is has "form.html" in it? Because that is what seems to be assumed in the code you posted.
It seems to be better to just overload the shouldOverrideUrlLoading and check if the url matches your json page. Something like this:
#Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if(url.toLowerCase().contains("www.site.com/test.php")) {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// read inputstream to get the json..
...
...
return true;
}
return false;
}
It might be a good idea to start an activity and load the JSON in that activity using, for example, an AsyncTask (network operations aren't allowed on the UI thread in the latest android APIs), instead of doing URL.openConnection immediately.

UrlRequest not working inside a SimpleButton

I have a UrlRequest in my Main Class, that does a request to a server in cakePHP, and its working fine, but when I do the exact same request in a click of a button its not working.
Can someone help me?
This is my code to do the request:
var token:String = LoaderInfo(root.loaderInfo).parameters.requestToken;
var myData:URLRequest = new URLRequest("users/personalInfo/"+token);
myData.method = URLRequestMethod.GET;
loader = new URLLoader(myData);
loader.addEventListener(Event.COMPLETE, onLoaded);
loader.dataFormat=URLLoaderDataFormat.TEXT;
loader.load(myData);
function onLoaded(e:Event):void {
MovieClip(this.root).gotoAndStop("main");
}
Click Handler
public function SaveProfileButton() {
addEventListener(MouseEvent.CLICK, mouseClick);
}
private function mouseClick(e:MouseEvent):void{
MovieClip(this.root).output.text = "loading...";
send();
}
send() is the code to do the request.
Thanks
I think you may need a cross domain policy xml on your server where the php is. 99% sure. http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html

GWT: Handle JSON data after submitting http request

I’m working on a GWT web application that needs to communicate with a common web server. Unfortunately, the server only supports PHP, so I can’t use GWT RPC. That’s why I want to use a simple PHP script on server side, which returns all the necessary data in JSON format. Because I’m fairly new to GWT, my code is based on this example:
http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON
The PHP script seems to work fine. Firebug shows me the returned JSON data and the port 200:
Response:
[{"key1":"k1","value1":"v1"},{"key2":"k2","value2":"v2"},{"key2":"k3","value3":"v3]
However, the response is never processed further. Here is my code:
private static final String JSON_URL = "http://www.myUrl/myScript.php";
public HashMap<String, Integer> loadCalendarTable(String p1, String p2) {
table = new HashMap<String, Integer>();
String url = JSON_URL+"?p1="+p1+"&p2="+p2;
url = URL.encode(url);
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert("Couldn't retrieve JSON");
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
try {
// parse the response text into JSON
JSONValue jsonValue = JSONParser.parse(response.getText());
JSONArray jsonArray = jsonValue.isArray();
if (jsonArray != null) {
HashMap<String, Integer> hm = updateTable(jsonArray);
}
else
throw new JSONException();
}
catch (JSONException e) {
Window.alert("Could not parse JSON");
}
}
else
Window.alert("Couldn't retrieve JSON (" + response.getStatusText() + ")");
}
});
//(*)
}
catch (RequestException e) {
Window.alert("Couldn't retrieve JSON");
}
return table;
}
private HashMap<String, Integer> updateTable(JSONArray array) {
//do something
return table;}
By executing the application on the web server, there occurs no exception and no alert pops up. By using some alerts (which I omitted in the code above for readability), I noticed that the try-statement in new RequestBuilder() is executed. Another alert at (*) shows, that the try-statement is passed. (No exception occurs, as mentioned before). Obviously, the method onResponseReceived() is never executed. I never called this method, so this could be the reason for my problem. But then, I don’t understand where I should call onResponseReceived().
Remark:
I omitted my PHP script, because that’s actually the same as showed in the online example (http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON). Besides, the script seems to work properly.
How do you know that onResponseRecieved is not being executed? This should be called when your script.php returns JSON data. Assuming your server sends back a 200 status code, the response might be parsed, but no nothing is done with the data
try {
// parse the response text into JSON
JSONValue jsonValue = JSONParser.parse(response.getText());
JSONArray jsonArray = jsonValue.isArray();
if (jsonArray != null) {
HashMap<String, Integer> hm = updateTable(jsonArray);
// Now what? hm isn't actually used for anything...
} else {
throw new JSONException();
}
From the value returned at the end of the method, table is apparently important, but it will be returned, empty before the onResponseRecieved callback is ever invoked. This is because all GWT Ajax calls are asynchronous - the script won't stop running while waiting for the server to resume. Create an alert with response.getTest() in the if (jsonArray != null) block, and you may find that this code is getting called after all. If so, you've fallen victim to That's not async - it is considered generally good JavaScript practice (and all but mandatory in GWT) to wait for results to arrive when ready, and to keep executing as normal in the meantime.

AS2: load class variables with sendandload

I'm using Actionscript 2.0 in combination with PHP, now I can make a call to my PHP file and receive data but apparently I have to use that data immediately, I cannot use it to fill my class variables.
This is what I want :
class user {
var lastname:String;
function user(in_ID:Number){
var ontvang:LoadVars = new LoadVars();
var zend:LoadVars = new LoadVars();
zend.ID = in_ID;
zend.sendAndLoad("http://localhost/Services/getUser.php", ontvang, "POST");
ontvang.onLoad = function(success:Boolean) {
if (success) {
lastname = ontvang.lastname;
} else {
lastname = 'error';
}
};
}
}
I've found out that this is a big issue in AS2, I found this post to work around it if you're loading XML data but I can't seem to get it to work with LoadVars :
http://www.actionscript.org/forums/showthread.php3?t=144046
Any help would be appreciated ..
When your onLoad handler is called, it is being called as if it were a member function of the LoadVars instance, and not your user instance.
There are several ways around this, one is to use Delegate.create() to create a function which will work as intended, for example:
import mx.utils.Delegate;
class user {
var lastname:String;
var ontvang:LoadVars;
function user(in_ID:Number){
ontvang = new LoadVars();
var zend:LoadVars = new LoadVars();
zend.ID = in_ID;
ontvang.onLoad = Delegate.create(this, onLoad);
zend.sendAndLoad("http://localhost/Services/getUser.php", ontvang, "POST");
};
}
function onLoad(success:Boolean) : Void
{
if (success) {
lastname = ontvang.lastname;
} else {
lastname = 'error';
}
}
}
Don't forget that the load is asynchronous - when you create one of your user objects, the member variables won't be immediately available. What you may need to do is let your user object be capable of signaling its readiness much like LoadVars does, (e.g. with a callback function provided by the caller) so that your app is driven by by these asynchronous events.

Categories