Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to add to the li list but I am having some trouble with "order".

When I input "order" after the button click the alert shows it as:
"[object Object]"

It should read:
{name: somename, drink: somedrink}


How do I get the json object?

ASP.NET
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        var $orders = $('.orders');
        var $name = $('#<%= name1.ClientID %>');
        var $drink = $('#<%= drink1.ClientID %>');

        $('#<%= add_order.ClientID %>').on('click', function () {
            var order = {
                name: $name.val(),
                drink: $drink.val()
            };
            alert(order);
            $.ajax({
                type: 'POST',
                url: 'Myorder.aspx/ordered',
                data: order,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (newOrder) {
                    $orders.append(newOrder.d);
                },
                error: function () {
                    alert('Error in new order');
                }
            });
        });
    });
</script>
<h2>Coffee Orders</h2>
<ul class="orders">

</ul>
<h4>Add a Coffee Order</h4>
<p>Name:<asp:TextBox ID="name1" runat="server"></asp:TextBox></p>
<p>Drink:<asp:TextBox ID="drink1" runat="server"></asp:TextBox></p>
<asp:Button ID="add_order" runat="server" Text="Add!" />
Posted

{name: somename, drink: somedrink} IS a JavaScript object (written in JSON) so it is an object!
Try
JavaScript
alert(newOrder.d.name);
 
Share this answer
 
v2
That is because at this very moment, the data you're trying to alert to the user is just a JavaScript object. For, it is trying to convert that into a string and alert the user.

To convert into the JSON format, you can use stringify method,

Try this code,

JavaScript
// save the string in a variable
var obj = JSON.stringify({name: $name.val(),
                         drink: $drink.val()});


.. it will work for you now. :-)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900