Javascript:Send JSON Object with Ajax

Javascript : Send JSON Object with Ajax?

With jQuery:

$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });

Without jQuery:

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));

sending JSON object along with file using FormData in ajax call and accessing the json object in PHP

Firstly, note that you can only append binary data or a string through the FormData.append() method. Providing an object as you are means that toString() will be called on it, so the value will actually become "[object Object]".

To fix this you'll need to manually JSON.stringify the object before you append() it:

let obj = {
'label1':'value1'
};
form_data.append('file', file_data);
form_data.append('json', JSON.stringify(obj));

Then in your PHP you can deserialise the JSON using json_decode().

However, it would be much simpler to just append the values to the FormData object directly. That way you don't need to manually serialize/deserialize anything:

form_data.append('file', file_data);
form_data.append('label1', 'value1');
form_data.append('foo', 'bar');

Then in your PHP:

var label = $_POST['label'];
var foo = $_POST['foo'];

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>

AJAX Post request - sending json object to node.js server

You say newWorkLog is an object so you need to convert it to json to send it in your request.

$.ajax({
type:"POST",
dataType:"json",
contentType: "application/json",
data:JSON.stringify(newWorkLog),
url:"/add",
})
.done(function(response){
console.log("Response of update: ",response)
})
.fail(function(xhr, textStatus, errorThrown){
console.log("ERROR: ",xhr.responseText)
return xhr.responseText;
});


Related Topics



Leave a reply



Submit