Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax Parse Error when returning array from PHP

I have read most of the SA questions regarding this issue, but none have solved my problem.

The following code is passing a JavaScript array to PHP5. This works fine, but when I return a PHP array to the ajax code, a

parserror: unexpected token "[" is returned. 

JS

        $(function () {
            translate($("h1,p"));
            function translate(selection$) {
                var elements = [];
                for (i = 0; i < selection$.length; i++) {
                    elements.push(selection$.get(i).outerHTML);
                }
                var jString = JSON.stringify(elements);
                $.ajax({
                    url: 'test.php',
                    type: 'post',
                    data: { 'data': jString },
                    cache: false,
                    dataType: 'json',
                    success: function (data, status) {
                        $("#after").append(data);
                    },
                    error: function (xhr, desc, err) {
                        alert("Details: " + desc + "\nError: " + err + "\n" + xhr.responseText);
                    }
                }); // end ajax call
            }
        });

The stringified array passed is

["jQuery Translator","Hello World"]

PHP

EDIT

The complete PHP code is:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if('POST' == $_SERVER['REQUEST_METHOD'])
{
    include 'HttpTranslator.php';
    include 'AccessTokenAuthentication.php';
    if (!empty($_POST['data'])) {
        $elements = json_decode($_POST['data']);
    }
    $auth = new AccessTokenAuthentication();
    $authHeader=$auth->authenticate();
    $fromLanguage = "en";
    $toLanguage   = "es";
    $contentType  = 'text/html';
    $category     = 'general';
    //Create the Translator Object.
    $translatorObj = new HTTPTranslator();
    foreach ($elements as $element) {
        $params =   "text=".urlencode($element)."&to=".$toLanguage."&from=".$fromLanguage;
    $translateUrl =  "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
        //Get the curlResponse.
        $curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);    
        //Interprets a string of XML into an object.
        $xmlObj = simplexml_load_string($curlResponse);
        $translated = array();
        foreach((array)$xmlObj[0] as $val){
            array_push($translated, $val);
        }
        header('Content-type: application/json');
        var_export($translated);
    }
}

?>

The xhr.responseText is

"["<h1>jQuery Traductor<\/h1>"]["<p>Hola mundo<\/p>"]"

which does not look like json to me. I am not a PHP5 expert, but suspect I am not filling the array correctly. Any help is appreciated.

like image 534
ron tornambe Avatar asked Jan 07 '16 20:01

ron tornambe


1 Answers

Move the

  header('Content-type: application/json');
    var_export($translated);

outside the foreach of $elements.

Also initialize $translated = array(); before the foreach of $elements.

Like this:

$translated = array();
foreach ($elements as $element) {
    $params =   "text=".urlencode($element)."&to=".$toLanguage."&from=".$fromLanguage;
    $translateUrl =  "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
    //Get the curlResponse.
    $curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);    
    //Interprets a string of XML into an object.
    $xmlObj = simplexml_load_string($curlResponse);

    foreach((array)$xmlObj[0] as $val){
        array_push($translated, $val);
    }

}

 header('Content-type: application/json');
 var_export($translated);
like image 140
Tomás Avatar answered Oct 04 '22 14:10

Tomás