0

So I am trying to use something like the below code to send post data but I need to send with json as the format.

$.post(baseUrl + 'main', {
    meta: '1',
    metaOut: '1',
    hashcode: hashCode,
    url: inputHost
}

I know about the $.ajax way but there are many functions already using the $.post so I'd have to convert all.

    $.ajax({
    type: "POST",
    crossDomain: true,
    headers: {"Content-Type": "application/x-www-form-urlencoded",},
    dataType: "json",
    url: baseUrl+'get-image',
    data: {_token: _ourtoken, site: inputHost},
    success: function (result) {
        console.log(result.messages.success);
    },
    error: function (result) {
        console.log(result.responseText);
    }
});

Looking for a way to either make all posts inside this .js file send with json or for each $.post, make it send with json format.

AGradePHP
  • 63
  • 5
  • `dataType` refers to the format that AJAX will receive as the response, not the format it will use to send the data. Meanwhile, you're explicitly setting the `Content-Type` header to `form-urlencoded` - why set that if you want to send JSON? Consult the Javascript portion of [this answer](https://stackoverflow.com/a/8517361/4205384) for an example. And it's also always a good first step to read the [documentation](https://api.jquery.com/jquery.ajax/) of the method you're trying to use. – El_Vanja Jan 14 '21 at 12:27
  • @El_Vanja Okay I will read it thank you. I wanted to receive data type as json in php yes – AGradePHP Jan 14 '21 at 12:30

1 Answers1

0

Assuming you're using the latest jQuery framework, you could define a default by using the jQuery's ajaxSetup function like so:

$.ajaxSetup({
  dataType: "json"
});

See documentation for further information, do also note that the documentation doesn't recommend doing it. https://api.jquery.com/jQuery.ajaxSetup/

Keep in mind that $.post() is the short method equivalent of using the $.ajax({type:"POST"}).

Werzaire
  • 78
  • 3