shanseti vikas
shanseti vikas

Reputation: 49

loop executes only last array element using php, ajax and javascript

Hi friends am trying to save the data from the loop here is my code.

<html>
 <head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 </head>
<body onload="searchVideo();">
<?php
    ini_set('max_execution_time', 300);
    $query = "SELECT * FROM `playlists`";
    $result = mysqli_query($mysql,$query);
    while($row=mysqli_fetch_assoc($result)){
          $id=$row['id'];
          $playlists=$row['playlists'];
          $myArray = explode(',', $playlists);
              $length =  sizeof( $myArray);
              $myArray[0]=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-
              $myArray[1]=PLFgquLnL59ak1QNHmrUSjNM6WTegpgX__
              for ($i=0; $i<$length; $i++){
               echo "
                  <script>
                    var pageToken = '';
                    var numOfResult = 0;
                    var maxResults = 200;
                    function searchVideo(){
                    var separator = ',';
                    $.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken=' + pageToken + '&playlistId=$myArray[$i]&key=APIKEY&callback=?',function(data){
                    var l = data.items.length;
                    pageToken = data.nextPageToken;
                    numOfResult += l;
                    var itemUrl = '';
                    var videoids = [];
                    for(var i = 0; i < l; i++) {
                    if( i == 0) {
                        separator = ',';
                       }
                   else {
                       separator = ',';
                   }
                   var videoid = data.items[i].snippet.resourceId.videoId;
                   var title = data.items[i].snippet.title;

                   $.ajax({
                     method: 'POST',
                     url:    'add.php',
                    data: { title: title, videoid: videoid }
                   })
                  .done(function(data) {

                 });
              }

            if( numOfResult <= maxResults) {
               searchVideo();

            }
    });

}

    </script>
    ";
              }

    }



?>

add.php

<?php
 $title = mysqli_real_escape_string($mysql,$_POST['title']);
 $videoid = mysqli_real_escape_string($mysql,$_POST['videoid']);
 $thumbnail_url = 'http://img.youtube.com/vi/'.$videoid.'/hqdefault.jpg';

  $sql = "INSERT INTO ytfb(name,video_name,thumbnail_url)     VALUES('$title','$videoid','$thumbnail_url')";
    $create_post_query=mysqli_query($mysql,$sql);
        if(!$create_post_query)
      {
        die("Connection failed".mysqli_error($mysql));
       }
 ?>

When am trying to save the data using ajax in add.php the elements from the last array element are only saved the elements from the first array element is not saved how can I be able to save the data from all the array elements. Can anyone please help me out with this

Upvotes: 0

Views: 213

Answers (2)

Kancho Iliev
Kancho Iliev

Reputation: 701

Define the function searchVideo outside the cycle and organize to call it with different parameters. In cycle change global vars or input parameters of searchVideo. Now you get this result because finaly executes the last istance of this function.

Upvotes: 1

Deepak Kumar T P
Deepak Kumar T P

Reputation: 1076

 for(var i = 0; i < l; i++) {
                    if( i == 0) {
                        separator = ',';
                       }
                   else {
                       separator = ',';
                   }
                   var videoid = data.items[i].snippet.resourceId.videoId;
                   var title = data.items[i].snippet.title;

Here i will be the index of last element so only last item is getting stored. You have to loop the ajax call through the loop to get all elements to be saved.

Upvotes: 0

Related Questions