ajax response php error

Hi, before working with yii2, i used to code regular php with jquery ajax.

Usually i just code javascript like this


var parameters = {var1:var1, var2:'some text here'};				

				

$.post('a url for php file',parameters,success);

function success(response,status,xhr){

   //alert(response);

   var obj = jQuery.parseJSON(response);

   //some javascript code

}

the php file will return response string using this code


echo json_encode($data);

When the jquery $.post executed, if there are any error in the php file , those error will be return as part of response string. I can view the error by executing alert(response) or console.log(response) in callback function success().

Working with yii2, i use the same script. But ‘url for php file’ is replace with baseUrl/controller/action. The script work as intended.

But if there are any error in the controller/action method, the callback function success() wont be executed.

So how to view the php error in controller/action method after jquery $.post executed?

Thx.

Yii (and all frameworks in general), in case of execution error return an http header with 500 Internal Server Error

So jquery seeing this in the response does not trigger the success event but the fail one

Try something like




var parameters = {var1:var1, var2:'some text here'};          	

          	

$.post('a url for php file',parameters,success)

	.fail(function(error) {

    	alert(error);

	});


function success(response,status,xhr){

   //alert(response);

   var obj = jQuery.parseJSON(response);

   //some javascript code

}



You old code was working because you didn’t modify the header in case of errors, therefore for jquery the output was correct

Thanks for your help. To display the error i code like you show and add .responseText to the error variable like below


$.post('a url for php file',parameters,success)

        .fail(function(error) {

        alert(error.responseText);

        });