AJAX value sending error

Hi I have problems with the script below. The problem I think lies on data that need to be sent to php via AJAX.

jQuery

$('.send').live("click", function(){

    $.ajax({

        url:'foobar.php',
        type:'post',
        data: 'id=' + $(this).attr('id'),
        dataType:'json',
        contentType: 'application/json; charset=utf-8',
        success: function(data) {

            switch (data.status)
            {
                case "a":

                    alert(data.text);

                    break;

                case "b":

                    alert(data.text);

                    break;

                }
            },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

            alert ("error: "+textStatus);

            }
        })
    }

and, PHP

$id = $_REQUEST['id'];

switch ($id) {

    case "foo":

        $data["status"] = "a";
        $data["text"] = "foo-foo";
        echo json_encode($data);

        break;

    case "bar":

        $data["status"] = "b";
        $data["text"] = "bar-bar";
        echo json_encode($data);

        break;

    }

but, if I do this

//data: 'id=' + $(this).attr('id'),

and change this

$id = 'foo';

the script work just fine. What I need to do to make both script above can work? Thanks in advance.

Answers


I will put my comment as an answer.

Apart from using a deprecated jQuery API, what others didn't point out is the following:

What you are doing in the below line:

contentType: 'application/json; charset=utf-8',

is that you are promising the server that the HTTP entity will be a JSON-string, which is not the case. It is actually the usual percentile-encoded string. (a=b&c=d&e=f).

If you remove that line, the browser sends a default value Content-Type as application/x-www-url-form-encoded. That would trigger PHP to parse the HTTP entity as such and give you as the $_REQUEST array properly populated.


change this

data: 'id=' + $(this).attr('id'),

to

data: {id :  $(this).attr('id')},

also use on here, live is deprecated

$('.send').on("click", function(){

Need Your Help

error reading MIDI files into program

standards midi file-type

I have a midi file which was generated using MuseScore. It plays well in Windows Media Player, but causes my midi reading program to crash. I've been using the following links to help me: MIDI

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.