Validate json and cancel reload

Validate json and cancel reload

MarcDMarcD Posts: 3Questions: 1Answers: 0

Hi,

My json source (that I don't control and can't change) will sometimes return data that I don't want to use. Instead, I'd prefer to stick to what was there before and wait for the next refresh cycle. I feel that using " "data": function (d) " would get me to the part where I can validate the data before it updates, but even if I can do that, I'm not sure how to deal with it if it fails validation.

Any ideas?

Thanks!

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,815Questions: 1Answers: 10,517 Site admin
    Answer ✓

    ajax.dataSrc is probably the one you want rather than ajax.data (which is before the request is made).

    What you would need to do is cache the last valid JSON response from the server and if a request contains data you don't want to use, just return the last valid one. It will still effectively reload the table, but it will be with the old data.

    Allan

  • MarcDMarcD Posts: 3Questions: 1Answers: 0

    This works great! I do my test to validate and only "return json.data;" if I'm satisfied. Returning nothing keeps the table as it was before the reload().

    Thank you!

  • allanallan Posts: 63,815Questions: 1Answers: 10,517 Site admin

    You might want to check the console when returning nothing - I think DataTables will probably throw an error if you do that.

    Allan

  • MarcDMarcD Posts: 3Questions: 1Answers: 0

    You're right, it does. I went with a global variable set to "" to start with. Looks something like this:

    "dataSrc": function ( json ) {
    if (json.data.length > 0) {
    oldjson = json;
    return json.data;
    } else if (oldjson != "") {
    return oldjson.data;
    } else {
    return json.data;
    }
    }

    Would you suggest an alternate method?

  • allanallan Posts: 63,815Questions: 1Answers: 10,517 Site admin

    That looks about as good as it gets to me - nice one :-)

    Allan

This discussion has been closed.