Unwanted line break in PHP output

Asked

Viewed 323 times

1

I have a php code that after performing an instruction, returns a string to AJAX.

  • The problem is that this string is coming out with line breaks that don’t exist. (Both in php and in AJAX return in Javascript)

Look at the code:

<?php
	
	date_default_timezone_set('America/Sao_Paulo');
	require_once("conexao.php");
		
	setlocale(LC_ALL, "", "pt_BR.utf-8");
	
	//CLASSE PARA VERIFICAR SE A EMPRESA JÁ POSSUI O BENEFÍCIO
	
	class Usuarios
	{				
		private $nome;
		private $idade;
		private $cidade;
		
		public function __get($atributo)
		{			
			return $this->$atributo;
		}
		
		public function __set($atributo, $valor)
		{			
			$this->$atributo = $valor;
		}		
							
		public function cadastrar()
		{	
			try
			{			
				//Conexão com o Banco de Dados (Futuramente podemos atribuir essa conexao a uma classe
				$c = new Conexao();
				$conexao = $c->conectar();
								
				$query = "INSERT INTO usuarios(nome,idade,cidade)VALUES(:nome,:idade,:cidade)";
				
				$stmt = $conexao->prepare($query);
				$stmt->bindValue(':nome',$this->nome);
				$stmt->bindValue(':idade',$this->idade);
				$stmt->bindValue(':cidade',$this->__get('cidade')); //Pode ser assim também
				
				$stmt->execute();
				$total = 0;
				$total = $stmt->rowCount();

				
				if($total > 0)
				{					
					echo "sucesso";	
					die();
				}
				else
				{
					echo "falha";	
					die();
				}
				
			}
			catch(PDOException $e)
			{
				//Verificando o erro ocorrido
				echo "Erro: ".$e->getCode()." Mensagem: ".$e->getMessage();				
			}
		}	

	
		
	}
		
		
	if(isset($_POST['cadastrar']))
	{
		$nome = filter_input(INPUT_POST, 'nome', FILTER_SANITIZE_STRING); 
		$idade = filter_input(INPUT_POST, 'idade', FILTER_SANITIZE_STRING);
		$cidade = filter_input(INPUT_POST, 'cidade', FILTER_SANITIZE_STRING);
		
		$usuarios = new Usuarios();
		
		$usuarios->__set('nome',$nome);
		$usuarios->__set('idade',$idade);
		$usuarios->__set('cidade',$cidade);

		$usuarios->cadastrar();
	}

?>

How are the exits:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

  • With this, the condition of the If and if Else below (in JS) are never met. Precisely because of line breaks.

//EVENTO PARA QUANDO SUBMITAMOS O FORMULÁRIO 
$('#formulario-crud').submit(function(e) {
  e.preventDefault();

  let formulario = $(this);

  $.ajax({
    url: "classes/classes.php",
    type: "post",
    dataType: "html",
    data: formulario.serialize(),


  }).done(function(data) {

    console.log(data);
    if (data == "sucesso") {
      alert("Usuário Cadastrado com Sucesso");
    } else if (data == "falha") {
      alert("O usuário não foi cadastrado");
    }

  }).fail(function() {

  }).always(function(retornoempresas) {

  });

});

  • I would like to do it in a way that would identify and solve the problem at its source. I would like to avoid things like Trim(), etc... I would actually like to know the cause of the line breaks. Could you help me ?
  • 2

    Check if before the tag <?php opening script has no spaces or blank lines, if these lines are present they will be included in the output. Blank spaces or lines after tag ?> script completion will also be included in the output. Check it in the files included in your script.

  • Okay, @Augustovasques. I will have access to that code in the evening. I will check and I will be at your suggestion. Thank you!

  • @Augustovasques , I checked these situations and did not solve. Very strange this.

  • My code is exactly as provided here.

  • Even in another file, using json_encode, this is happening.

  • You checked the conexao.php?

  • Worse than that file I didn’t check. I’ll check and give you a Return.

  • I checked everything. Everything seems to be in order and according to your recommendations. I’m still having the problem. If you want the whole code I can send it to you or something.

  • Sends the code....

  • I was told that it is not very nice to send PHP code by Fiddle, but it was the only way I can send all parts (including HTML and JS). https://jsfiddle.net/fksjdnLt/

  • I need the files just like they’re on the servers. For example, the way you put lines 148, 149, 150 and 15 of the html file would be responsible for the spaces. Use a virtual driver or put the project on github.

  • All right, https://github.com/thiagopetherson/crud-oo.git

  • I created a host for the your script, time I have some time off I take a look.

  • The database is missing.

Show 9 more comments

1 answer

1

Use Javascript . Trim() function in return:

data.trim()

O . Trim() eliminates spaces on the edges of the string.

  • Hello, Sam. You as always helpful. Thank you. But dude, I wouldn’t want to do it that way with Trim(). I would really like to know why PHP is giving this output with line breaks in echo. I think by doing Trim(), we’d just be 'covering the sun with the sieve'. Since this is probably a PHP error. You don’t agree ?

  • Dude, if you want a string returned, the PHP document that will return this string will possibly return with spaces. O . Trim() eliminates these spaces.

  • Oops, Sam. But that doesn’t usually happen to me. The string that returns to Ajax always arrives in the exact way that leaves php.

  • Have you tried replacing possible line breaks, like: data.replace(/\n/g, '').trim()?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.