Ajax request - xml/json - ajax

Studying for an exam and came across the following practice question.
You develop a web application by using jQuery. You develop the following jQuery code:
$(document).ready(function () {
$('#submit').click(function () {
$.ajax({
//INSERT CODE
data: $('#myForm').serialize(),
success: function (result) {
$('#result').text(result.message);
}
});
})
})
The web application exposes a RESTful web api that has an endpoint of product/create. You need to create a new product by using AJAX.
Which code segment should you insert at line 04?
//Option A:
type: "POST",
dataType: "xml",
contentType: "application/x-www-urlencoded; charset=UTF-8",
url: ".product/create",
//OPTION B:
type: "POST",
dataType: "json",
url: ".product/create",
Could someone explain why option B is correct?
I understand that it should be a post request since a new product is being created. Datatype could be either json or xml. Content-type is optional. Is it because result.message can only work when a json is passed in?

For the datatype:"xml", The contenttype is not valid in Option A. The valid options for XMLs are: text/xml, application/xml.
But, Option B has valid entries.
The corrected option A is below,
//Option A:
type: "POST",
dataType: "xml",
contentType: "application/xml; charset=UTF-8",
url: ".product/create",

Related

Correct spelling in ajax POST

I have two verions of code I believe should do the same thing, but the first one works and other one doesn't (Post vars: agenti, week_, team_). I have searched for few examples of how to do it the other way and I am sure my example is similar.
What do I do wrong?
First:
$.post("index.html",
{
agenti: getItems(),
week_: week_array,
team_: team
},
function(data,status){
if (status = 'Success'){
alert('Aktuální řazení operátorů bylo úspěšně uloženo.');
} else {
alert('Aktuální řazení operátorů se nepodařilo uložit.\nKontaktujte prosím správce aplikace.');
}
Second:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "index.html",
data: JSON.stringify({agenti: getItems(), week_: week_array, team_: team}),
success: function (msg)
{
alert('Aktuální řazení operátorů bylo úspěšně uloženo.')
},
error: function (msg)
{
alert('Aktuální řazení operátorů se nepodařilo uložit.\nKontaktujte prosím správce aplikace.')
}
});
I want to do the second one because I need to specify content type and i couldn't figure how to do it in the first way.
Thanks you!
edit: I use IE; this code will be used only in IE.
so the first thing is that, no need to use JSON.stringify function, as the data accepts JSON objects, as well the string represented like a url (test1=1&test2=2...). So to use it like the following is ok.
data: {agenti: getItems(), week_: week_array, team_: team},
Also when you are using contentType: 'application/json' the GLOBAL $_POST variable is not being populated as it is being populated only for form-urlencoded data which is default value for contentType option, here you go with data from jQuery reference`
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
In order you like to use application/json, you can retrieve that information in PHP side using php input like this following. file_get_contents('php://input');
---Working Example---
Javascript:
$.ajax({
type: "POST",
// contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost",
data: {agenti: 'test1', week_: 'test2', team_: 'test3'},
success: function(msg) {},
error: function(msg) {}
});
PHP:
// Retrieve the input
var_dump(file_get_contents('php://input'));
// Use $_POST var
echo json_encode($_POST);

working XML feed , blogger is an exception?

This is a working fiddle. http://jsfiddle.net/bpBtC/1/
But this http://jsfiddle.net/bpBtC/131/ doesn't work with the same method?
(All the other websites with XML feeds also fail using the same method, why?)
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://www.blogger.com/feeds/2399953/posts/default",
dataType: "xml",
success: xmlParser,
dataType: 'jsonp'
});
});
function xmlParser(xml) {
$(xml).find("entry").each(function () {
$(".entirecont").append($(this).find('title').text());
});
}
You are setting dataType twice.
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://www.blogger.com/feeds/2399953/posts/default",
dataType: "xml",
success: xmlParser,
dataType: 'jsonp' //<-- this is what actually used.
});
Remove the second dataType and your code will fail.http://jsfiddle.net/bpBtC/130/
The first fiddle works because it is using JSONP (not XML) as the return data type and a method of circumventing the cross-site scripting restrictions. Familiarize yourself with JSONP and how it works.
The second feed does NOT return JSONP, it returns XML and so it can't work. Also you can't have two datatype-parameters on same ajax-call.

wcf service json 400 Bad Request

I get a 400 Bad Request error when I try to call WCF service from client side using ajax. Following is my code,
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:58055/Service1.svc/GetUser",
crossDomain: true,
data: '{"Id": "3"}',
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
alert(msg.GetUserResult[0]);
console.log("success " + msg);
},
error: function (msg) {//On Successfull service call
console.log(msg);
}
});
Any insights would be really helpfull...
The first thing you should try is hit the URL using fiddler(so that you could post your data too) and see if you get the same error.
Are you making a cross domain request. From the example it looks like you are not. Could you remove
crossDomain: true,
line and try the jquery again.
There are other options also which unnecessay like processdata. Suggest you to use the following code and see if it works or not.
$.ajax({
type: "POST",
// the url to the service -
url: "url",
// the format that the data should be in when
// it is returned
contentType: "json",
data: '{"Id": "3"}',
// the function that executes when the server
// responds to this ajax request successfully
success: function(data) {
// put the JSON response in the employees table
}
According to the ajax api documentation the default content type is 'application/x-www-form-urlencoded'. When sending JSON, the content type should be 'application/json; charset=utf-8' except that WCF does not like that. I got the same error messages and when I removed the content type I stopped getting this error. By the way, I noticed that you set crossDomain to true, this other question is relevant to that option.

In MVC calling webservice with ajax call not working give error code 404?

In my .net framework with MVC calling webmethod like. webservice1.asmx/helloWorld
with Ajax give error 404 not found..In my another server same code working. Is there
anything missing to call ?? and physical path give me same webserive and webmthod in my .net project.. please help me ..
EDIT
code to call the web service
$.ajax({
type: "POST",
url: "/WebServices/WebService1.asmx/HelloWorld",
data:"{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(msg) {
var data = msg.d;
},
error: function(msg) {
alert(msg);
}
});
I suspect that you have hardcoded the url to the web service in your javascript call instead of using an url helper to generate it. So try like this:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "#Url.Content("~/WebServices/WebService1.asmx/HelloWorld")",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(msg) {
var data = msg.d;
},
error: function(msg) {
alert(msg);
}
});
</script>
Notice how the url to the web service is no longer /WebServices/... but it is generated with an url helper. So if for example you deploy your application in a virtual directory in IIS the helper will take into account this virtual directory.

$.ajax is not working

In my web page there is a textbox to get the scanned barcode value. Once we scan the barcode it has to get details from the database. I am creating the change event for the textbox.
Problem: $.ajax is not working.
Code:
var target = $('#txtBarcode'), val = target.val();
target.change(monitor());
function monitor() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "HomePage.aspx/SearchProduct",
dataType: "json",
success: function(data) {
alert("Success!!!");
}
});
}
You are trying to pass 'monitor' to the change method but you're actually calling it. It should look like this (no parens)
var target = $('#txtBarcode'), val = target.val();
target.change(monitor);
function monitor() {
You can always declare it inline too:
var target = $('#txtBarcode'), val = target.val();
target.change(
function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "HomePage.aspx/SearchProduct",
dataType: "json",
success: function(data) {
alert("Success!!!");
}
});
});
Add an error handler.
Make sure your relative URL is right.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "HomePage.aspx/SearchProduct",
dataType: "json",
success: function(data) {
alert("Success!!!");
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
// ...
}
});
EDIT: Dan is right about your change handler.
You can copy some answers posted here, and at least one of will likely to work, but you won't get the intimate knowledge of why. Here's an additional way:
Since you use asp.net, put the break point in the first line of HomePage.aspx/SearchProduct. This ensure that the request goes to the right URL on the server.
Step all the way through this method to make sure there's no exception that gets thrown.
Use FireFox and install Firebug (even if you target IE and have no intention to make it run on FF). You can inspect the http response.
Add an error handler in addition to the success handler.

Resources