Ajax Call using jsonp for calling rest webservice from other domain - html

How I use the jsonp when call to rest webservice from different domain.becouse my simple json does not working for rest webservice.how can i call rest webservice for ajax call.i use both jsonp and javascript for that.server responce i seen on only browser in firebug but how to show it on my application
my JS code.
function callService() {
$.ajax({
type: varType, //GET or POST or PUT or DELETE verb
url: varUrl, // Location of the service
data: varData, //Data sent to server
crossDomain: true,
cache: false,
async: false,
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
alert("Server Responce Successfully!..");
},
error: function (msg) {
alert('error ' + msg.d);
}
});
}
function countryProvinceWCFJSONMulti() {
var head = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.type = 'JSON';
script.src = "http://192.168.15.213/myservice/Service.svc/GetEvents";
script.type = "text/javascript";
head.appendChild(script);
varType = "GET";
varData = '{"username": "' + "Suhasusername" + '","password": "' + "suhaspassword" + '"}';
varContentType = "application/JSONP; charset=utf-8";
varDataType = "JSONP";
varProcessData = true;
callService();
}

If the same-origin policy isn't an issue, your code should look something like this:
$.ajax({ url: url,
dataType: 'jsonp',
contentType: 'application/json',
success: function (data) {
alert("Server Response Successful!..");
}
});
Here is a question that talks about circumventing the same-origin policy

Related

Ajax function (Unexpected token) in AJAX Call

so I have been testing a bunch of new different JS code to see if I can get the POST request to send information to a SharePoint list. When I run my newest block, it tells me "Error: Line 20: Unexpected token" when I call $.ajax saying the period is what is unexpected? I truly don't understand.
Here is my JS code:
$(document).ready(function(){
$("#btnSubmit").click(function(){
saveDelivDetails();
});
});
function saveDelivDetails(){
var itemType = GetListItemTpye(listname);
var item = {
"__metadata":{"type":itemType},
"Program":$("#dProgram").val(),
"Deliverable":$("#dDeliverable").val(),
"To":$("#dTo").val(),
"Date":$("#dDate").val(),
"Approved":$("#dApproved").val(),
"Notes":$("#dNotes").val()
};
var requestUrl = _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('"+listname+"')/items",
$.ajax({
url: requestUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers:{
"Accept":"application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val()
},
success: onSuccess,
error: onError,
});
function onSuccess(data){
alert("New Item Created");
$("#txtSubmitName").val();
}
function onError(error){
alert('error' + error);
console.log(error);
}
function GetListItemType(name){
return "SP.Data."+CharacterData(0).toUpperCase().name.slice(1)+"ListItem";
}
You have a , after line 19.
var requestUrl = _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('"+listname+"')/items",

posting json to express - invalid json

I am trying to post some json to a node server running express but it keeps telling me the json was invalid. But its not, its just a plain old object. Currently I get the error 'unexpected token i'
client:
$.ajax({
contentType: 'application/json',
type: "POST",
url: "/admin",
data: {id: '435ghgf545ft5345', allowed: true}
});
server:
var bodyParser = require('body-parser');
app.use(bodyParser({strict: false}));
app.post('/admin', function(request, response) {
console.log(request.body);
});
I have also tried putting bodyParser.json() as the second parameter in the post route and get the error 'invalid json at parse'. I cant figure out why.
This code may help you :
var jsondataResource = JSON.stringify({id: '435ghgf545ft5345', allowed: true});
$.ajax({
type: 'POST', //GET or POST or PUT or DELETE verb
async: false,
url: '/admin', // Location of the service
data: jsondataResource , //Data sent to server
contentType: 'application/json', // content type sent to server
dataType: 'json', //Expected data format from server
processdata: true, //True or False
crossDomain: true,
success: function (msg, textStatus, xmlHttp) {
result = msg;
},
error: ServiceFailed // When Service call fails
});
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
}

Chrome extension transfer to manifest 2 - No ajax response

Hayush!
Been trying to transfer my Chrome extension to manifest 2. Everything is working except for one script which calls an ajax. I have a variable that contains a JSON content which needs to be transferred to the server.
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
For some reason the ajax part is not executed at all. No error message was triggered, nor in the server error log.
All of the inline scripts and scripts in general were included in the popup.js. So it's probably not the issue.
Any thoughts?
Thanks!
The following code works perfectly on previous manifest
function importbookmarks(){
$('#formadd').css('display','none');
$('#importing').css('display','block');
_gaq.push(['_trackEvent', 'chromextension','importbookmarks', username]);
chrome.bookmarks.getTree(function(bookmarks) {
sendlist(bookmarks);
});
}
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
// processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
}
});
}
The problem wasn't with the function. The button execution wasn't calling it correctly.
Here is the code I used to get the function to work in manifest 2
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("import-bookmarks").addEventListener("click", function () {
importbook();return;
});

Headers using ajax request

How to set headers using Ajax request? in below code
$.ajax({
type: type, //GET or POST or PUT or DELETE verb
url: requestURL, // Location of the service
// contentType: "application/x-www-form-urlencoded", // content type sent to server
dataType: "xml", //Expected data format from server
processData: false, //True or False
success: successCallback, //On Successfull service call
error: serviceFailed// When Service call fails
});
Request headers can be managed using beforeSend(jqXHR, settings) function and the setRequestHeader method, e.g.
$.ajax({
...
beforeSend : function(xhr) {
xhr.setRequestHeader('content-Type', 'application/x-www-form-urlencoded');
}
});

Calling a webservice from jQuery returns “No Transport” error

I have the following web service;
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
I am pointing to the latest jquery library.
<script type="text/JavaScript" src="Scripts/jquery-1.6.4.js"></script>
I have this jQuery method;
$.ajax({
type: "POST",
url: "../Service/AFARService.asmx/HelloWorld",
// this._baseURL + method,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnSuccess,
error: fnError,
crossDomain: true,
dataFilter: function (data) {
var response;
if (typeof (JSON) !== "undefined" && typeof (JSON.parse) === "function")
response = JSON.parse(data);
else
response = val("(" + data + ")");
if (response.hasOwnProperty("d"))
return response.d;
else
return response;
}
});
When I execute I get a "No transport" error returned. I added crossDomain: true still no success.
Thanks in advance
BB
to enable cross domain calls, you can try
jQuery.support.cors = true;
if this doesn't works you can go through(JSONP) :
http://www.west-wind.com/weblog/posts/2007/Jul/04/JSONP-for-crosssite-Callbacks
https://en.wikipedia.org/wiki/JSON
http://remysharp.com/2007/10/08/what-is-jsonp/
you can follow any of these
try using
url: "AFARService.asmx/HelloWorld",
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
return "Hello World";
}