开发者

Foreach Loop only executing once when called with Ajax

I'm trying to loop through a textarea array ($taskLinks) with PHP and check each new line entry against the database for matches and return the matches ($a) from the database:

    $a = array();
    $array = split("\r\n", $taskLinks);
    foreach($array as $url){
    $query = "SELECT url FROM links
    WHERE  `url` 
    LIKE  '$url'
    AND `projectId` = '$projectId'";    
    $result = mysql_query($query);
    $row = mysql_fetch_object ($result);
    $matchedLink = $row->url;
    array_push ($a,$matchedLink);
    }
    foreach ($a as $row){
        echo "$row\r";
    }

The PHP script (called linkchecker.php) above works perfectly but im trying to call it with AJAX when the user adds to the textarea and then returns any matches from the above. To do this I have the below, combined with onChange="ajaxFunction()" on the textarea.

ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                var ajaxDisplay = document.getElementById('ajaxDiv');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
                document.myForm.time.value = ajaxRequest.responseText;
            }
        }
        var taskLinks = document.getElementById('taskLinks').value;
        <!--
        <?php 
        echo("var projectId = ('$projectId');");
        ?>
        // -->
        var queryString = "?taskLinks=" + taskLinks + "&projectId=" + pro开发者_运维技巧jectId;
        ajaxRequest.open("GET", "linkchecker.php" + queryString, true);
        ajaxRequest.send(null); 
    }

The problem is the php script only seems to work when one line is added to the textarea - the variables are passing to the script in the query string and the PHP script works but only for one line in the textarea - I need it to work for for multiple lines like it does normally.

What can I do to the AJAX to make sure the PHP script checks every entry in the textarea?


Looks like the \r is lost when working with values of textarea's, so your pattern "\r\n" does not match.
You may use :

$array = split("[\r\n]+", $taskLinks);

...instead.

Or use e.g. jQuery's serialize() (if possible), it keeps the \r

If you cannot use jQuery you also may use jQuery's approach to keep the \r .
It replaces inside strings occurencies of /\r?\n/g with "\r\n"

EDIT:


you also need to encode the parameters:

var queryString = "?taskLinks=" + encodeURIComponent(taskLinks) + 
                  "&projectId=" + encodeURIComponent(projectId);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜