0

I have the 'unexpected character error' problem, my Jquery ajax code looks like that:

 function test(){
        if(true){
        $.ajax({
            type: 'POST',
            url: 'test.php',
            dataType: 'json',
            data: {
                godot: 'godot',
                jobadze: 'jobadze'
            },
            success: function(data){
                alert(data);
            },
            error: function(jqXHR, textStatus, errorThrown) { alert("Error Status: "+textStatus+"\nMessage: "+errorThrown);
            }
        });

and this is the php code:

<?php
echo 'test';
?>

it should alert "test", but it calls error. What is going on?

1
  • remove dataType from your request Commented Feb 5, 2018 at 14:09

3 Answers 3

1

You're not returning any JSON. You returning text but you've specified in the AJAX that it will return json.

You have: dataType: 'json',

You could change the dataType: 'text', if you will always be returning text

or in your php change echo 'test'; to echo json_encode('test');

Hope this helps

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

Comments

1

You wrote dataType: 'json', so the PHP script is required to return valid JSON. Since you're not, the it gets an error when it tries to parse the response as JSON, and reports that error.

You should use json_encode:

<?php
echo json_encode('test');
?>

Comments

1

it should alert "test", but it calls error. What is going on?

Reason for this is your dataType : "json" in $.ajax() method which expects the response from serverside should be a json, which is not the case because that is just a simple text string nothing else, so what could you do:

  1. Either remove the dataType or change the dataType: "text"
  2. Or do a json_encode('string') at your serverside.

As you asked in your question

It should alert "test",

so you can skip the #2 and do this:

    $.ajax({
        type: 'POST',
        url: 'test.php',
        dataType: 'text',
        data: {
            godot: 'godot',
            jobadze: 'jobadze'
        },
        success: function(data){
            alert(data); // will alert "test".
        },
        error: function(jqXHR, textStatus, errorThrown) { 
             alert("Error Status: "+textStatus+"\nMessage: "+errorThrown);
        }
    });

but it calls error

    $.ajax({
        type: 'POST',
        url: 'test.php',
        dataType: 'json', //<----because of this

See json is a {key : value} pair js object and from your php you are just echoing a string not a object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.