Send JSON Data with Jquery

Send JSON data with jQuery

Because you haven't specified neither request content type, nor correct JSON request. Here's the correct way to send a JSON request:

var arr = { City: 'Moscow', Age: 25 };
$.ajax({
url: 'Ajax.ashx',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});

Things to notice:

  • Usage of the JSON.stringify method to convert a javascript object into a JSON string which is native and built-into modern browsers. If you want to support older browsers you might need to include json2.js
  • Specifying the request content type using the contentType property in order to indicate to the server the intent of sending a JSON request
  • The dataType: 'json' property is used for the response type you expect from the server. jQuery is intelligent enough to guess it from the server Content-Type response header. So if you have a web server which respects more or less the HTTP protocol and responds with Content-Type: application/json to your request jQuery will automatically parse the response into a javascript object into the success callback so that you don't need to specify the dataType property.

Things to be careful about:

  • What you call arr is not an array. It is a javascript object with properties (City and Age). Arrays are denoted with [] in javascript. For example [{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }] is an array of 2 objects.

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Create a model

public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}

Controllers Like Below

    public ActionResult PersonTest()
{
return View();
}

[HttpPost]
public ActionResult PersonSubmit(Vh.Web.Models.Person person)
{
System.Threading.Thread.Sleep(2000); /*simulating slow connection*/

/*Do something with object person*/

return Json(new {msg="Successfully added "+person.Name });
}

Javascript

<script type="text/javascript">
function send() {
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}

$('#target').html('sending..');

$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
}
</script>

How do I use jQuery.post to send JSON data to a php script?

Using jQuery you can send data to your end point using the POST protocol. Example below

$.ajax({
url : 'taskmanager.php',
type : 'POST',
data : JSON.stringify(dataStore),
success : function(res) {
// Successfully sent data.
console.log(res);
},
error: function(err) {
// Unable to send data.
console.log(err);
})
});

You may also use the $.post method, its just a preference. $.ajax provides with some extra flexibility, in case you maybe want to update your protocol to GET instead of post or numerous other instances...

More info on this here: http://forum.jquery.com/topic/what-should-i-use-post-vs-ajax

Send form data with jquery ajax json

here is a simple one

here is my test.php for testing only

<?php

// this is just a test
//send back to the ajax request the request

echo json_encode($_POST);

here is my index.html

<!DOCTYPE html>
<html>

<head>

</head>
<body>

<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});

</script>
</body>
</html>

Both file are place in the same directory

jQuery posting JSON

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type header:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting JSON to webservice

How do I POST JSON data using jQuery AJAX

You had to send the token as data

const $output = $("#logs");
const process = response => $output.html(
response.logs.map(log => `<hr/><dl>${
Object.entries(log).map(([key,val]) => `<dt>${key}</dt><dd>${val}</dd>`).join("")
}</dl>`).join(""));

$.ajax({
type: "POST",
url: "https://fetch1.hipposhq.com/hipposapilogstatus",
dataType: 'json',
data: {
"token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO"
},
success: process,
error: function(request, status, error) {
console.log(request.responseText);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="logs"><div>

POST Ajax Call not send JSON Content and GET Unsupported Media Type

Try to use JSON.stringify() on data before sending Ajax.

JSON.stringify(jsonData);

Refer this for more : https://stackoverflow.com/a/3987156/6572971



Related Topics



Leave a reply



Submit