0

I have script in A.js like this:

function sinkronMyDB(){
    sinkronDB();
    var u_name = window.localStorage.getItem('uname');
    if(dataSync.length !== 0){ // <-- line 4
        var dataSinkronItems = [];
        for (var i = 0; i<dataSync.length; i++) {
            dataSinkronItems[i] = dataSync[i];
            console.log('dataSync('+i+') = '+dataSync[i]);
        };
        $.ajax({
            url:'http://qrkonfirmasi.16mb.com/delivery/update.php',
            data: {data : dataSinkronItems, username: u_name}, 
            type:'post',
            async:'false',
            dataType: 'json',
            beforeSend:function(){
                $.mobile.loading('show',{theme:"a",text:"Update...",textonly:true,textVisible:true});
            },
            complete:function(){
                $.mobile.loading('hide');
            },
            success:function(result){
                if (result.status===true) {
                    dataBaru = [];
                    idBaru = [];
                    for (i=0; i<dataBaru.length; i++){
                        dataBaru[i] = result.dataBaru[i];
                        idBaru[i] = result.id[i];
                    }
                    sinkronUpd();
                    console.log('Database update success.');
                } else{
                    console.log('Tidak ada pengiriman baru.');
                }
            },
            error:function(request,error){
                alert('Koneksi error. Silahkan coba beberapa saat lagi!');
            }
        });
    }else alert('Belum ada barang yang terkirim');
}

function sinkronDB() is in another Script file. lets call it B.js. the script content is like this:

function sinkronDB(){
    db.transaction(sinkronQuery,errorCB);
}

function sinkronQuery(tx){
    tx.executeSql("SELECT * FROM data_pengiriman WHERE Status = 'Terkirim'",[],successSelect);
}

function successSelect(tx,result){
    var len = result.rows.length;
    dataSync = [];
    for (var i=0; i<len; i++){
        dataSync[i] = result.rows.item(i).id_pengiriman;
        console.log('dataSync['+i+'] = '+dataSync[i]);
    }
}

In console log it's say error:

Uncaught ReferenceError: dataSync is not defined at file A.js line 4.

I tried check it with jshint and no error. Can anyone help me solve it, please!

3 Answers 3

1

The problem is sinkronDB is asynchronous, so the if statement is evaluated before sinkronDB is completed

So you need to use a callback to handle the response like

function sinkronDB(callback) {
    db.transaction(function (tx) {
        sinkronQuery(tx, callback)
    }, errorCB);
}

function sinkronQuery(tx, callback) {
    tx.executeSql("SELECT * FROM data_pengiriman WHERE Status = 'Terkirim'", [], function (tx, result) {
        successSelect(tx, result, callback);
    });
}

function successSelect(tx, result, callback) {
    var len = result.rows.length;
    var dataSync = [];
    for (var i = 0; i < len; i++) {
        dataSync[i] = result.rows.item(i).id_pengiriman;
        console.log('dataSync[' + i + '] = ' + dataSync[i]);
    }
    callback(dataSync)
}

then

function sinkronMyDB() {
    sinkronDB(function (dataSync) {
        var u_name = window.localStorage.getItem('uname');
        if (dataSync.length !== 0) { // <-- line 4
            var dataSinkronItems = [];
            for (var i = 0; i < dataSync.length; i++) {
                dataSinkronItems[i] = dataSync[i];
                console.log('dataSync(' + i + ') = ' + dataSync[i]);
            };
            $.ajax({
                url: 'http://qrkonfirmasi.16mb.com/delivery/update.php',
                data: {
                    data: dataSinkronItems,
                    username: u_name
                },
                type: 'post',
                async: 'false',
                dataType: 'json',
                beforeSend: function () {
                    $.mobile.loading('show', {
                        theme: "a",
                        text: "Update...",
                        textonly: true,
                        textVisible: true
                    });
                },
                complete: function () {
                    $.mobile.loading('hide');
                },
                success: function (result) {
                    if (result.status === true) {
                        dataBaru = [];
                        idBaru = [];
                        for (i = 0; i < dataBaru.length; i++) {
                            dataBaru[i] = result.dataBaru[i];
                            idBaru[i] = result.id[i];
                        }
                        sinkronUpd();
                        console.log('Database update success.');
                    } else {
                        console.log('Tidak ada pengiriman baru.');
                    }
                },
                error: function (request, error) {
                    alert('Koneksi error. Silahkan coba beberapa saat lagi!');
                }
            });
        } else alert('Belum ada barang yang terkirim');
    });
}
Sign up to request clarification or add additional context in comments.

6 Comments

thanks it's fixed. but cant u check my code again in B.js. it's always result alert('Koneksi error. Silahkan coba beberapa saat lagi!'). it means cant connect to server caused by connection error. but i try login function it works well. and in console no error sign.
By the way this is sinkronUpd(): function sinkronUpd(){ db.transaction(updQuery,errorCB); } function updQuery(tx){ var len = dataBaru.length; for (var i = 0; i < len; i++) { tx.executeSql("INSERT OR IGNORE INTO data_pengiriman VALUES ('"+idBaru[i]+"', '"+dataBaru[i]+"', 'Belum Terkirim')"); console.log('Inserted new kode '+dataBaru[i]+ ' id: ' +idBaru[i]+'.'); } }
@MahfudMuhammad add alert(error) in the error handler to see the error
it says parsererror. but i use the same way of json parsing in login and it worked well.
@MahfudMuhammad what is the value returned... can you check the browser's network tab to check the returned value... since you have set dataType: 'json' you need to return a proper json response.. which seems to be not happening
|
0

As the error message says, you have not defined dataSync. Define it, var dataSync = []; and push whatever you need to it.

1 Comment

i suppose to make a global array. so where should i define it?
0

You have defined dataSync inside successSelect(tx,result) method, and it is not a global variable. sinkronMyDB() method has no access to it.

If you want to make it a global array, put var dataSync = [] outside the functions, and make sure successSelect(tx,result) method is executed before sinkronMyDB() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.