Steve Steve - 3 months ago 16
JSON Question

response other than true and false

I need response other than TRUE and FALSE just to display yet another message. like

echo json_encode(notloggedin);
in e.g below

public function watchlist(Request $request)
{
if($request->ajax())
{
$source=new Book();
$add->user_id=$request->id;
if(!Auth::check())
{
echo json_encode(notloggedin);die;
}
$add->save();
echo json_encode(TRUE);die;
}

echo json_encode(FALSE);die;
}
}


ajax: so that i could do.

$.ajax({
type:"POST",
url: "{{url('/bookcontroller/book')}}",
data: {id:id},
success: function (data) {
var response = $.parseJSON(data);
if(response == true)
{
swal("Book Added to list", "", "success");
}

else if(response == false)
{
swal("Opps!", "Something went wrong!. Try again", "error");
}

else if(response == notloggedin)
{
swal("Please login first", "", "error");
}

Answer

You can achieve it by slightly modifying your code as below:

public function watchlist(Request $request)
{
    if($request->ajax())
    {
            $source=new Book();
            $add->user_id=$request->id;
            if(!Auth::check())
            {            
                echo json_encode('notloggedin');die;    //if notloggedin is not a variable then you should put quote around it to make it string                     
            }
            $add->save();        
            echo json_encode(TRUE);die;
        }

        echo json_encode(FALSE);die;
    }
}

Here is modified ajax part:

    $.ajax({
        type:"POST",
        url: "{{url('/bookcontroller/book')}}",
        data: {id:id},
        success: function (data) {
            var response = $.parseJSON(data);
                if(response === true)
                {
                    swal("Book Added to list", "", "success");
                }

                else if(response === false)
                {
                    swal("Opps!", "Something went wrong!. Try again", "error");
                }

               else if(response === 'notloggedin')
              {
                   swal("Please login first", "", "error");
               }
         }
    });