Ajax Call with Contenttype: 'Application/JSON' Not Working

Ajax call with contentType: 'application/json' not working

When using contentType: 'application/json' you will not be able to rely on $_POST being populated. $_POST is only populated for form-encoded content types.

As such, you need to read your data from PHP raw input like this:

$input = file_get_contents('php://input');
$object = json_decode($input);

Of course if you want to send application/json you should actually send JSON, which you are not doing. You either need to build the object serialization to JSON directly, or you need to do something like this - Convert form data to JavaScript object with jQuery - to serialize the object from the form.

Honestly in your case, since you are dealing with form data, I don't quite think the use case for using application/json is there.

How to set content type as application/json using Ajax call?

Welcome to Stack Overflow.

There's multiple problem with your call. You are using FORM submit and AJAX call also for same purpose. Use only one of them. Using AJAX Call you will be able to maintain Single Page Application, so will my solution only focus on that.

Since we are using AJAX call thus there's no need for form and form action as these will be taken care by AJAX url.

HTML and JS:

<html>
<head>
</head>
<body>
<h1>Enter the transaction details below:</h1>
Enter the amount:<br>
<input type="number" name="amtvalue" id="amtvalue" value="0"/><br>

<p onClick="validateForm();">Submit</p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function validateForm() {
console.log("in validateForm");

var amt = document.getElementById("amtvalue").value;

console.log(amt);
if (isNaN(amt) || amt < 0) {
alert("Amount is not valid");
return false;
}

console.log("before ajax call");

$.ajax({
url: "/govtcontract/set",
method: "POST",
headers: {
'Content-Type': 'application/json'
},
data: {
value: amt
},
success: function(got) {
console.log("shortened url: " + got);
}
});
}
</script>
</html>

Also on Server app.js add following also to fetch any kind of data in req.body

  // configure the app to use bodyParser() to extract body from request.
// parse urlencoded types to JSON
app.use(bodyParser.urlencoded({
extended: true
}));

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));

// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));

For starters guide to Web Application using NodeJS and HTML check out this repository, this illustrate Single Page Application and difference between multiple page and single page.

Content Type Fails to send to Server through AJAX Post

Use dataType: 'json' to send json data. You are not sending json data on server. you need to change dataType to send json data

Try use this ajax code, no need to stringify json object if its already correct object. i have tested it at my side hopefully it will help you.

$.ajax({
type:"POST",
url: "YOUR PATH TO FILE OR METHOD",
data:{
order:'555'
},
dataType: 'json',
success: function(data){
if(data['success']=='true'){
echo 'success';
}else{
if(data['success']=='false'){
echo 'not success';
}
}
},
error: function(xhr, status, error) {
console.log(status);
console.log(error);
}
});

AJAX call with Content Type Application/json not retrieving data from PHP

Finally Solved the problem,
I completely teared down the PHP cUrl function, in a way that only basic functionality was left. Now the JSON data is returned to the AJAX call. What I noticed was that there were some warnings when the cUrl function was executed (like undefined variables) but the JSON data was still returned in the PHP function. So, primary you should think that warnings should be no problem. After resolve the warning coming from the cUrl function, the JSON data as returned properly to the AJAX call. In other words, the Ajax call will not return data when a PHP warning is occurring.

Jquery - How to make $.post() use contentType=application/json?

I think you may have to

1.Modify the source to make $.post always use JSON data type as it really is just a shortcut for a pre configured $.ajax call

Or

2.Define your own utility function that is a shortcut for the $.ajax configuration you want to use

Or

3.You could overwrite the $.post function with your own implementation via monkey patching.

The JSON datatype in your example refers to the datatype returned from the server and not the format sent to the server.

Ajax call to web method not working with content type set to ` application/json; charset=utf-8`

There's nothing wrong with contentType you've set. It's correct:

 contentType: "application/json; charset=utf-8",

First of all make sure you've valid handler mappings in web.config as shown below:

Edit:

 <system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
</system.web>

For more info, check out this link

Apart from that you must surround data being passed with single/double quotes like below:

 data: "{ 'values':" + JSON.stringify(myarray) + "}"

Or jQuery will automatically URL encode it. For more info check this URL



Related Topics



Leave a reply



Submit