Request Ajax jquery Jsonp Returning Undefined

Asked

Viewed 168 times

1

I need to process the feedback of the following code below. Remembering that it works correctly but, at some point, the search term does not exist returning "Undefined" and shows nothing on the screen. I need you to search for a locally saved default image right now. Thank you in advance.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">

$.ajax({  
type: "GET",
url: "http://alvoparabusca.com.br", 
data: {termo:"termo da busca",limitado:1,tipo:"imagem"},

success: function(data){
    img = data["resultado"][0].imagem;
    $("html").css({"background-image":"url("+ img +")"});
},
dataType: "jsonp"
});

</script>
  • if you give a console.log in. data what the result?

  • When Undefined returns the Console returns: Object {resultCount: 0, Results: Array[0]}

1 answer

0


success: function(data) {
  if (data && data.resultCount > 0) {
    img = data["resultado"][0].imagem;
    $("html").css({
      "background-image": "url(" + img + ")"
    });
  } else { //Se não for localizado, seta sua imagem default
    $("html").css({
      "background-image": "url(suaImagemDefault.jpg)"
    });
  }
}

that would be it ?

  • That’s the idea Brunno, but it didn’t work here, when there is the image is giving the same problem within the if. I tried to switch to if (date === 'Undefined') so it passes to Else and stays there, even though the image exists.

  • @Emetec, try the if according to the Edit I did in the reply

  • Nothing yet @Brunno. Every time you enter if to compare it closes indicating that "image" is "Undefined" does not run Else. I am trying to validate before the sucess. If there is a value it executes the sucess otherwise it goes to error.

  • @Emetec, friend, if you add a console.log(data); before if, what does it print on your brownser console ? Undefined, 'Undefined', null ?

  • Displays the following @Brunno: Object {resultCount: 0, Results: Array[0]} and below: Uncaught Typeerror: Cannot read Property 'image' of Undefined

  • @Emetec, according to your return it looks like the resultCount arrow the result amount so just change the if to: if (date & & date.resultCount > 0) I edited the answer. Test there :)

  • 1

    Perfect @Brunno. Now it worked correctly. Thank you so much.

Show 2 more comments

Browser other questions tagged

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