Jian Short
Jian Short

Reputation: 135

Ajax post failed or something else

I am trying to get a get post value after an AJAX call. First I will show you my AJAX codes:

$('#color').change(function(){

    var color = $('#color').find(':selected').text();
    var id = {$product_details.id};

    //alert({$product_details.id});
    //alert(color+id);

    var url = 'http://myurl';

    $.ajax({

        url: url,
        type: 'post',
        data: {'color='+color+'&id='+id},
        success: function(msg){
            alert(msg);
        }
    });

});

I have tested that I had posted to the correct url (not one above). I have tested the variables by alert. This is my PHP file:

echo $_POST['color'];

if(isset( $_POST['color'] )){
    echo 'hi';
    //get_unit();
}

But I am unable to echo the $_POST['color']. What could be the problem?

Upvotes: 0

Views: 50

Answers (4)

Felix
Felix

Reputation: 38102

Try to change:

data: {'color='+color+'&id='+id},

to:

data: {'color':color, 'id':id}

since you've used POST method.

Upvotes: 2

Jai
Jai

Reputation: 74738

You can try with two changes:

change this:

var id = {$product_details.id};

to this:

var id = $product_details.id;

because you have a wrong syntax of an object this should either be with {key:value} pairs or you should do the change as above.

and you should post your data this way:

data: {'color':color, 'id':id},

Upvotes: 1

Cyrus Great
Cyrus Great

Reputation: 36

          $.ajax({
            url:Url,
            dataType: 'json',
            contentType: "application/json",
            type: "POST",
            data: JSON.stringify({ 'color': color1 ,'Id':id1  }),
            success: function (msg) {
             alert(msg);
                }

Try to use this format.color1 and id1 are local variable that you stored your data on them.

Upvotes: 1

Girish
Girish

Reputation: 12117

NO need {} when you pass post data in query string, {} will be used when you send data in object, please try this way

data: 'color='+color+'&id='+id

// OR

 data : {"color" : color, 'id' : id}

//

<script>
    $('#color').change(function(){

        var color = $('#color').find(':selected').text();
        var id = {$product_details.id};

        //alert({$product_details.id});
        //alert(color+id);

        var url = 'http://myurl';

        $.ajax({

            url: url,
            type: 'post',
            data: 'color='+color+'&id='+id,
            // OR
            // data : {"color" : color, 'id' : id}
            success: function(msg){
                alert(msg);
            }
        });

    });
</script>

Upvotes: 1

Related Questions