Toastr with AJAX

18.8k views Asked by At

I am trying to get a toastr message to display from JSON retrieved via AJAX. This must be able to change the type of alert and its contents. I am not too clever with JSON, after reading up on it for a while i still have no idea where to start. Any pointers?

Ajax:

 function ping(data1)
    {
        $.ajax({
           type: "POST",
           url: "bridge/ping.php",
           data: "var1="+data1,
           success: 
        }
     });

Toastr:

          toastr.success("Message here","Title here)
3

There are 3 answers

2
tymeJV On

Basically on your PHP side, you'll send back an encoded JSON like:

$arr = array('message' => 'your message here', 'title' => 'your title here');
echo json_encode($arr);

Now, on your client, you write the success:

success: function(data) {
    toastr.success(data.message, data.title);
}
0
msalihbindak On

I use it like this. It works perfect.

Server

$message = array('message' => 'Success!', 'title' => 'Updated');
return response()->json($message);

Client

success:function(data){
  setTimeout(() => {
  toastr.success(data.message, data.title);
  },500)
},
0
Merlin On

Look at my question: In the JSON array, replace "t" with different toast type ['info'], ['warning'], ['success'], etc. Then, parse the JSON to fit John Papa's answer.

Using timeouts with toastr