0

I am having trouble making an PHP API to get data from MYSQL and parse JSON. I have a demo app (hiApp) and comes with some JSON files inside a folder.

The demo JSON file is like this:

{ "err_code": 0, "err_msg": "success", "data": [{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]}

This what my contacts.php is returning:

[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]

My contacts.php api looks like this: …

…
    $result = mysql_query("select * from sellers", $db);  

    $json_response = array();

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $row_array['nickname'] = $row['first_name'];
        $row_array['location'] = $row['territory'];

        array_push($json_response,$row_array);
    }

    echo json_encode($json_response);

?>

The js file to parse JSON, looks like this:

define(['utils/appFunc',
        'i18n!nls/lang',
        'components/networkStatus'],function(appFunc,i18n,networkStatus) {

    //var apiServerHost = window.location.href;

    var xhr = {

        search: function(code, array){
            for (var i=0;i< array.length; i++){
                if (array[i].code === code) {
                    return array[i];
                }
            }
            return false;
        },

        getRequestURL: function(options){
            //var host = apiServerHost || window.location.host;
            //var port = options.port || window.location.port;
            var query = options.query || {};
            var func = options.func || '';

            var apiServer = 'api/' + func + '.php' +
                (appFunc.isEmpty(query) ? '' : '?');

            var name;
            for (name in query) {
                apiServer += name + '=' + query[name] + '&';
            }

            return apiServer.replace(/&$/gi, '');
        },

        simpleCall: function(options,callback){
            options = options || {};
            options.data = options.data ? options.data : '';

            //If you access your server api ,please user `post` method.
            //options.method = options.method || 'GET';
            options.method = options.method || 'POST';

            if(appFunc.isPhonegap()){
                //Check network connection
                var network = networkStatus.checkConnection();
                if(network === 'NoNetwork'){

                    hiApp.alert(i18n.error.no_network,function(){
                        hiApp.hideIndicator();
                        hiApp.hidePreloader();
                    });

                    return false;
                }
            }

            $$.ajax({
                url: xhr.getRequestURL(options) ,
                method: options.method,
                data: options.data,
                success:function(data){
                    data = data ? JSON.parse(data) : '';

                    var codes = [
                        {code:10000, message:'Your session is invalid, please login again',path:'/'},
                        {code:10001, message:'Unknown error,please login again',path:'tpl/login.html'},
                        {code:20001, message:'User name or password does not match',path:'/'}
                    ];

                    var codeLevel = xhr.search(data.err_code,codes);

                    if(!codeLevel){

                        (typeof(callback) === 'function') ? callback(data) : '';

                    }else{

                        hiApp.alert(codeLevel.message,function(){
                            if(codeLevel.path !== '/')
                                mainView.loadPage(codeLevel.path);

                            hiApp.hideIndicator();
                            hiApp.hidePreloader();
                        });
                    }
                }
            });

        }

    };

    return xhr;
});

I know the error is in the way contacts.php is displaying the JSON results or I need to change something in the js file.

Thanks for the help.

user2964231
  • 39
  • 1
  • 6
  • Can you say more about where you are experiencing the problem? You said that PHP returns the correct JSON string, so I suspect you are not being able to read the JSON response in JS? – Andrea Tondo Oct 30 '14 at 10:06
  • Yes, that is right, I need to change something in the JS file, but I can't see what is it. The initial json is returning also this `{ "err_code": 0, "err_msg": "success", "data":` and I have to make the JS file work without this. – user2964231 Oct 30 '14 at 10:15
  • `data`, after the `JSON.parse(data)`, looks correct, containing an array of objects. I think you should be able to call directly `callback(data)` making sure to change its behavior as at that time data will not contain anymore the `err_code`, `err_msg`, `data` properties. You did not post your callback, so I cannot provide you a possible complete code solution. – Andrea Tondo Oct 30 '14 at 10:28
  • this is it `loadContacts: function() { if(VM.module('contactView').beforeLoadContacts()) { xhr.simpleCall({ query: { callback: '?' }, func: 'contacts' }, function (response) { if (response.err_code === 0) { VM.module('contactView').render({ contacts: response.data }); } }); } }` – user2964231 Oct 30 '14 at 15:55
  • I've posted a possible answer below. – Andrea Tondo Oct 31 '14 at 08:24
  • Please view my answer below. Thanks for the help. – user2964231 Oct 31 '14 at 11:55

2 Answers2

1

Based on your comments above I've tried to rewrite a solution keeping the same structure, but removing the unnecessary things; this is what the code may look like. Note that there are no references to err_code and err_msg peoperties, and the callback is called directly on data variable.

define(['utils/appFunc',
        'i18n!nls/lang',
        'components/networkStatus'],function(appFunc,i18n,networkStatus) {

    //var apiServerHost = window.location.href;

    var xhr = {

        getRequestURL: function(options){
            //var host = apiServerHost || window.location.host;
            //var port = options.port || window.location.port;
            var query = options.query || {};
            var func = options.func || '';

            var apiServer = 'api/' + func + '.php' +
                (appFunc.isEmpty(query) ? '' : '?');

            var name;
            for (name in query) {
                apiServer += name + '=' + query[name] + '&';
            }

            return apiServer.replace(/&$/gi, '');
        },

        simpleCall: function(options,callback){
            options = options || {};
            options.data = options.data ? options.data : '';

            //If you access your server api ,please user `post` method.
            //options.method = options.method || 'GET';
            options.method = options.method || 'POST';

            if(appFunc.isPhonegap()){
                //Check network connection
                var network = networkStatus.checkConnection();
                if(network === 'NoNetwork'){

                    hiApp.alert(i18n.error.no_network,function(){
                        hiApp.hideIndicator();
                        hiApp.hidePreloader();
                    });

                    return false;
                }
            }

            $$.ajax({
                url: xhr.getRequestURL(options) ,
                method: options.method,
                data: options.data,
                success:function(data){
                    data = data.length > 0 ? JSON.parse(data) : [];

                    if (typeof(callback) === 'function' && data !== undefined)
                        callback(data);
                }
            });

        }

    };

    return xhr;
});

Then you may call it this way, using directly response var, which now contains the parsed data array:

loadContacts: function() {
    if(VM.module('contactView').beforeLoadContacts()) {
        xhr.simpleCall({
                query: { callback: '?' },
                func: 'contacts'
        }, function (response) { 
            if (response !== undefined) { 
                VM.module('contactView').render({ 
                        contacts: response
                }); 
            } 
        }); 
    } 
}

Also, you would have to add

header('Content-Type: application/json');

before your PHP echo line in order to be able to parse it in JS.

Andrea Tondo
  • 479
  • 7
  • 16
0

Ok, many thanks Andrea, looks like there is something else that I'm missing because the results from the contacts.php and the initial contacts.php file is the same in my browser:

[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]

It works just fine if I use the initial contacts.php that only has pure json data like above, but if I switch to my api it stops working.

Also it stops working if I use this in the initial contacts.php:

<?php

$myString = '[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]';
echo $myString;

?>

I'll keep looking, but thanks to you I'm one step ahead.

user2964231
  • 39
  • 1
  • 6
  • Have you tried setting header('Content-Type: application/json'); in PHP before echoing? – Andrea Tondo Oct 31 '14 at 14:30
  • 1
    Thanks Andrea, it worked. You saved me :) I would like to vote your answer, but I don't have enough reputation... – user2964231 Nov 02 '14 at 12:12
  • I'm glad it helped you! I've integrated my full answer with this information, feel free to accept it, if it pleases you, instead of voting up. – Andrea Tondo Nov 02 '14 at 16:47