10

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.

4
  • Do a var_export($translated); instead of echo json_encode($translated); and post the results, please. Commented Jan 9, 2016 at 22:13
  • Thanks Tomas, the returned info. is: Details: parsererror Error: SyntaxError: Unexpected token a array ( 0 => ' jQuery Traductor', )array ( 0 => 'Hola mundo', ) Commented Jan 9, 2016 at 22:41
  • Could we see more php code? It seems that echo json_encode($translated); is executing twice. That is the only way to produce a string that is two jsonArrays that are together: "[...][...]". Commented Jan 9, 2016 at 22:57
  • I think you are onto something here Tomas. I revise the code and test. Commented Jan 10, 2016 at 0:13

1 Answer 1

4
+50

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);
Sign up to request clarification or add additional context in comments.

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.