user3541436
user3541436

Reputation: 95

AJAX success function not executing

I'm trying to create a simple AJAX call for testing, but have encountered a problem. I have nested in my AJAX call a success function which should pop an alert message but it doesn't. Checking firebug, the POST is successful and responds with "A20" (without quotations). Is there something wrong in my code?

index.php (view)

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="init.js"></script>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>

<button id="your_button">Push me</button>

</body>
</html>

init.js

$(function() {
$('#your_button').bind("click", function() {

var json_data = {"category": "A", "size": "20"};

$.ajax({
    url: "posted.php",
    dataType: "json",
    type: "POST",
    cache: false,
    data: {"data": json_data},
    success: function (data) {
        if (!data.error) {
            alert('k');
        } else {
            alert('error!');
        }
    }
});
});
});

posted.php

$category = $_POST['data']['category'];
$tsize = $_POST['data']['size'];
echo ($category);
echo ($size);

Upvotes: 2

Views: 4233

Answers (4)

Chetan Gawai
Chetan Gawai

Reputation: 2401

Try this -

$(function() {
$('#your_button').bind("click", function() {

var json_data = {"category": "A", "size": "20"};

$.ajax({
    url: "posted.php",
    dataType: "json",
    type: "POST",
    cache: false,
    data: json_data,
    success: function (data) {
        if (!data.error) {
            alert('k');
        } else {
            alert('error!');
        }
    }
});
});
});

Posted.php

  $category = $_POST['category'];
$tsize = $_POST['size'];
//echo ($category);
//echo ($tsize);
echo json_encode($_POST);

Your want json data but you were not echoing json data

Upvotes: 1

shashank
shashank

Reputation: 566

First you are using two jquery libraries, remove any one of them.

Second replace data: {"data": json_data}, with data: json_data,.

Third on posted.php use $category = $_POST['category'] and $tsize = $_POST['size'];.

Hope it will help you.

Upvotes: 1

Abhas Tandon
Abhas Tandon

Reputation: 1889

You need to set proper headers in your PHP and send a valid json response from PHP file. Add these lines to your PHP

  header('Access-Control-Allow-Origin: *');
  header('Content-type: application/json');

and echo back some valid json from it like echo '{"auth":"true","error":"false"}';

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

this is not right:

data: {"data": json_data}

do like this:

data: {data: json_data}

Upvotes: 1

Related Questions