I have to fire an ajax call against two different domain based on the platform of the client (mobile/desktop):
var baseDomain = (isMobile()) ? "http://m.test.com" : "http://www.test.com";
function AddProduct(ProductId, ButtonClientId) {
$.ajax({
type : "POST",
eval("url : \""+baseDomain+"/data/call.aspx/AddToShoppingCart\",");
contentType : "application/json; charset=utf-8",
data : '{productId:' + ProductId + ', quantity: 1, isSingle: true}',
dataType : "json",
success : function(data) {
ProductAddedSuccess(data.d, ButtonClientId);
},
error : ProductAddedError
});
}
I cannot go thru this as I always get the "SyntaxError: missing formal parameter". Where I'm wrong?
Try this:
$.ajax({
type : "POST",
url : baseDomain + "/data/call.aspx/AddToShoppingCart",
contentType : "application/json; charset=utf-8",
data : '{productId:' + ProductId + ', quantity: 1, isSingle: true}',
dataType : "json",
success : function(data) {
ProductAddedSuccess(data.d, ButtonClientId);
},
error : ProductAddedError
});
The URL is just a string, so create the string you want in a variable and assign it to the url property of the Ajax options:
var baseDomain = isMobile() ? "http://m.test.com" : "http://www.test.com";
function AddProduct(ProductId, ButtonClientId) {
$.ajax({
type : "POST",
url: baseDomain + "/data/call.aspx/AddToShoppingCart",
contentType : "application/json; charset=utf-8",
data : '{productId:' + ProductId + ', quantity: 1, isSingle: true}',
dataType : "json",
success : function(data) {
ProductAddedSuccess(data.d, ButtonClientId);
},
error : ProductAddedError
});
}
The reason for the error is you are placing a function call (to eval()) in the middle of an anonymous object declaration!
e.g.
{
propName1: "Value 1",
someFunctionCall(),
propName2: "Value 3"
}
Which makes no sense to Javascript :)
Related
I'm calling Ajax like below
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: '{ "jsondata":' + jsondata + ',"key":"' + getValue('id') + '"}',
success: function (data) {
callback(data);
},
error: function (error) {
callback(error.responseText);
}
});
I want to get the "Data" value at calling time because after the call the execution doesn't goes to the desired web method and the error is showing like
""Message":"Invalid web service call, missing value for parameter: \u0027obj\u0027..."
I have to track the the Ajax posting value during Ajax call and find out what is the problem with posting data.Is there any tricks to get the data value before Ajax calling?
Any help will be appreciated.
Edit: I'm sending the jsondata value like below
var jsondata = '{ "pagenumber":"' + pagenumber + '","sortColumn":"' + sortColumn + '","sortDirection":"' + sortDirection + '","rowPerPage":"' + rowPerPage + '"}';
Thanks.
I was just checking with below code -
please have a look. please check beforesend content
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/dummy',
dataType: "json",
data: '{dummy:"dummy"}',
success: function (data) {
alert(data);
},
error: function (error) {
alert(error);
},
beforeSend: function(data,data1) {
console.log('before'+data1.data)
},
});
})
});
var path = "test_ajax.php";
var jsondata = "Testing123";
var test = "test";
var data = {jsondata : jsondata,key : test};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: data,
success: function (data) {
alert("success:"+data);
},
error: function (error) {
alert("failure"+error.responseText);
}
});
When i try to POST my JSON am not able to see any request and also my local server not even getting these calls.
This is my ajax part
function callserver(){
var markers = {"regDate" : 1451330123000, "specialities" : " ", "isActive" : true, "mobileNo" : "876876","id" : 0, "completed" : false,"mcname" : "", "password" : "hgh","role" : "SuperAdmin,Consultant","logins" : [],"email" : "testtestets#test.com","name" : "regcg","organization" : "hghjg"};
alert(markers);
$.ajax({
type: "POST",
data:markers,
headers: {
'Accept':'application/vnd.company.productname-v1+json',
'X-PD-Authentication':'42</B7Tg8o5C7`7<7Ar0?]pJs`#Noplt>I1m>QYQn[v=osDl:unWyx`SYqBK#0?w',
'Content-Type':'application/json'
},
dataType: "json",
url: "http://x.x.x.x:9001/users",
success: function(data) {
alert("success");
},
error: function () {
alert("failure");
}
});
}
Till alert(markers); is working but after that
am not getting "Success" or "failure" alert.
Console screenshots
Please help me
As you are not ready to show the full HTML, it looks like you are using another library with jQuery, because jQuery works. So kindly change all the $ to jQuery:
function callserver(){
var markers = {"regDate" : 1451330123000, "specialities" : " ", "isActive" : true, "mobileNo" : "876876","id" : 0, "completed" : false,"mcname" : "", "password" : "hgh","role" : "SuperAdmin,Consultant","logins" : [],"email" : "testtestets#test.com","name" : "regcg","organization" : "hghjg"};
alert(markers);
// Change here
jQuery.ajax({
type: "POST",
data:markers,
headers: {
'Accept':'application/vnd.company.productname-v1+json',
'X-PD-Authentication':'42</B7Tg8o5C7`7<7Ar0?]pJs`#Noplt>I1m>QYQn[v=osDl:unWyx`SYqBK#0?w',
'Content-Type':'application/json'
},
dataType: "json",
url: "http://x.x.x.x:9001/users",
success: function(data) {
alert("success");
},
error: function () {
alert("failure");
}
});
}
$(".loadingPnl").removeClass('hdn');
var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/SaveAvailableFavoriteItem";
var linkName = $('.txtLinkName').val();
linkName = linkName.replace("'","\'");
$.ajax({
type: "POST",
url: callUrl,
data: "{'linkName': '" + linkName + "', 'webSiteUrl':'" + $('.txtWebAddress').val() + "','iconId':'" + $(".ddlIcons").val() + "'}",
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});
return true;
}
The problem is you're building JSON yourself as the request parameters. Moreover, you're building invalid JSON (JSON property names are always with double quotes (")).
Instead, pass an object and let jQuery take care of how to send it - if you pass that instead of a string the server can figure it out. If you really want to do it yourself you can also pass an object to JSON.stringify.
var payload = {
linkName: linkName,
webSiteUrl: $('.txtWebAddress').val(),
iconId: $(".ddlIcons").val()
};
$.ajax({
type: "POST",
url: callUrl,
data: JSON.stringify(payload), // or just payload
contentType: "application/json; charset=utf-8",
processData: false, // if you just pass payload, remove this
dataType: "json"
// you had two `return`s here, but they wouldn't work, make sure
// you understand why
// http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call
});
You can send a JSON instead. Or use JSON.stringify if you want String.
{
'linkName' : linkName,
'webSiteUrl' : $('.txtWebAddress').val(),
'iconId' : $(".ddlIcons").val()
}
Don't create JSON string by yourself AND don't use JSON.stringify().
Problem with creating JSON string yourself is to escape string properly for JavaScript (which could be tricky). see Special Characters
Problem with JSON.stringify is that I found it somehow slower than XMLHttpRequest which is strange because I thought it is using JSON.stringify behind curtains.
XMLHttpRequest is handling this for you. If you just pass your object as a data and XMLHttRequest will do the trick.
$.ajax({
type: "POST",
url: callUrl,
data: {'linkName': linkName,
'webSiteUrl': $('.txtWebAddress').val(),
'iconId': $(".ddlIcons").val()
},
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});
Hi there are already lots of threads related to this problem.
But still i got stuck into the same . When I am trying to access this REST api, I couldnt able to get the response. I cannot control server side response header because its public API .can any body help on this.
Below is my code
$(document).ready(function() {
$("#medication").autocomplete({
select : function(request, response) {
//$(this).value(response.item.value);
getMedicationIdByName(response.item.value);
},
search : function(){$(this).addClass('working');},
open : function(){$(this).removeClass('working');},
source : function(request, response) {
$.ajax({
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
type : "GET",
url : "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
data : "name="+ request.term,
crossDomain: 'true',
dataFil ter : function(data) {
return data;
},
success : function(data) {
try {
//alert("success!!"+JSON.stringify(data));
data = data.suggestionGroup.suggestionList["suggestion"]+ "";
data = data.split(",");
response($.map(data,function(item) {
//alert("success!!"+JSON.stringify(item))
return {
value : item
};
}));
} catch (e) {
alert(e);
}
},
error : function() {
alert('Cannot connect to REST API!!!');
}
});
},
minLength : 4
});
});
You need to set dataType to jsonp in your ajax request.
type: "GET",
headers: {
Accept : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url: "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
data: { name: "bard"},
dataType: "jsonp",
crossdomain: true,
I'm using JQuery to consume a WCF Service. Actually this works fine:
var para = ' { "Parameter" : { "ID" : "5", "Name" : "Peter" } }'
$.ajax({
type: "POST",
contentType: "application/json",
data: para,
url: url
success: success
});
But I don't want to pass the data parameter as String and I think it should be possible to pass ist as array in any way. Like that:
var para = { "Parameter" : { "ID" : 5, "Name" : "Peter" } }
But when I try this I'm getting an error. What I'm doing wrong?
Thanks
var para = '{ "ID" : "5", "Name" : "Peter" }';
$.ajax({
type: "POST",
data: para,
url: url
success: success
});
If you format it like this you should be able to get the values as
$_POST will return array('ID' => '5', 'Name' => 'Peter');
but you can also access it by doing:
$_POST['ID'] and $_POST['Name']
Also you could make use of the jquery post function:
var para = '{ "ID" : "5", "Name" : "Peter" }';
$.post(
url,
para
);
You can use JSON.stringify function from the json2.js. Then you ajax call will be
var para = { Parameter : { ID :5, Name : "Peter" } };
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify(para),
url: url
success: success
});
The usage of manual conversion to the JSON string is not good because of possible spatial characterless in the string which must be escaped (see http://www.json.org/ for details).