user3369592 user3369592 - 4 months ago 21
jQuery Question

better design for Ajax replace div with another div

I am new to Ajax. I have a template which has "name" and a button. Wheni the button is clicked, the name and button will be replaced with some messages.
My code works perfectly.
Ajax:

$('#fulfillButton').bind('click',function() {
$.ajax({
type : "GET",
contentType : "application/json; charset=utf-8",
url : "/order/${orderID}",
dataType : "json",
cache: false,
timeout: 12000,

success: function (data) {
alert("success");
},

error: function (data,textStatus) {
if(textStatus == "timeout")
{
$('#main-panel').replaceWith('<div class="error-message">' + "Timeout, please clcik the button beblow to scan again!" + '</div>');
}
else
{
var responseText = data.responseText;
var jsonErrorMessage = JSON.parse(responseText);
$('#main-panel').replaceWith('<div class="error-message">' + jsonErrorMessage["body"] + '</div>');
}
},
});


Html :

<div id="main-panel">
<div class="full-name">
${name}
</div>
<div id
<button id="fulfillButton" type="button" class="action-button shadow animate fulfill-button-color">
FulFill
</button>
</div>
<button id="goBackButton" type="button" class="go-back-button">
Go Back
</button>


But now I am looking for a better design. As you can see

$('#main-panel').replaceWith('<div class="error-message">' + jsonErrorMessage["body"] + '</div>');


But I want to avoid interspersing view elements with the logic (to not put div tage here). I want to put DIV in the HTML or can I use the existing DIV with the "error_message" style applied in the JS? If so, how could I actually write code?

Answer

Why don't you add the error-message divs in your html (inside main-panel, give them some ids, lets say error1, error2) as hidden <div class="error-message" id="someID' hidden>...</div> and then when you get an error instead of replace just call

error: function (data,textStatus) {
    $('#main-panel').find('*').not('.error-message').remove();//Remove everything except from the error-message divs
    if(textStatus == "timeout")
    {
        $('#error1').html('Timeout, please clcik the button beblow to scan again!');
        $('#error1').show();
    }
    else
    {
        var responseText = data.responseText;
        var jsonErrorMessage = JSON.parse(responseText);
        $('#error2').html(jsonErrorMessage["body"]);
        $('#error2').show();
    }
},
Comments