Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, I need some help. I have been given a assignment where I need to submit j

ID: 3854882 • Letter: H

Question

Hello, I need some help. I have been given a assignment where I need to submit json data to the server by using a post ajax function, and getting a json response back. When I run this post it will go through but the content type is application/x-www-form-urlencoded; charset=UTF-8. What I want the content type to be is application/json and I've tried stating it in the ajax function as contentType: "application/json" but it will not work. Is there a way where i can get the contentType to not default into application/x-www-form-urlencoded? I need to do this without using PHP. The code is below

--------------------------------------------------------------------------------------------

<!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery.post demo</title>

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

</head>

<body>

<form action="someURL" id="searchForm" >

<textarea name="s" rows="5" cols="25"></textarea>

<input type="submit" value="Search">

</form>

<!-- the result of the search will be rendered inside this div -->

<div id="result"></div>

<script>

// Attach a submit handler to the form

$(document).ready( function() {

$( "#searchForm" ).submit(function() {

$.ajax({ // create an AJAX call...

type: "POST", // GET or POST

url: $(this).attr('action'), // the file to call

data: $(this).serialize(), // gets the form data

  

// update the DIV

}).then(function(data){

$("#result").empty().append(data);

});

return false; // cancel original event

});

});

</script>

</body>

</html>

Explanation / Answer

In ajax, there are actually two properties, contentType and dataType... contentType gives the data type of content which we are sending and datatype sets the type to data which we are getting.. you can take an example of following code:-


$.ajax({ dataType : "json", contentType: "application/json; charset=utf-8", data : JSON.stringify(data), success : function(result) { alert(result.success); // result is an object which is created from the returned JSON }, });

Here dataType specifies that we want data response in json format, if you want in html format you cannchange it to html.

in contentType we need to set application/json to change from default urlformencoded one ..

Hope this will help. Please try this once.. and let me know in comments if you still face the same problem.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote