jQuery addClass example

Change class name on click in jQuery

by dipique

HTML

<table id="tblResults" border="1">
  <tr>
    <th>Result</th>
    <th>JSON</th>
    <th>Matches #1</th>
    <th>.Error result</th>
    <th>.Done .Error result</th>
  </tr>      
</table>

JavaScript

const exampleCall = { url: 'https://code.jquery.com/jquery-1.12.4.min.js'} //example target for ajax call
const depUri = { url: 'https://code.jquery.com/jquery-1.12.4.min.js'} //example2 target for ajax call

function callDependency() { //example dependency
  return $.ajax(depUri) //the results of this call are never used and don't matter (for the purposes of this example)
}

function scenario1(ajaxCfg) {
  return $.ajax(ajaxCfg)
}

function scenario2(ajaxCfg) {
	return callDependency().then(() => $.ajax(ajaxCfg))
}

async function scenario3(ajaxCfg) {
    let jqXhrResult;
    try {
        await callDependency();
        jqXhrResult = await $.ajax(ajaxCfg).promise();
    } catch(err) {
        // Error handling goes here
        console.log('err')
    }

    return jqXhrResult;
}

Function.prototype.scenario4Getter = function(ajaxCfg, ...args) {
    return this(...args).then(() => $.ajax(ajaxCfg))
}

function scenario4(ajaxCfg)
{
	return callDependency.scenario4Getter(ajaxCfg)
}


$(function() {
  let results = [
    scenario1(exampleCall),
    scenario2(exampleCall),
    scenario3(exampleCall),
    scenario4(exampleCall)
  ]


  let idx = 1
  const firstResultJson = JSON.stringify(results[0])
  const table = document.getElementById('tblResults')
  for (let result of results) {
    const resultJson = JSON.stringify(result)
    const cells = [
      (idx++).toString(),
      resultJson,
      (resultJson == firstResultJson).toString()
    ]

    try {
      result.error(e => {})
      cells.push('Success')
    } catch (err) {
      cells.push(`Failed: ${err}`)
    }

    try {
      result.done(() => {}).error(e => {})
      cells.push('Success')
    } catch (err) {
      cells.push(`Failed: ${err}`)
    }

    //add the cells as a row to the table
    var row = table.insertRow(-1)
    for (const cell of cells)
      row.insertCell(-1).innerHTML = cell
  }
})