[jquery] jquery AJAX and json format

I have a webservice that expects to receive json, like so:

{"first_name":"test","last_name":"teste","email":"[email protected]","mobile":"+44 22 2222 2222", "password":"testing"}

My ajax call in jquery:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: {
            first_name: $("#namec").val(),
            last_name: $("#surnamec").val(),
            email: $("#emailc").val(),
            mobile: $("#numberc").val(),
            password: $("#passwordc").val()
        },
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
    });

Is there any way to check the format in which my data is being sent? I'm supposedly not sending correct JSON to the server (that is the first step in validation).

Is my jquery code sending valid JSON or did I miss something?

This question is related to jquery ajax json

The answer is


You aren't actually sending JSON. You are passing an object as the data, but you need to stringify the object and pass the string instead.

Your dataType: "json" only tells jQuery that you want it to parse the returned JSON, it does not mean that jQuery will automatically stringify your request data.

Change to:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({
            first_name: $("#namec").val(),
            last_name: $("#surnamec").val(),
            email: $("#emailc").val(),
            mobile: $("#numberc").val(),
            password: $("#passwordc").val()
        }),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
});

You need to parse the string you are sending from javascript object to the JSON object

var json=$.parseJSON(data);


I never had any luck with that approach. I always do this (hope this helps):

var obj = {};

obj.first_name = $("#namec").val();
obj.last_name = $("#surnamec").val();
obj.email = $("#emailc").val();
obj.mobile = $("#numberc").val();
obj.password = $("#passwordc").val();

Then in your ajax:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(obj),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
    });

$.ajax({
   type: "POST",
   url: hb_base_url + "consumer",
   contentType: "application/json",
   dataType: "json",
   data: {
       data__value = JSON.stringify(
       {
           first_name: $("#namec").val(),
           last_name: $("#surnamec").val(),
           email: $("#emailc").val(),
           mobile: $("#numberc").val(),
           password: $("#passwordc").val()
       })
   },
   success: function(response) {
       console.log(response);
   },
   error: function(response) {
       console.log(response);
   }
});

(RU) ?? ??????? ???? ?????? ????? ???????? ??? - $_POST['data__value']; ???????? ??? ????????? ???????? first_name ?? ???????, ????? ????????:

(EN) On the server, you can get your data as - $_POST ['data__value']; For example, to get the first_name value on the server, write:

$test = json_decode( $_POST['data__value'] );
echo $test->first_name;

Currently you are sending the data as typical POST values, which look like this:

first_name=somename&last_name=somesurname

If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?