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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 27, 2013 at 9:02
\$\endgroup\$

1 Answer 1

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Aug 27, 2013 at 9:28
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.