Cannot Call data from Web service using JSON....

You must Login before you can answer or comment on any questions.

Hi all...

I am trying to get the data from the webservice db(PHPMyAdmin) and in app not able to retrieve data...

Please help...

Here is my PHP Code:

<?php //cust-mysql-123-04 $link = mysql_connect('localhost', 'root', ''); if (!$link) { die('Not connected : ' . mysql_error()); }

// make foo the current db $db_selected = mysql_select_db('mobileapp', $link); if (!$db_selected) { die ('Can\'t use : ' . mysql_error()); }

// Set the default namespace to utf8 //$mysql->query("SET NAMES 'utf8'"); $json = array(); if($result = mysql_query("select * from mobile_user")) { echo mysql_num_rows($result); while ($row=mysql_fetch_array($result)) { // $json.= "<li>".$row['password']."</li>"; $json[]=array( 'password'=>$row['password'], ); } } //result_close(); echo $json; print_r($json);

header("Content-Type: text/json"); echo json_encode(array( 'password' => $json ));

mysql_close(); ?>


When I run this PHP code the result in the web page is

6ArrayArray ( [0] => Array ( [password] => test123 ) [1] => Array ( [password] => test123 ) [2] => Array ( [password] => Rr ) [3] => Array ( [password] => ) [4] => Array ( [password] => Rrtt ) [5] => Array ( [password] => newp ) ) Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/mobileapp/read.php:20) in /Applications/XAMPP/xamppfiles/htdocs/mobileapp/read.php on line 32 {"password":[{"password":"test123"},{"password":"test123"},{"password":"Rr"},{"password":""},{"password":"Rrtt"},{"password":"newp"}]}


My Titanium Code is

var currentWin = Ti.UI.currentWindow;

var sendit = Ti.Network.createHTTPClient(); sendit.open('GET', 'http://localhost/mobileapp/read.php'); sendit.send(); sendit.onload = function(){ var json = JSON.parse(this.responseText);

var json = json.mobile_user;

var dataArray = [];

var pos;
for( pos=0; pos &lt; json.length; pos++){

    dataArray.push({title:'' + json[pos].password + ''});
    // set the array to the tableView
    tableview.setData(dataArray);
};

};

var tableview = Ti.UI.createTableView({ });

currentWin.add(tableview);


Please help wats wrong with this...

In the App, it just gives the blank page.........

4 Answers

Tip: Add you code in the question box using the code markdown syntax - much easier to read.

In your Titanium code you have a loop that sets the tableview data on every iteration, this should only be done once you have the array ready.

You have also called your API BEFORE you create the handler to accept and process the data.

Change your code to this;

var currentWin = Ti.UI.currentWindow;
 
// add the table to the window straight away
var tableview = Ti.UI.createTableView({ });
currentWin.add(tableview);
 
// set up the API function and handler BEFORE triggerring it
var sendit = Ti.Network.createHTTPClient();
sendit.onload = function() {
    var json = JSON.parse(this.responseText);
    var users = json.mobile_user, data = [], intUser = 0, intUsers = users.length;
    for (intUser = 0; intUser < intUsers; intUser = intUser + 1){
        data.push({
            title: '' + users[intUser].password + ''
        });
    };
    tableview.setData(data);
};
 
// trigger the API, this will then call the handler that you already setup
sendit.open('GET', 'http://localhost/mobileapp/read.php');
sendit.send();

As this is your second question and is nearly the same the last one about XML and still has a lot of conceptual mistales... I highly recommend you learning the Basics of web Services, plain Ajax (XMLHttpRequest), JSON and finally Ti.Network.HTTPClient and probably Databases too.

— answered 10 months ago by Alexander Bauer
answer permalink
2 Comments
  • That's not an answer. The guy is trying to learn.

    — commented 10 months ago by Edward Marshall

  • No he doesnt, if he would like to learn he would check out the 5000 resources on the web.

    — commented 10 months ago by Alexander Bauer

Malcolm points out that you're calling setData() inside of the loop -- he's right in that you need to move that outside the loop.

But your server-side code is way off the mark.

First off, you can't call print_r() when you're outputting json. The JSON parser won't be able to understand the output.

Second, look at your object (below). You don't have a mobile_user property of the object. It's an object with a single property, password. The value of that property is an array of simple objects with one property each, pasword, with a value of a string.

And WHY IN THE WORLD are you sending passwords from server to client?!?!? That is an insanely bad practice from a security standpoint. Even if you encode/encrypt those, that's a really bad idea. I can't imagine a valid use case for something like that.

{
   "password":[
      {
         "password":"test123"
      },
      {
         "password":"test123"
      },
      {
         "password":"Rr"
      },
      {
         "password":""
      },
      {
         "password":"Rrtt"
      },
      {
         "password":"newp"
      }
   ]
}

— answered 10 months ago by Jason Priebe
answer permalink
3 Comments
  • Just for testing, i have added the field name as Password...

    Can u please give me the code in Php editing mine....

    — commented 10 months ago by Suresh Kumar S

  • Can u correct my PHP file which ll be really greatful....

    — commented 10 months ago by Suresh Kumar S

  • REALLY? You need help making a 3-line change in your PHP? But you're trying to build a database-driven client-server application?!?!?

    I'm always surprised when I see people asking for help like this on a developer's q&a forum. A question like that demonstrates a huge disconnect in skills/experience and the complexity of the task you're trying to take on.

    Is Titanium being represented somewhere as a tool for building mobile apps without coding?

    I'm not going to rewrite your code for you. I'll give you a few pointers:

    1. DO NOT SEND PASSWORDS FROM SERVER TO CLIENT - rewrite your application entirely if you were planning on using that technique. It's a terrible idea.

    2. DON'T PRINT OUT DEBUG LINES IN A JSON WEB SERVICE AND EXPECT THE CLIENT TO WORK - remove the echo() call and the print_r() call. Those may be helpful for you to manually examine the data, but your client can't parse it.

    3. As I mentioned, your JSON-encoded object had no property mobile_user; it had a property password. Change that in the line where you're outputting the JSON:

      header("Content-Type: text/json");
      echo json_encode(array( 'mobile_user'  =>   $json ));

    I hope this helps, and in the future, try to be more resourceful before coming to the Q&A for help. There are so many tools you can use to investigate your problems. If you'd used the debugger, you could have put a breakpoint right after you decoded the JSON object, and you could have examined the object. You would have quickly found out that it had no mobile_user property, which would help you zero in on the problem.

    If you can't learn how to diagnose problems using the tools at your disposal, I'm afraid you have little chance of success in building an app with Titanium.

    — commented 10 months ago by Jason Priebe

Jason and Alexander are right, you have to work out the basics first before moving on. Whilst Titanium is easy to use, that does not mean it is suitable for those who have not spent the time learning the fundamentals of what they hope to use in their app. You may well be biting of more than you can handle given you have issues with each stage.

Many people are happy to help you out, but the emphasis is on help, we are not going to write your app for you. Do we we have all been doing for years; do a bit, test it, do some, test some more, add more, test more.

Consider solving ONE problem first, then moving on to the next, for example your PHP is very flawed, this is not the place to have advice for that. Go and look for tools like http://jsonlint.com/ and http://jslint.com/, but DO NOT expect these to solve your problems, these are tools to use to look for issues.

Final point ALWAYS add code using the three ~ syntax in markdown - help available on the top of the question box. Code shown without this does not have line breaks or formatting, your PHP code ends up looking as if it is almost all comments when pasted into a text editor.

Your Answer

This question has been locked and cannot accept new answers.