0

I am using jquery ajax to retrieve data from a php function.

My php function is as follows

<?php

    if(isset($_GET['action'])) {

        $data = array();
        $data[0]["field"] = "data";
        echo json_encode($data);

    } else {

        // error
        return;

    }

?>

and I am calling using the jquery ajax in my javascript

$.ajax({
    url : '../functions/php/function.php',
    type : 'GET',
    dataType : 'json',
    data : {'wrong','wrong'},
    success : function(data) { console.log('all ok') },
    error : function(log) { console.log('not ok') }
});

Instead of just returning from the php function with nothing is it possible to retrieve an error so that the jquery executes the error function?

3
  • Return a status code of anything other than 2xx from your PHP code and the error handler will execute Commented Nov 8, 2016 at 14:51
  • Json sorry I'll fix my laziness Commented Nov 8, 2016 at 14:51
  • 1
    {'wrong','wrong'} should be pair of key:value Commented Nov 8, 2016 at 14:52

1 Answer 1

1

You can set header with any http status code lets say 400 http_response_code(400). When jQuery Ajax function sees the status code other than 200 it will execute your error callback function.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the right answer, they are right though it is a duplicate question I just couldn't find it. Thanks a bunch for your help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.