0

After hours of hit and trial this code has finally worked after looking at various posts for help. But i want someone to help me understand the function(i,dat) , what does this means ? Here is my full code below -

function get_assignedtasks_first_time(){
var jdata=$.getJSON( "http://45.114.246.107/quicktask/webservice/admtask.php?entdt=&entusr=SAURABH&company=&taskno=&status=&priority=&primary=", function( data ) {

db.transaction(function (tx) { 

    $.each(data, function(i, dat) {
                tx.executeSql('INSERT INTO tasks (sno, taskdesc) VALUES("'+data[i]['SNO']+'", "'+data[i]['TASKDESC']+'")');
            });
            alert("completed");

}); 
            }); 
}

1 Answer 1

1

The function $.each takes in two parameters. The first is the array being iterated over, and the second is a callback function to execute for each element in the array.

For each element in the array, $.each will execute this callback function with two arguments. The first argument (which you defined as i) is the index of the current element, and the second argument (dat) is the actual element you are looking at for each iteration.

For the function you defined, you are extracting the 'SNO' and 'TASKDESC' properties from each of the elements in the array. However, it looks like instead of using the dat parameter, which contains the current entry, you are using the original array (making your code a little bit more complicated to read).

Another way to implement the function might look like this:

function(index, element) {

    // put these variables in quotes
    var sno = "'" + element.SNO + "'";
    var taskdesc = "'" + element.TASKDESC + "'";

    // join these strings with commas
    var values = [sno, taskdesc].join(','); 

    tx.executeSql("INSERT INTO TASKS (sno, taskdesk) VALUES(" + values + ")")
    alert("inserted " + values);

}

In this case, we didn't need to use index at all since we are using the second parameter (the element being iterated over).

Sign up to request clarification or add additional context in comments.

2 Comments

This looks very neat, i'll try to do it this way too , can you give me a light on this line - var sno = "'" + element.SNO + "'"; // what does this mean , the single quote between the 2 quotes and a + before and after. Sorry i am a beginner
You need to wrap strings in either single or double quotes before inserting them into the database. The + sign just combines strings together. In javascript, if you want to add a quote to a string you need to wrap it in either double quotes (if you're adding a single quote), or wrap it in single quotes (if you're adding a double quote to the string).

Your Answer

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