Can you please tell me how to correctly return data from a php handler for ajax requests? And how to write this handler in general? I admit, always just returning data via echo , but something tells me that this is not quite correct.

Here is an example:

 $.ajax({ type:"POST", url:"../lib/ajax.php", data: {send:act, login:login, password:password}, cache: false, success: function(reply){ alert(reply); if(reply == 'true'){ $('.login-status').text('Ok'); $('.login-status').fadeTo(0, 1); $('.login-status').fadeTo(4000, 0); $('[name = login]').val(''); $('[name = password]').val(''); } } }) 

Handler:

 if(isset($_POST['login'])){ $login = $POST_['login']; $password = $POST_['password']; ... echo 'true'; } } 
  • What is meant by the correct data return? echo after all works and even, it seems as, is not a crutch. - Regent
  • @Regent I always thought that it’s not customary to return data through echo , but somehow they do it differently. - withoutname
  • If, for example, a framework is used (Yii and others), then yes, they do it differently (although who knows how he gives the page to Yii). And whether to give in plain text, HTML, JSON or some other format - it depends on the situation. Although JSON is often the most convenient option. - Regent

1 answer 1

Return data in JSON format. To do this, use json_encode.

Your ajax request code:

 $.ajax({ type:"POST", url:"../lib/ajax.php", data: {send:act, login:login, password:password}, cache: false, success: function(reply){ var res = jQuery.parseJSON(reply); if(res.login){ $('.login-status').text('Ok'); $('.login-status').fadeTo(0, 1); $('.login-status').fadeTo(4000, 0); $('[name = login]').val(''); $('[name = password]').val(''); } else { alert(res.error); } } }); 

Your handler:

 $res = array(); if(isset($_POST['login'])){ $login = $POST_['login']; $password = $POST_['password']; if(логин и пароль не совпадают){ $res['error'] = 'Логин или пароль введены неверно!'; } else { ... ... $res['login'] = true; } echo json_encode($res); } 
  • four
    @alexkad, it is more logical to add the dataType: 'json' parameter to the AJAX parameters, rather than writing var res = jQuery.parseJSON(reply); - mJeevas
  • @mJeevas, I agree, it is possible and so. - alexkad