How to send data from php to jquery ajax success handler in case php issues a warning?

I am trying to send data from PHP to a jQuery success handler and then process that data.

I did it just php echoand then got an echo line in the response text of the ajax success handler. This is not my question.

PHP:

function function_name() {
    $Id = $_POST['id'];
    if(/*condition*/){
        echo "yes";
    }
}

JS:

$.ajax({
    type:'POST',
    data:{action:'function_name', id:ID},
    url: URL,
    success: function(res) {
        if(res == 'yes'){
            alert(res);
        }
    }
});

The above example gives a warning. So far, everything is perfect.

My question is if PHP triggers any warning, the text of the response to ajax success is filled with two things:

  • Warning line
  • php echo string and therefore js if the condition fails.

What is the best successful way to send data from php to ajax success handler if there are any warnings from php?

+4
5

.

php , .

HTTP 200 OK.

PHP 400/500 HTTP.

success, .

. JavaScript:

, :

$.ajax({
    type: "POST",
    url: url,
    data: $form.serialize(),
    success: function(xhr) {
        //everything ok
    },
    statusCode: {
        400: function(xhr, data, error) {
            /**
             * Wrong form data, reload form with errors
             */
            ...
        },
        409: function(xhr, data, error) {
            // conflict
            ...
        }
    }
});

, :

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "YOUR ERROR HANDLING" );
  })
  .always(function() {
    alert( "finished" );
});

PHP:

, , PHP , , . symfony2 HTTP Kernel. - . , Silex, HTTP-/ , .

silex, :

index.php:

<?php
use Kopernikus\Controller\IndexController;
require_once __DIR__ . '/vendor/autoload.php';

$app = new Silex\Application();

$app['debug'] = true;

$className = IndexController::class;

$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app['controller.index'] = $app->share(
    function () use ($app) {
        return new IndexController();
    }
);
$app->post('/', "controller.index:indexAction");

$app->error(
    function (\Exception $e, $code) {
        switch ($code) {
            case 404:
                $message = 'The requested page could not be found.';
                break;
            default:
                $message = $e->getMessage();
        }

        return new JsonResponse(
            [
                'message' => $message,
            ]
        );
    }
);        
$app->run();

src/Kopernikus/Controller/IndexController.php:

<?php
namespace Kopernikus\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * IndexController
 **/
class IndexController
{
    public function indexAction(Request $request)
    {
        $data = $request->request->get('data');

        if ($data === null) {
            throw new BadRequestHttpException('Data parameter required');
        }

        return new JsonResponse(
            [
                'message' => $data,
            ]
        );
    }
}

HTTP 200 OK, .

httpie, curl.

:

$ http --form  POST http://localhost:1337 data="hello world"
HTTP/1.1 200 OK
Cache-Control: no-cache
Connection: close
Content-Type: application/json
Date: Wed, 14 Oct 2015 15:37:30 GMT
Host: localhost:1337
X-Powered-By: PHP/5.5.9-1ubuntu4.13

{
    "message": "hello world"
}

:

, :

$ http --form  POST http://localhost:1337 
HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Connection: close
Content-Type: application/json
Date: Wed, 14 Oct 2015 15:37:00 GMT
Host: localhost:1337
X-Powered-By: PHP/5.5.9-1ubuntu4.13

{
    "message": "Data parameter required"
}

:

$ http --form  GET  http://localhost:1337 data="hello world"
HTTP/1.1 405 Method Not Allowed
Allow: POST
Cache-Control: no-cache
Connection: close
Content-Type: application/json
Date: Wed, 14 Oct 2015 15:38:40 GMT
Host: localhost:1337
X-Powered-By: PHP/5.5.9-1ubuntu4.13

{
    "message": "No route found for \"GET /\": Method Not Allowed (Allow: POST)"
}

, github.

+5

, . better json, .

$response=array();
// A user-defined error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    global $response;
    $err= "<b>Custom error:</b> [$errno] $errstr<br>";
    $err.=  " Error on line $errline in $errfile<br>";
    $response['error']=$response['error'].PHP_EOL.$err;
}

// Set user-defined error handler function
set_error_handler("myErrorHandler");

//now your stuff
function function_name() {
    global $response;
    $Id = $_POST['id'];
    if(/*condition*/){
        $response['data']="yes";
        echo $response['data'];
        //better option
        //echo json_encode($response); **get data and errors sepratly**
    }
}

, seprately json_encode ajax - -

$.ajax({
    type:'POST',
    data:{action:'function_name', id:ID},
    url: URL,
    success: function(res) {
        var response=JSON.parse(res);
        if(response.errors!="")
         { alert('error occured - '+ response.errors);}
        alert("data recived "+  response.data);

    }
});
+1

, , PHP, if else if...,

if (res == 'yes') {
    alert(res);
} else if (res == 'no') {
    alert('no');
} else {
     alert('error');
}           
0

, , php- "" , , . , , , .

, js . , , , , , , , js, , JSON.

0

PHP, . , - , .

, , , . . exception, , . , JSON.

class MyResponse {
     protected $code;
     protected $response;
     protected $isException;
     protected $formFields;

/**
 * Creates a NavResponse object that will be delivered to the browser.
 */
    function __construct($code, $response = null, $field = false, $exception = false) {
        $this->code = $code;
        $this->formField = $field;
        $this->response = $response;
        $this->isException = $exception;
    }
}

class MyException extends Exception {

    function __construct($code, $log = null, $field = null) {
        self::$exceptionThrown = true;
        $this->_code = $code;
        $this->_field = $field;
        if ($log) {
            // store log message.
        }
    }

    public function response() {
        return new MyResponse($this->_code, null, $this->_field, true);
    }
}
0

Source: https://habr.com/ru/post/1611587/


All Articles