0

im just writing some code in php and jquery but i have little problem that i can´t solve yet.

I have 2 pieces of code, Im pretty sure that the jquery post method is fine (im not using a form, just 2 inputs inside a div) when the input values are set and sent to the php I do a database request for finding a match with the stored data.

the problem is i want a variable "return" for a future "if" comparison, i tried to do it with json_encode but it always says undefined in the js alert(). Even if i use the data.answer like the associative arrays.

I dont know what's wrong, I hope that you can help me.

PS: when I use an echo string it works fine... but not with the associative array. If the values of the array are '1' or '2' it works but using "alert(data) and it displays {answer:1} (or 2). I also tried with stringify but it didnt work.

As I said i want the value for comparisons.

Thx a lot for your help.

Here is my code:

Js code.

$('.send').click(function(){
var id1=$('.id-usuario').val();
var clave1=$('.clave-usuario').val();


$.post('login.php',{id_usuario:id1, clave_usuario:clave1},function (data){

alert(data.answer);

});

and the php.

<?php

$id_usuario = $_POST['id_usuario'];
$clave_usuario = $_POST['clave_usuario'];

$dbconn3 = pg_connect("host= localhost port=5432 dbname=EmergenciesResponse user=postgres password=asdf");
$query1=pg_query("select id_usuario, clave_usuario from usuarios where id_usuario='$id_usuario' and clave_usuario='$clave_usuario'");


if(pg_num_rows($query1)==1){   
$answer[]=array(
'answer'=>1

);

   echo json_encode($answer);

}
else{ 
    $answer[]=array(
        'answer'=>2

    );

    echo json_encode($answer);}
pg_close($dbconn3);

?>

3 Answers 3

1

Hello Please add bellow line in top of your php file

header('Content-Type: application/json');

Sign up to request clarification or add additional context in comments.

Comments

1

You have to parse string to json formate using parseJson

Try this

$.post('login.php',{id_usuario:id1, clave_usuario:clave1},function (data){
     var parseData = $.parseJson(data);  //parse string to json format.
     alert(parseData.answer);

});

Comments

1

Set the datatype for the response parsing with,

$.post('login.php',{id_usuario:id1, clave_usuario:clave1},function (data){

    alert(data.answer);

 }, "json")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.