java tech
java tech

Reputation: 11

how to send json request in ajax post method

I'm trying to post json request in ajax call, but I'm not receiving any success response from the request.

Please find my below code: what I'm doing wrong here:

It hit the url and i'm getting 200 ok status but it always go error condition..

Can someone help, what i need to change to work:

I tried data: JSON.stringify({key:"value",key1: "value1"}) - but this also didn't help

<script type="text/javascript">
function JSONTest() {

 $.ajax({
    url: 'http://localhost:8080/test/toSend',
    dataType: 'json',
    type: 'post',
    contentType: 'application/json',
    data: '{key:"value",key1: "value1"}',
    processData: false,
    success: function( data, textStatus, jQxhr ){

        alert("success..." +data);
        $('#response pre').html( JSON.stringify( data ) );
    },
    error: function( jqXhr, textStatus, errorThrown ){
        console.log( errorThrown );
    }
});   

    }

</script> 

Upvotes: 1

Views: 880

Answers (2)

Brian Gerhards
Brian Gerhards

Reputation: 849

$.ajax is not hooked up as a promise! Use the below code!

function JSONTest() {
    $.ajax({
        url: 'http://localhost:8080/test/toSend',
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: '{key:"value",key1: "value1"}',
        processData: false
    }).done(function (data, textStatus, jQxhr) {
        $(this).addClass("done");
    }).fail(function (jqXhr, textStatus, errorThrown) {
        console.log("error errorThrown");
    });
};

Upvotes: 0

Mohamed Salem Lamiri
Mohamed Salem Lamiri

Reputation: 6077

To use JSON.stringify({key:"value",key1: "value1"}) you need to load this script :

JSON-js

Upvotes: 0

Related Questions