Search code examples
javascriptphpjquerytoastr

How to Show a toastr message with dynamic variables


I'm using Toastr to show a popup of message in UI.

I'm sending a request to server via Ajax and in response, i'm sending a below response

echo json_encode(
                    array(
                            "type" => "error",
                            "message" => $error,
                            "status" => "Error While Updating!"
                         )
                );

I'm using the resp.type to show dynamic toastr so below is my toastr code

.done(function(resp)
    {
        toastr.resp.type(resp.message, resp.status,{progressBar:!0,showMethod:"slideDown",hideMethod:"slideUp",timeOut:2e3,preventDuplicates: true,positionClass: "toast-bottom-right"});
    });

The problem with above code is that when the code is running it throws an error message of Uncaught TypeError: toastr.type is not a function

Could anyone help me out what's going wrong or what might be a correct solution here


Solution

  • You cannot embed toastr.resp.type, it is invalid and hence will throw an error.

    Below code would work as you want, as far as i understand the question

    .done(function(resp)
       {
           toastr[resp.type](resp.message, resp.status,{progressBar:!0,showMethod:"slideDown",hideMethod:"slideUp",timeOut:2e3,preventDuplicates: true,positionClass: "toast-bottom-right"});
       });
    

    Please view this as a reference: https://github.com/CodeSeven/toastr/issues/203

    function showToast(message, timeout, type) {
          type = (typeof type === 'undefined') ? 'info' : type;
          toastr.options.timeOut = timeout;
          toastr[type](message);
      }
    
    showToast('Hello Toastr!", 15000, 'warning');