John Brunner
John Brunner

Reputation: 2872

Send multiple variables with PHP to AJAX over JSON doesnt work

I have a problem. I want to send 3-4 variables from a PHP File to my AJAX request (over json)... and I'm sure that my code is right, it doesn't work. It is doing nothing. If I'm doing just a normal "echo" everything works finde, but json is not working?

Here is my JS-code:

$.ajax({
       type: "POST",
       url: "test.php",
       data: "varA=" + varA + "&varB=" + varB,
       dataType: json,
       cache: false,
       success: function(data1){

       alert(data1.b);

       if (data1.a == "success"){
       alert("OK");

       location.href = "index.html";
       }

       else{
       alert("Not OK");
       }

       }
       });

And here is my PHP-code:

...
    $qry="SELECT * FROM database1 WHERE varA='".$_POST['varA']."' AND varB='".$_POST['varB']."'";
$result=mysql_query($qry);

if($result) {
    if(mysql_num_rows($result) == 1) {
        $test = mysql_fetch_assoc($result);
        echo json_encode(array('a' => 'success', 'b' => $test['database_entry']));
...

I don't have a clue why this AJAX code would not be fired! Hope you could help me, THANKS!

Upvotes: 0

Views: 2442

Answers (3)

swapnilsarwe
swapnilsarwe

Reputation: 1300

You are maiking a mistake by writing

dataType: json,

here json is supposed to be in a string

dataType: 'json',

In your code it is trying to search for the variable json which is not available and hence undefined, and hence no ajax call is made

Upvotes: 1

Rohan Prabhu
Rohan Prabhu

Reputation: 7302

Send your data as a JSON object, not a self-generated query string:

data:  {"varA":  varA, "varB": varB},
dataType: json,
cache: false,

Upvotes: 2

Rodik
Rodik

Reputation: 4092

The data you are sending to your ajax call is a string, wheras it should be an object or an array.

data: "varA=" + varA + "&varB=" + varB,

should be

data: {"varA":varA,"varB":varB},

Upvotes: 1

Related Questions