Search code examples
javascriptdom-events

JavaScript eval doesn't work when passing a href


I was not clear first time about ajax requests.

When I click on the link another one should appear.

Here it is what I'm trying to do (simplified), but the problem is when it appears the JS inside it doesn't want to run.

HTML:

<html><body>
<div id="result">&nbsp;</div>
<a href="javascript:suggest('result'); return true;">click to see the link</a>
</body></html>

JavaScript

function evalResponse (request)
{
    try
    {
        //var responseText = request.responseText.replace (/\n/g, " ");
        var responseText = request.responseText;
        return eval('(' + responseText + ')');
    }
    catch (e)
    {
        alert ("line: " + e.lineNumber + "\nmessage: " + e.message + "\nName: " + e.name);
    }
}


function suggest(target_div)
{
    
    var opt = {
        // Use POST
method: 'post',
        // Send this lovely data
postBody: 'Action=Edit&search_word=' + search_item + '&target=' + textarea,
        // Handle successful response
onSuccess: function(t) {
            
            var json = evalResponse (t);
            
            data = json[1];
            
            if (errors.errorText == undefined)
            {
                           document.getElementById('target_div').update(data['link']);
            }


        },
        // Handle 404
on404: function(t) {
            alert('Error 404: location "' + t.statusText + '" was not found.');
        },
        // Handle other errors
onFailure: function(t) {
            alert('Error ' + t.status + ' -- ' + t.statusText);
        }
    }

    new Ajax.Request('handler.php', opt);
}

PHP handler:

    $jsonArray = array();
    $jsonArray[1]["link"] = '<a href="javascript:alert(\'fdg\');" onClick="return true;">link</a>';

$json = new Services_JSON();
echo $json->encode($jsonArray);

Solution

  • You have some small errors which may be caused by simplifying your code.

    postBody: 'Action=Edit&search_word=' + search_item + '&target=' + textarea
    

    In this line are two undefined variables search_item and textarea. In the fiddler I modified this line to get a result from fiddler which is equal to that what comes from your php script:

    {"1":{"link":"<a href=\"javascript:alert('fdg');\" onClick=\"return true;\">link<\/a>"}}
    

    However I would not recomment to use eval! It is dangerous better use JSON.decode(response) that parses the result from the server and prevents executing e.g. a alert from the server.

    if (errors.errorText == undefined)
    

    There are you also accessing nonexisting objects also your check is wrong. errors is in this case undefined so you need to check this too. A correct comperation looks like that with the typeof operator:

    if (typeof(errors) === "undefined" || typeof(errors.errorText) === "undefined")
    

    Finally you have another small error you added too much qoutes in this line:

    document.getElementById('target_div').update(data['link']);
    

    I guess that you wanted to use this line:

    document.getElementById(target_div).update(data['link']);
    

    All together your example will work. See also this fiddler with all changes.