Cross-domain calling a WCF Service - javascript

I have a WCF service, this is a method which I'd to call:
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
double?[] GetPoints(string tourname);
I checked by WCF Test Client, it works fine
So I need to call this method from html page. It should work from other computer that is cross-domain.
I wrote somethig using jQuery 1-6-2.min.js:
var varType;
var varUrl;
var varData;
var varContentType;
var varDataType;
var varProcessData;
function CallService() {
alert("CallService");
$.ajax({
type : varType, //GET or POST or PUT or DELETE verb
url : varUrl, // Location of the service
data : varData, //Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, //Expected data format from server
processdata : varProcessData, //True or False
success : function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function Start() {
varType = "POST";
varUrl = "http://localhost:1592/TourService.svc/GetPoints";
varData = '{"tourname ":"customname"}';
varContentType = "application/json; charset=utf-8";
varDataType = "json";
varProcessData = true;
CallService();
}
function ServiceSucceeded(result) {
alert("ServiceSucceeded");
alert(result);
}
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + ' ' + result.statusText);
varType = null;
varUrl = null;
varData = null;
varContentType = null;
varDataType = null;
varProcessData = null;
}
However ServiceFailed function is invoked with message "Service call failed 0 error"
How to make a cross-domain calling of WCF service?(using jQuery or not)
Thanks

Basically you need to be using jSONP instead of jSON:
Using jQuery & JSONP for cross-domain AJAX with WCF services
I'll provide a summary shortly in case this link disappears.
Also see the jQuery documentation for more about how to use jSONP, jQuery & AJAX

.net framework 4 for wcf has json call back inbuilt now ,
I think jquery1.5 onwards they added the following option , crossDomain , try the below code
$.ajax({
type: "POST",
dataType: "html",
crossDomain: true,
url: "http://www.domain.com/page.aspx",
error: function() {
alert("error");
},
success: function(msg){
alert(msg );
}
});

Related

Getting a partial response from a lQuery ajax request for progress bar?

I call a php page using an ajax request, then the php page calls a python script and the python script writes percentage of work done in a txt file and of course calculates what is needed.
From my code it is only possible to acess the txt file after the ajax request is done but this doesn't make sense as it is always 100%.
How would i read data if the txt with the progress is lets say: http://domain.com/progress.txt durring the request.
$.ajax({
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', "http://domain.com/pr.txt", true);
xhr.send();
var pro_perc = xhr.responseText;;
alert(pro_perc);
move1(pro_perc);
return xhr;
},
type: "POST",
url: "http://domain.com/req.php",
data: reqdata,
cache: false,
success: function(html) {
var values = html.split('[mydata]');
var mydata = values[1];
});
Actually you can find your answer here
JQuery ajax progress via xhr
or you can use this
var interval;
$.ajax({
beforeSend: function(){
interval = setInterval(function(){
$.get("http://domain.com/pr.txt").done(function(progress){
console.log(progress)
})
},10);
},
type: "POST",
url: "http://domain.com/req.php",
data: reqdata,
cache: false,
success: function(html) {
clearInterval(interval);
var values = html.split('[mydata]');
var mydata = values[1];
}
});

How to make post request using javascript

I am trying to make a POST request in javascript. But response is not getting.
http://xecutehr.com/api/HRMSService.svc/PostAttendance?input={"Header":{"CompanyId":"MTF","LicenceKey":"MTF-4525"},"Body":{"E_Code":"01330","AttendanceDateTime":"2016-04-27T13:00:30","Mode":"I","DeviceId":"MTF1330"}}
This is the url format and this is the code I have written:
if(valid){
var values = form.serializeObject();
var e_code = values.staff_code.substring(3);
var device_id = values.staff_code;
var date_time = datetime;
var url = "http://xecutehr.com/api/HRMSService.svc/PostAttendance?input=";
$.ajax({
url:url,
headers: {
"CompanyId":"MTF",
"LicenceKey":"MTF-160427-RHGB-4525"
},
type: "POST",
data:{
"E_Code":"0"+e_code,
"AttendanceDateTime":date_time,
"Mode":"I",
"DeviceId":device_id
},
datatype: "jsonp",
success: function(data) {
alert(response);
}
});
}
I tried a lot I am missing some basics in in . How can I handle this? suggest some solutions or links
You can't have jsonp and do a POST.
A jsonp request loads as a <script>.
E.g.
request: /url?callback=something&E_Code=0something
The response will be something like:
something({E_Code: '0something'})
Where something() is your ajax response handler.

HTTP 405 api jquery ajax php

i am trying to add member on myewellness.com
i am using jquery and php on a wordpress website, i have to collect the user's details and add him to myewellness.com
this is the link to their api documentation:
http://www.mediafire.com/view/pr6s7isht9ihdao/API-Services-Documentation-v2.0-1.pdf
but i am getting this on chrome:
OPTIONS https://api.myewellness.com/api/v1/services/membership/create send # jquery.js?ver=1.11.2
(index):1 XMLHttpRequest cannot load https://api.myewellness.com/api/v1/services/membership/create. Response for preflight has invalid HTTP status code 405
(index):1509 Failed: [object Object]
and CORS not enabled error on fire fox,
here is my js:
jQuery.noConflict();
(function( $ ) {
$(function() {
$("#register_form").submit(function(){
console.log("Wellness API Initiated!");
var api_user_name = $("#user_name").val();
var api_user_email = $("#user_email").val();
var api_payment_first_name = $("#payment_first_name");
var api_payment_last_name = $("#payment_last_name");
var api_user_password = $("#user_password").val();
var api_client_address_one = $("#client_address_one").val();
var api_client_address_two = $("#client_address_two").val();
var api_client_city = $("#client_city").val();
var api_client_state = $("#client_state").val();
var api_client_zip = $("#client_zip").val();
var api_client_gender = $("#client_gender").val();
var api_client_home_phone = $("#client_home_phone").val();
var api_client_cell_phone = $("#client_cell_phone").val();
var api_client_work_phone = $("#client_work_phone").val();
var api_client_birth_date = $("#client_birth_date").val();
$.ajax({
type: "POST",
url: "https://api.MYEWELLNESS.com/api/v1/services/membership/create",
/*headers: {
'Authorization':'Basic Vml0YWxhbGVydA==:MTI5OTky',
'Content-Type':'application/json'
},*/
data: "user_name="+api_user_name+"&password="+api_user_password+"&first_name="+api_payment_first_name+"&last_name="+api_payment_last_name+"&address1="+api_client_address_one+"&address2="+api_client_address_two+"&city="+api_client_city+"&state="+api_client_state+"&country=US&zip="+api_client_zip+"&email="+api_user_email+"&phone="+api_client_home_phone+"&work_phone="+api_client_work_phone+"&cell_phone="+api_client_cell_phone+"&gender="+api_client_gender+"&birthdate="+api_client_birth_date,
datatype: "json",
beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " +"Vml0YWxhbGVydA==:MTI5OTky"); },
success: function(msg){
console.log("Success: "+msg);
},
error: function(error){
console.log("Failed: "+error);
}
});
console.log("API Fire Complete!");
return false;
});
});
})(jQuery);
Their server isn't giving you permission to instruct other people's browsers to access their API.
You shouldn't want to do that anyway - otherwise you will be handing over your API key to all your visitors!
Make the API requests from your server, using PHP, instead. You'll probably want to look at the cURL library to do that.

Angular $http.jsonp() method works only once

Response is succeded (alert->done), but second and another hits will response 'error'.
I've tried to add some config params with 'cache: false' but still works only first time. Should I clear some cache/history or sth?
$scope.add2 = function() {
var config = {
//url : 'http://www.***.pl/index.php/json/getallusers',
cache: false,
//type : 'POST',
crossdomain: true,
//callback: 'JSON_CALLBACK',
//data: d,
contentType: "application/json",
dataType: "jsonp",
};
var r = Math.floor(Math.random() * 1000) + 4;
var d = {user_type_id:0, user_venue_id:0, fname:r};
var e = objToString(d);
//$http.jsonp('http://www.***.pl/index.php/json/adduserget?callback=JSON_CALLBACK&'+ e, config)
$http.jsonp('http://www.***.pl/index.php/json/adduserget?callback=JSON_CALLBACK&'+ e)
.success(function(res){
console.log('res:' + res.user);
alert('done');
})
.error(function(){
console.log('error');
alert('error');
});
};
This is the new question in jsonp and post action in ionic framework (angular.js)
I've added to server response 'angular.callbacks._0(' before json data... maybe here's mistake?
This is solution for my issue:
now i'm dynamiccaly getting the callback parameter which can by vary (not always angular.callback_0, but can be: angular.callback_1, angular.callback_2, etc.) from GET method at a server and put it before response data f.e in php:
<?php header('content-type: application/json;');
$json=json_encode($result);
echo $_GET['callback'].'('.$json.')';
?>
Issue is because url is getting cached in browser and the other time it will fetch from the cache.So I'd suggest you to add new dummy parameter inside you URL that will have current Date.now() so that every time you call service that will make URL unique doe to Date.now() component.
Code
$http.jsonp('http://www.where2play.pl/index.php/json/adduserget?callback=JSON_CALLBACK&'+
e + '&dummy='+ Date.now()) //<--this will add new value everytime to make url unique

Ajax not calling controller method

I am new to Ajax. i am trying to call my controller method but call from Ajax not invoking url i am given.. here my controller method and ajax call in my jsp file..
#RequestMapping(value = "/getdata", method = RequestMethod.POST)
public #ResponseBody String add(#RequestParam(value="userDetailObject", required=true) User_Details u,Model model) {
System.out.println("In the controller method..");
String result=null;
result="From controller :"+u.getEmail();
System.out.println("at controller .."+result);
return result;
}
and my Ajax is
//script type="text/javascript" src="../jquery-1.4.4.js"
var jq = jQuery.noConflict();
function getData() {
alert("hello");
// get the form values
var email = $('#email').val();
// var education = $('#education').val();
$.ajax({
type : 'POST',
dataType: 'json',
url : "/SpringDemoSts/getdata",
data : 'email=' + email,
success : function(response) {
// we have the response
//$('#info').html(response);
$('#email').val(response);
//$('#education').val('');
},
error : function(e) {
alert('Error: ' + e);
}
});
}
/script
what is wrong i am doing wrong here ?
the url defined in ajax :
/SpringDemoSts/getdata
is didfferent to that in the requestmapping shown
/getdata
and the parameter is called userDetailObject and your ajax call defines data incorrectly,you are using request parameters style as the data. When in fact you need json/a plain primitive or string.

Categories

Resources