AJAX receives JSONP as "Undefined"

Asked

Viewed 101 times

1

first I wanted to say that I have been researching for this here in the forum and I found some similar questions, but no answer worked here.

Next, I have a php file on the server that connects to the database, makes a query and returns in json format the data I need:

<?php
header('Access-Control-Allow-Origin:','*');
header('Content-Type:application/json;charset=UTF-8');

error_reporting(E_ALL & ~ E_NOTICE);// para nao mostrar undefined variable
require("config.php");

$usuario = $_POST['usuario'];
$senha = $_POST['senha'];

$sql = $pdo->prepare("SELECT * FROM login WHERE usuario = :usuario AND senha = :senha");

$sql->bindValue(":usuario",$usuario,PDO::PARAM_STR);
$sql->bindValue(":senha",$senha,PDO::PARAM_STR);
$sql->execute();


$ln = $sql->fetchAll();
$n = $sql->rowCount();

if ($sql) {
    if ($n>0){
       //$retorno['status'] = "s"; 
       $retorno['dados'] = $ln;
   echo $_GET['callback'] . '('.json_encode($retorno).')';
       //echo json_encode($retorno);
    }else{
        //$retorno['status'] = "n";
        echo $_GET['callback'] . '('.json_encode($retorno).')';
        //echo (json_encode($retorno));
    }

}

However, when I receive it using ajax (from an external source), only the 'status' comes, and the 'return' comes as 'Undefined', and so I cannot get the correct result to do the operation.

Follow the javascript:

$(function () {

function onAppReady() {
    if (navigator.splashscreen &&     navigator.splashscreen.hide) { // Cordova API detected
        navigator.splashscreen.hide();
    }
}
$('form[name=form-login]').submit( function(){  
    $.ajax({
        type: 'POST',
        crossDomain:true,
        url: 'http://www.minhaurl.com.br/api/meuphp.php?callback=?',
        dataType:'jsonp',
        contentType  : "application/json",
        data: $(this).serialize() // pega os dados do form

    }).done(function(data){

            console.log(data);


            if (data.status == "s"){
               //faz a ação desejada

            }
            else if (data.status == "n"){
                // sempre vem status:n, pois não vem dados para fazer a operação
                alert('Credenciais Inválidas');
            }
            else {
                alert('...');
            }
        })
    .fail(function(data, textStatus, errorThrown){
         alert('falhou');  
         console.log(data);    
        });
   return false; 
});

I mean, I can’t communicate with the server through an external source. Any help? Thanks.

1 answer

0


UPDATE 23/05/2016

Good morning your informed return is an application/json but your return is a script remove the header header('Content-Type:application/json;charset=UTF-8'); in your PHP and in your ajax where you are dataType:'jsonp'place dataType:'script' this will work

END

If it is returning this is probably encoding problem. Try to give a utf8_encode() or utf8_decode before the json_encode()

But as it is array try to see in the PDO to startar the connection with the SET_NAMES as below.

*Obs: If it doesn’t work check in Notepad++ if your file is encoding in utf-8

<?php
header('Access-Control-Allow-Origin: *');
//header('Content-Type:application/json;charset=UTF-8');

error_reporting(E_ALL & ~ E_NOTICE);// para nao mostrar undefined variable
require("config.php");

$usuario = $_POST['usuario'];
$senha = $_POST['senha'];
$pdo->exec("SET NAMES utf8"); //aqui eu mudo para UTF-8
$sql = $pdo->prepare("SELECT * FROM login WHERE usuario = :usuario AND senha = :senha");

$sql->bindValue(":usuario",$usuario,PDO::PARAM_STR);
$sql->bindValue(":senha",$senha,PDO::PARAM_STR);
$sql->execute();


$ln = $sql->fetchAll();
$n = $sql->rowCount();

if ($sql) {
    if ($n>0){
       //$retorno['status'] = "s"; 
       $retorno['dados'] = $ln;
   echo $_GET['callback'] . '('.json_encode($retorno).')';
       //echo json_encode($retorno);
    }else{
        //$retorno['status'] = "n";
        echo $_GET['callback'] . '('.json_encode($retorno).')';
        //echo (json_encode($retorno));
    }

}
  • Hi, I did this what you said, but continue with the mistake.

  • I know, I’m correcting the answer...

  • 1

    Hiago only has an error that has not noticed header('Access-Control-Allow-Origin:','*');, the correct is header('Access-Control-Allow-Origin: *'); updates ae :)

  • opa, true... but the problem is not of CORS is about an expected result incorrectly. It expects a JSON and returns a script

  • But still I updated thank you.

Browser other questions tagged

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