Question

I am trying to create a simple AJAX call using JSON, but I keep getting a parse error on the result and when I check the resultText it shows the source code of the entire page, with the JSON response showing a success above the page headers.

Here is my AJAX call, where #class is a select box with values.

$("#class").change( function () {
            if($('#class').val().length > 0){

                    $.ajax({

                        type: "GET",
                        url: "http://192.168.0.9/ajax",
                        data: 'class_id=' + $("#class").val(),
                        datatype: 'json',
                        async: 'true',
                        beforeSend: function() {
                            alert("Before send!");
                        },
                        success: function(result){
                           if (result.status){

                                $('#result').html(result);
                         } else {
                            alert('request unsuccessful!'); 
                         }

                        },
                        complete: function() {
                            alert("Complete!");

                        },
                            error: function (request,error) {
                             alert('A jQuery error has occurred. Status: ' + error +':'+ request.responseText);                           
                             $("#result").html(request.responseText);  


                        }
                    });                   
            } else {
                alert('Please make a selection');
            }           
            return false; 

            }); 

This is my PHP function that returns the result

$result = array();
    $result['status'] = "success";
    $result['message'] = "Types";
    header("Content-Type: application/json; charset=utf-8", true);
    echo json_encode($result);

Finally, this is the response I am getting in my error alert:

A jQuery error has occurred status:parseerror
{"status":"success", "message":"Types"}<!DOCTYPE html>
<html>
...rest of my page from where the request was sent

I am hoping this is a simple error and someone can tell me what I am doing wrong?

Was it helpful?

Solution

Perhaps your parameter should be pass in JSON format:

data: "{'class_id':'" + $("#class").val() + "'}",

OTHER TIPS

Try to remove datatype:'json' from the Javascript and header("Content-Type: application/json; charset=utf-8", true); it should be recognize itself

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top