0
\$\begingroup\$

I want to insert and edit values on the same button click. The code is working fine and I am using the same code for both insertion and deletion.

function saveToDB(){
var value= pageValidation();
if($('#jobid').val()==" "){
    if(value!=false){
    var data = {        
        "names": $('#names').val(),
        "os": $('#OS').val(),
        "browser": $('#browsers').val(),
        "version": $('#version').val(),
        "scripttype": $('#testscripts').val(),
        "server": $('#server').val()
    };
    $.ajax({
        type: 'post',
        url: "/insertJobs",
        dataType: "json",
        data: data,
        success: function (response) {
            console.log("job insertion success");
            console.log(response);
            displayjobs();
        }
    });
  }
}
else{

    if(value!=false){
    var data = {
        "jobid": $('#jobid').val(),
        "names": $('#names').val(),
        "os": $('#OS').val(),
        "browser": $('#browsers').val(),
        "version": $('#version').val(),
        "scripttype": $('#testscripts').val(),
        "server": $('#server').val()
    };
    $.ajax({
        type: 'post',
        url: "/editJobs",
        dataType: "json",
        data: data,
        success: function (response) {
            console.log("job Updated succesfully!!");
            console.log(response);
            displayjobs();
        }
    });
  }
}
}

Are there any possible ways to remove duplication and compress this code?

\$\endgroup\$
2
\$\begingroup\$

The only difference between the two code blocks is the service endpoint and the inclusion of the ID, so you could shorten it to:

function saveToDB(){
    var jobId = $('#jobid').val();      
    var valid = pageValidation();
    var url = jobId === " " ? "/insertJobs" : "/editJobs" ;

    if(valid){
        var data = {
            "jobid": jobId.trim(),        
            "names": $('#names').val(),
            "os": $('#OS').val(),
            "browser": $('#browsers').val(),
            "version": $('#version').val(),
            "scripttype": $('#testscripts').val(),
            "server": $('#server').val()
        };
        $.ajax({
            type: 'post',
            url: url,
            dataType: "json",
            data: data,
            success: function (response) {
                console.log("Change this message");
                console.log(response);
                displayjobs();
            }
        });
    }
}

That code assumes that the code running at /insertJobs will ignore the empty jobid value. If it won't, update the code so as not to send it.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.