Ajax does not recognize PHP echo

Asked

Viewed 114 times

1

I have a simple ajax:

$.ajax({
    url:"php/exemplo.php",
    type:"POST", 
    data:new FormData(this),
    contentType:false,
    cache:false,
    processData:false,
    success: function(resposta){
      if(resposta == '<nome>'){
        alert('deu certo');
      }
}});

In PHP I give a echo "<nome>"; and that <nome> arrives at the right ajax (checked with an Alert)... but the if does not understand that is <nome>, does not fall inside the if...

What can be the mistake?

  • 3

    What gives console.log(typeof resposta, resposta && resposta.length, resposta);?

  • Maybe you have space, use the function trim() php

  • Put PHP, always follow the MCVE (How to create a Minimal, Complete and Verifiable example): https://answall.com/help/mcve

  • PHP is just an echo "name";

  • @Geeksilva with Trim would do so? echo Trim("<name>");? If it is, did not give also....

  • @Sergio really gave this console.log 8.. and not 6 as it should

  • @ok caiocafardo, so it has blank spaces I presume or line breaks. It tests like this: if(resposta.trim() == '<nome>'){. If not, put the exact console.log result I asked for on top.

Show 2 more comments

4 answers

3

Probably the return of Ajax is coming with some space or line break along with <nome>, therefore the if understands that answer is not exactly <nome>.

One way to solve this is by changing the form of comparison with indexOf:

if(resposta.indexOf('<nome>') != -1){
  alert('deu certo');
}

1


The error was what they were talking about, some empty space was coming from PHP. I was able to adjust using Jquery’s Trim: jQuery.Trim()

Thus remaining:

if($.trim(resposta) == '<nome>'){

1

You can use the .trim() Javascript native and do if(resposta.trim() == '<nome>'){.

Thus clears blanks and line breaks before comparison.

-1

Make sure the <nome> obtained in AJAX has no extra space before or after s and is using UTF-8 without GOOD.

Browser other questions tagged

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