user1763032
user1763032

Reputation: 427

Jquery: ajax loop

I am trying to make a page which tells me on which page of youtube search results my video is ranked. I am using AJAX.

I have this is in my php page

<?php
$search_term = "Search Term";
$page_link = "rbdSxr9Vvw0"; //this is the youtube video id
$search_term = str_replace(" ","+",$search_term);
$youtube_search = "http://www.youtube.com/results?search_query=".$search_term."&";
$i = $_POST['i'];
if(strpos(file_get_contents($youtube_search."page=$i"),$page_link) == false){
echo "not found";
}else{
echo "found";
}
?>

I need to write jquery function which will send numbers starting from 1 to the php page. It needs to show the current page it's checking and the result. It needs to stop when the result says "found". Thanks in advance.

EDIT:

I ended up using this code:

In my html page:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<script type = "text/javascript" src = "../jquery.js"></script>
</head>
<body>
<script type = "text/javascript">
function checkPage(i){
    console.log("checking page", i);
    $.ajax({
        url: "ajax.php",
        data: {page: i},
        success: function(data){
            if(data != "found"){
                $('#div').text("not found at "+i);;
                checkPage(i+1);
            }
            else {
                alert("found at page "+i);
            }
        }
    });
}

checkPage(1);
</script>

</body>
<div id = "div"></div>
</html>

In my ajax page:

<?php
$search_term = "search term";
$page_link = "ZXsdlk0_HuQ"; //this is the youtube video id
$search_term = str_replace(" ","+",$search_term);
$youtube_search = "http://www.youtube.com/results?search_query=".$search_term."&";
$result = "false";
$i = $_GET['page'];
if(strpos(file_get_contents($youtube_search."page=$i"),$page_link) == false){
echo "not found";
}else{
echo "found";
}
?>

Upvotes: 0

Views: 174

Answers (2)

winhowes
winhowes

Reputation: 8065

You could do something like this. You'd have to receive the "page" in your PHP, but this would work.

function checkPage(i){
    console.log("checking page", i);
    $.ajax({
        url: "myPHPPageURL",
        data: {page: i},
        success: function(data){
            if(data != "found"){
                checkPage(i+1);
            }
            else {
                alert("found at page "+i);
            }
        }
    });
}

checkPage(1);

Upvotes: 1

Andrew Paramoshkin
Andrew Paramoshkin

Reputation: 989

var loop_end = SMTH;

for (var i = 0; i < loop_end; i++) {
   $.ajax({
     url: '/path/to/script.php',
     type: "POST",
     data: {i: i},
     success: function (data) {
     }
  });
}

Upvotes: 1

Related Questions