Ajax, Jquery and PHP: Can not read property 'length' of undefined

1

I've been trying to run this code all morning. One method loads several div, one inside another

function renderPage(e){
        var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
                                        '<h1>Bienvenido!<br>Elige una opcion</h1>' +
                                        '<div class="seeTweets">Ver Twetters</div>' +
                                        /*'<div class="addUsers">Agregar usuarios</div>' +*/
                                    '</div>';
        var contSeeLastTwitter = '<div class="tweets-container"></div>';

        $(document.body).append(contPrincipalLastTwitter);

    }

Then the idea is to put the internal div to the listener to dynamically show the content received from an array sending from php

 $('.seeTweets').click(function (e) {

        var contSeeTweets = '<div>';
        var twitterAcounts;
        e.preventDefault();
        e.stopPropagation();
        $.ajax({
            url: 'scriptPHP.php',
            type: 'GET',
            data: { usUsers: 'tweets.txt'},
            succes:
                function (response){
                    $.each(response, function (e, objt) {
                        twitterAcounts.push(objt);
                    })
                },
            error:
                function (e) {
                    console.log(e.responseType);
                    console.log('FAIL');
                }
        });

        console.log(twitterAcounts);
        contSeeTweets += '<select class="optAcounts">';
            for(i=0; i < twitterAcounts.length(); i++){
                contSeeTweets+= '<option>' + contSeeTweets[i] + '</option>'
            }

        twitterAcounts  += '</select></div>';
    });

The php array is taken from a .txt file

class processQuery{

private $userNamesTwitter = [];

function __construct() {
  $this->userNamesTwitter = $this->addUsersTwitter('tweets.txt');

	}
  
function addUsersTwitter($file){

			$handleFile = file_get_contents($file);
			$finalFile = explode(",", $handleFile);
			$this->userNamesTwitter = $finalFile;

			if ($_GET['usUsers']){
				echo json_encode($this->userNamesTwitter);

			}else{
				return $this->userNamesTwitter;
			}


		}

		function manageQueryTwitter(){
			if (isset($_GET['usTwitter'])) {
				$this->screen_name = $_GET['usTwitter'];
				$this->callTwitter();


			} else if (isset($_GET['usUsers'])){
				echo $this->userNamesTwitter;
			}

		}


	}


	$myClass = new processQuery();
	$myClass->manageQueryTwitter();

I thought it might be because of the php, but debugging a bit does not even enter the ajax block.

Thank you!

    
asked by Marco Diaz 30.09.2017 в 19:23
source

1 answer

2

As I said, I suspect that there is an understanding problem on your part about how Ajax requests work and maybe the Clases in PHP.

If you consider this fragment of your code:

$.ajax({
            url: 'scriptPHP.php',
            type: 'GET',
            data: { usUsers: 'tweets.txt'},
            ...

It means that the Ajax request is sending the following data to the file scriptPHP.php : usUsers=tweets.txt using the GET method.

Then, the file scriptPHP.php has to be ready to receive that request.

If scriptPHP.php contains the code of the class you have shared in the question, it is impossible for the code to work.

To the class code you should give it another name. For example: processQuery.php

scriptPHP.php should look like this:

//Evaluamos que se enviaron los datos de 'data' (petición Ajax)
if (isset($_GET['usUsers'])) {
    $archivo=$_GET['usUsers']; //El valor sería en este caso tweets.txt
    /*Incluimos la clase y creamos una instancia de la misma*/
    include ("processQuery.php");

    /*La clase podría recibir el nombre del archivo en parámetro*/
    $processQuery=new processQuery();
    $jsonRespuesta=$processQuery->addUsersTwitter($archivo);
}else{
    $jsonRespuesta=array("error"=>"No hay datos en la petición");
}

/*Si Ajax espera un JSON, siempre responderemos con un JSON*/
header("Content-Type: application/json", true);
echo json_encode($jsonRespuesta);

The class code also needs a retouch and an analysis. Think that classes generally represent entities of the application and are written to reuse code. Think of a class Persona through which you can get all or part of a person's data ... You have conceived a class that is really a method or a function. That class does not represent any entity. You can do it that way, but that is not the meaning of the classes. It's more its name itself is informer processQuery ... a class to process a request? In POO everything that starts with verbs are methods, not classes.

However, let's keep the class. You will see that, if we retouch it a bit, it is reduced to a simple method:

processQuery.php

class processQuery{

private $userNamesTwitter = [];

function __construct() {
//$this->userNamesTwitter = $this->addUsersTwitter('tweets.txt');

    }

function addUsersTwitter($file){

            $handleFile = file_get_contents($file);
            $finalFile = explode(",", $handleFile);
//          $this->userNamesTwitter = $finalFile;
            return=$finalFile;
//          echo json_encode($this->userNamesTwitter);

        }

/*
 *No le veo sentido a esto ¿?*
/*
        function manageQueryTwitter(){
            if (isset($_GET['usTwitter'])) {
                $this->screen_name = $_GET['usTwitter'];
                $this->callTwitter();


            } else if (isset($_GET['usUsers'])){
                echo $this->userNamesTwitter;
            }

        }
*/

    }

/*
    $myClass = new processQuery();
    $myClass->manageQueryTwitter();
*/

Honestly, in this context, I do not see any sense in using a class. I have commented part of your code, because you use variables that do not appear as part of the class, etc. In addition, evaluating the request GET within the class seems to me a bad practice, because you create the instance of the class, then evaluate the request and if it is not set, you will have created an instance of an object for nothing.

For cases like yours you could handle everything without the need of a class. Give the impression that you use a Clase just because ... Classes have their reason for being.

I have left it like that because I do not know how to give more scope to your class. But the code is incoherent on many points. I have already mentioned almost all of them, but for example: the file name tweets.txt that you send from Ajax, you never use it. What do you send it for? Then, in the constructor, you put by hand the name of the file. By doing that, you limit that class to being used only with files that are called tweets.txt . One of the reasons to be of the Classes is to reuse the code ... when you put fixed data in them they lose that feature.

Ajax

Then your Ajax request is also incoherent.

If you make a request, you can not handle things outside of success or fail (they are obsolete functions but I do not want to deal with that now).

What I want you to understand for now, is that success and fail serve to know if the request was successful or not.

  • If successful, you must do within the success block everything that is the result of a successful request.
  • If you did not succeed, you should indicate that there was an error.

Therefore, this:

    console.log(twitterAcounts);
    contSeeTweets += '<select class="optAcounts">';
        for(i=0; i < twitterAcounts.length(); i++){
            contSeeTweets+= '<option>' + contSeeTweets[i] + '</option>'
        }

    twitterAcounts  += '</select></div>';

It should not be outside the success . Who guarantees that everything will work well? In fact, it is malfunctioning and you have the current error, because twitterAcounts did not fill up as you expected in success .

Also, it is good to place the type of data you expect from the server to the Ajax request.

The code should look something like this:

$('.seeTweets').click(function (e) {

    var contSeeTweets = '<div>';
    var twitterAcounts;
    e.preventDefault();
    e.stopPropagation();
    $.ajax({
        url: 'scriptPHP.php',
        type: 'GET',
        data: { usUsers: 'tweets.txt'},
        dataType: "json",
        succes:
            function (response){
                $.each(response, function (e, objt) {
                    twitterAcounts.push(objt);
                })

                console.log(twitterAcounts);
                contSeeTweets += '<select class="optAcounts">';
                for(i=0; i < twitterAcounts.length(); i++){
                    contSeeTweets+= '<option>' + contSeeTweets[i] + '</option>'
                }
                twitterAcounts  += '</select></div>';
            },
        error:
            function (e) {
                console.log(e.responseType);
                console.log('FAIL');
            }
    });

});
    
answered by 01.10.2017 / 03:19
source