Ajax json javascript

Therefore, trying to pass javascript values ​​to php script using Ajax, I get the following error message.

Uncaught SyntaxError: Unexpected end of input

While passing through the code that I found, I saw that my answer from my script returned a null string. Someone, please, point me to my mistake, I cannot understand it.

Here is my javascript (request.js)

var request;

function getHTTPObject()
{
    var xhr = false;
    if (window.XMLHttpRequest)
    {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try
        {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
                xhr = false;
            }
        }
    }
    return xhr;
}

function runAjax(JSONstring)
{
    // function returns "AJAX" object, depending on web browser
    // this is not native JS function!
    request = getHTTPObject();
    request.onreadystatechange = sendData;
    request.open("GET", "request.php?json="+JSONstring, true);
    request.send(null);
}

// function is executed when var request state changes
function sendData()
{
    // if request object received response
    if(request.readyState == 4)
    {
    // parser.php response
    var JSONtext = request.responseText;

    // convert received string to JavaScript object
    var JSONobject = JSON.parse(JSONtext);


    // notice how variables are used
    var msg = "Number of errors: "+JSONobject.errorsNum+
        "\n- "+JSONobject.error[0]+
        "\n- "+JSONobject.error[1];

    alert(msg);
    }
}

my php file.

<?php
//request.php
$decoded = json_decode($_GET['json']);

$json = array(
    'errorsNum'    =>    2,

    'error'       =>    array(
                        "error 1","error 2!"
                 )
);

$encoded = json_encode($json);

die($encoded);

?>

and finally my html file where I call ajax.

<html>
<head>
<script src="request.js">
</script>
</head>
<body>
<a href="Javascript:runAjax('vinoth')">call</a><br>
</body>
</html>

Thanks in advance.

+3
source share

All Articles