0

I have an issue with parsing json in my success function (ajax). I am now starting to learn json properly, but I simply can't get this to work.

I have this jquery function to submit data:

$("#loginForm").on('submit', function(form)
{   
    form.preventDefault();
    var tdata= $("#loginForm").serializeArray();
    var that = $(this),
    data = tdata;

    $.ajax({
        url: that.attr('action'),
        type: 'POST',
        data: data,

        success: function(data){

            alert(data["error"]["email"]);
        },
        error: function(){
            alert(data["error"]["email"]);
        }
    });

 });

In the controller I have this:

$this->load->library('form_validation');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'required');
 .....
$arrReturnData['error'] = $this->form_validation->error_array();
 echo json_encode($arrReturnData);

In firefox when I trace the requests, the string received is:

{"error":{"email":"The Email field is required.","password":"The Password field is required."}}

But I cannot parse it :( I don't know how, and I've spent more than 3 hours just on this part. Everything works just that I can't parse this.

I tried like:

data.error["email"]

or

data[0]["email"]

But It fails to get the email error message. Please help :)

BlasterGod
  • 196
  • 1
  • 13
  • check https://stackoverflow.com/a/4935684/2275490 and related – Vickel Oct 21 '17 at 00:07
  • It should work as long as you have the same JSON coming back to the success callback. What is the response content type ? Is it text or `application/json`? – Shyju Oct 21 '17 at 00:10
  • When I use alert(data) I get [object Object],[object Object],[object Object] . If I use obj=JSON.parse(data); alert(obj.error); I get the error "JSON.parse: unexpected character at line 1 column 2 of the JSON data" – BlasterGod Oct 21 '17 at 00:13
  • Does data.error.email work? – TimBrownlaw Oct 21 '17 at 00:37
  • You might also need to set dataType: json – TimBrownlaw Oct 21 '17 at 00:38
  • If I alert(data.error.email) it gives me TypeError: data.error is undefined I tried adding dataType: json and no success :( The response payload (from firefox developer tools, network trace) is { "error": { "email": "The Email field is required.", "password": "The Password field is required." } } – BlasterGod Oct 21 '17 at 12:59

1 Answers1

0

I found a solution. I couldn't manage to work with the data variable. What I did, is modified the error function (jquery ajax) like this:

error: function(request, status, error){
                var json=request.responseText;
                obj = JSON && JSON.parse(json) || $.parseJSON(json);
                alert(obj.error.email);

            }

So I use JSON.parse of the request.responseText. And now I can successfully use obj.error.email

BlasterGod
  • 196
  • 1
  • 13