How to connect restful Web Services + phone gap. please give and sample demo.
Try this sample
$.ajax({
url: Your_webservice_url,
type: "GET",
data: {
ModifiedSince: modifiedSince
},
dataType: "json",
success: function(data) {
console.log("The server returned " + data.length);
//Play with the received json data.
},
error: function(model, response) {
alert("Web service error: " + response.responseText);
}
});
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});
Related
I am working on an asp.net C# Web API project. I am posting data from a client using jQuery AJAX. The code is given below. I have tried two types of AJAX calls as shown below. Whether the API succeeds or not, the code under either success or error is never reached in the AJAX.
Asp.Net Web API Code:
[HttpPost]
[Route("SendCustomerDetails")]
public async Task<IHttpActionResult> SendCustomerDetails([FromBody] String jsonData)
{
//Code to process json
//...
//...
resp = await client.PostAsJsonAsync("customer/newcustomer", jObject);
if (resp.IsSuccessStatusCode)
{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
else{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
}
Jquery AJAX code1:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json"
}).done(function (data) {
alert("Success: " + data);
$('#value1').text(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("failure: " + jqXHR.responseText || textStatus);
$('#value1').text(jqXHR.responseText || textStatus);
});
Jquery AJAX code2:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json",
success: function(data) {
alert("Success: " + data);
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});
fix the action
[HttpPost]
[Route("~/SendCustomerDetails")]
public IActionResult SendCustomerDetails(JObject model)
{
return Ok(" It is Success");
}
try this code
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
data: { model:jsonData},
success: function(data) {
alert("Success: " + JSON.stringify(data));
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});
(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem
I am Using visual studio 2015 to build android application using cordova. It works fine in the emulator. but when i am releasing it ajax request is failing where as same thing works on emulator.no error is seen in log but only the ajax error.
var url = 'http://oployeelabs.net/demo/demo_doctorola/doctorola-server/index.php/doctor_panel_api/validation_modified/format/json';
load();
$.ajax({
url: url,
data: { cell_no: phone, pass: pass },
method: 'POST',
dataType: 'json',
success: function (data) {
alert();
if (data == "false")
{
alert("Wrong password");
}
else
{
localStorage.doctorid = data[0].id;
localStorage.userinfo = JSON.stringify(data);
$.ajax({
url: "http://oployeelabs.net/demo/demo_doctorola/doctorola-server/index.php/api/information/meta-info/location/id/"+data[0].id+"/username/9791a47fef07649b1c3e70749e898153/password/2d593e25d0560b19fd84704f0bd24049/format/json",
method: 'GET',
dataType: 'json',
success: function (dt) {
localStorage.Chamberinfo = JSON.stringify(dt);
mainView.router.loadPage({ url: 'menu.html', ignoreCache: true, reload: true })
$('.toolbar').removeClass('hide');
}
});
}
//if (data === "ok") {
// $(".confirm_appointment").remove();
// var anc = "<a id='confirm_appointment' class='confirm_appointment' style='opacity: 0;' href='confirm.html' data-context='{\"slot_id\": \"" + slot_id + "\",\"slot_date\": \"" + slot_date + "\", \"email\": \"contact#john.doe\"}'>profile</a>";
// $(document).find('.page_content').append(anc);
// $(".confirm_appointment")[0].click();
//}
//else {
// myApp.hidePreloader();
// myApp.alert("", "Sorry, this slot has been booked. Please try with another slot.");
//}
},
error: function (xhr, status, exception) {
alert(xhr.responseText+" "+status+" "+ exception);
console.log("Error: " + xhr.responseText + " - " + exception);
},
complete: function () {
myApp.hidePreloader();
unload();
}
});
Strangely it worked after i uninstalled whitelist plugin and installed it again. i dont know why but i think its a bug of cordova.
I got 'bad request" message on the below Rest API Ajax call, When I tested on Developer console it return data successfully.
var _url = auth.get("instance_url") +
"/services/data/v28.0/query/?q=SELECT Id, Name FROM Account WHERE Website LIKE '%gmail.com%' ";
$.ajax({
url: _url,
cache: false,
async: false,
type: 'GET',
contentType: 'application/json',
headers: {
'Authorization': 'OAuth ' + auth.getAccessToken()
},
success: function (data) {
console.log("accounts: " + JSON.stringify(data));
result = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + +errorThrown);
}
});
You need to URLEncode the query parameter, spaces are not valid in a query string, e.g.
var _url = auth.get("instance_url") + "/services/data/v28.0/query?q=" + encodeURIComponent("select id,name from account");
I have simple question to display data on html page. Following code displays array of json data on screen. but, I want to display it by each element such as "url", "img_url" and so on.
could you please let me know who to do it ?
ajax code
var dataString = 'url=' + pathname + '&img_name=' + img_name + "&tag=" + tag;
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
//handleError();
alert("error");
} else {
var data = xhr.responseText;
$('#tt').html("<div id='message'></div>");
$('#message').html(data);
}
}
});
json return
{"cid":"14","url":"http:\/\/localhost\/","img_url":"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg","img_name":"mat_173317134c.jpg","html":"<div id=\"hotspot-19\" class=\"hs-wrap hs-loading\">\r\n<img src=\"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg\">\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"95\" data-y=\"64\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nasdf\r\n<\/div>\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"168\" data-y=\"53\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nrere\r\n<\/div>\r\n<\/div>\r\n","jscript":""}
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
success: function (data) {
for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}
}
});
I hope this is what you need.