AJAX escaping '+' symbol, invalid syntax - json

I need this part of my url:
"Regular+Season" printed as "Regular+Season" instead of "Regular%2BSeason" to the console.
I have currently developed a ajax function and I keep getting invalid syntax errors due to this issue
Ajax code:
function loadStats() {
$.ajax({
url: 'http://stats.nba.com/stats/leagueLeaders?&callback=?',
jsonpCallback: 'jsonReturnData',
dataType: 'jsonp',
data: {
LeagueID: '00',
PerMode: 'PerGame',
Scope: 'S',
Season: '2016-17',
SeasonType: 'Regular+Season',
StatCategory: 'PTS',
format: 'json'
},
success: function(response) {
console.log(response);
}

Related

How to Post JSON Data to server in phonegap

hi i write in this code but i get Error like UNdefined how we can resolve this issue if any one know this answer plz let me know
$.ajax({ type: "POST", contentType:"application/json; charset=utf-8", dataType: "application/json", url:"some url",
data :{familyVoterId:'0',boothId:'0',voterId:'59136604',previousEnrollmentNumber:'29422415',casteId:'62',street:'hamlet',voterRelationId:'8',cadrePrevYear:'',relativeName:'DESSAPPA',previousRollesList:[{fromDateStr:'2012-10-24',cadreRoleId:'1',cadreCommitteeId:'1',cadreCommitteeLevelId:'1',toDateStr:"2013-10-24"}],partyMemberSinceStr:"2001-10-24",uniqueKey:"10d11073-a8b1-4764-bf2f-e2c0a269e9cd",nameType:"Voter",panchayatId:"0",age:28,surveyTimeStr:"2014-10-24 15:05:15",gender:"M",relationTypeId:8,bloodGroupId:3,dobStr:"1968-02-02",nomineeGender:"1",photoType:"VOTER",voterCardNumber:"UXN0862806",longititude:"78.413",aadheerNo:"987654321",candidateAadherNo:"12345678910",educationId:"2",nomineeAge:"21",previousParicaptedElectionsList:[{"electionTypeId":17,candidateId:"30126",constituencyId:"461"}],voterName:"RAMAKRISHNA",occupationId:"1",houseNo:"3-60",cadreFamilyDetails:[],createdUserId:"152",refNo:"TR-T-9999-12985",constituencyId:"282",latitude:"17.4278",nomineeName:"nominee",mobileNumber:"9999999999"},
success: function(data)
{
alert("success");
},
error: function(msg)
{
alert(msg.message);
}
});
Also, in addition, the reason it is failing in the first place is because you need to do a cross-domain post. In order to do this correctly through jQuery, you need to use the following options:
dataType: 'jsonp',
cache: false,
I reproduced your error. In Chrome if you click inspect element and then select the Console tab you can see the error message :
XMLHttpRequest cannot load file:///D:/DeleteME/pyMail/some%20url.
Cross origin requests are only supported for protocol schemes: http,
data, chrome-extension, https, chrome-extension-resource.
As mentioned before you need to specify the data type as jsonp if your are posting to another domain.
Example:
$.ajax({ type: "POST", contentType:"application/jsonp; charset=utf-8", dataType: "application/json", url:"http://www.google.com",
data :{familyVoterId:'0',boothId:'0',voterId:'59136604',previousEnrollmentNumber:'29422415',casteId:'62',street:'hamlet',voterRelationId:'8',cadrePrevYear:'',relativeName:'DESSAPPA',previousRollesList:[{fromDateStr:'2012-10-24',cadreRoleId:'1',cadreCommitteeId:'1',cadreCommitteeLevelId:'1',toDateStr:"2013-10-24"}],partyMemberSinceStr:"2001-10-24",uniqueKey:"10d11073-a8b1-4764-bf2f-e2c0a269e9cd",nameType:"Voter",panchayatId:"0",age:28,surveyTimeStr:"2014-10-24 15:05:15",gender:"M",relationTypeId:8,bloodGroupId:3,dobStr:"1968-02-02",nomineeGender:"1",photoType:"VOTER",voterCardNumber:"UXN0862806",longititude:"78.413",aadheerNo:"987654321",candidateAadherNo:"12345678910",educationId:"2",nomineeAge:"21",previousParicaptedElectionsList:[{"electionTypeId":17,candidateId:"30126",constituencyId:"461"}],voterName:"RAMAKRISHNA",occupationId:"1",houseNo:"3-60",cadreFamilyDetails:[],createdUserId:"152",refNo:"TR-T-9999-12985",constituencyId:"282",latitude:"17.4278",nomineeName:"nominee",mobileNumber:"9999999999"},
dataType: 'jsonp',
success: function(data)
{
alert("success");
},
error: function(msg)
{
alert(msg.message);
}
});
Message is not a property of the XHR object msg in your error callback function. That is why it shows undefined in your alert box. You can try to alert msg.statusText and see the status text.
Please check the documentation http://api.jquery.com/jquery.ajax/
(The jqXHR Object section)

jsonp jquery ajax call

I'm in need of a code example here :/ I'm trying to get a jsonp call to work.
This is my code on jquery:
$.ajax({
crossDomain:true,
url: "the_server_url",
type: "POST",
data: {
numberOfUnits:10,
unitType:"u",
language:"eng-us",
genderAndAge:"MiddleAgeAnyGender",
script:"",
synced_recording:0,
secret:0,
numAuditions:0
},
dataType: "jsonp",
success: function(text) {
alert("Text: "+text);
},
error: function(request,error)
{
alert("err: "+error);
alert ( " Can't do because: " + JSON.stringify(request));
alert("response text: "+request.responseText);
}
});
And this is what I get:
alert #1: err: parsererror
alert #2: Can't do because: {"readyState":4,"status":200,"statusText":"success"}
alert #3: response text: undefined
I don't have access to the server code. Any ideas? Thank you!

ajax post multiple parameters does not pass properly to asp.net mvc action

I am not able to pass 2 parameters to the action method as json. I have the following ASP.net MVC3 action.
[HttpPost]
public JsonResult Create( PatientContactEpisodes patientcontactepisode, IList<PatientContactEpisodeProcedures> patientcontactepisodeprocedures)
And my ajax post looks like this.
$("#SaveButton")
.button()
.click(function () {
var episode = getpatientcontactepisode();
$.ajax({
type: 'POST',
traditional: true,
url: "/User/PatientContactEpisodes/Create",
contentType: 'application/json, charset=utf-8',
data: {patientcontactepisode: JSON.stringify(episode), patientcontactepisodeprocedures: JSON.stringify(createArray)},
//data: JSON.stringify(episode),
dataType: "json",
success: function (results) {
alert("success");
}
});
});
ISSUE
The issue is that the value does not seem to be passed when I send both parameters to the action. Both are null/empty. Whereas, when i send a single parameter
//data: JSON.stringify(episode), or //data: JSON.stringify(createarray),
The above works fine.
Try:
data: {JSON.stringify({patientcontactepisode: episode, patientcontactepisodeprocedures:createArray})},
This should do the stuff for you.

How to read the JSON file using jQuery in ASP.NET?

I have tried this alot but always I am getting the failure problem .Can any one guide how can we read the json file using jQuery?I have a json file in my project as given in this image
i have written the code as given below
$(document).ready(function () {
$('#btnLoad').click(function () {
$.ajax({
url: "example.json",
dataType: "text/json",
type: "GET",
contentType: "application/json;charset=utf-8",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
But It is always AjaxFailed is firing.
dataType should be 'JSON'
There are only 4 accepted values for dataType, which you can see here:
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
Also, your error function takes 3 parameters:
errorFn(jqXHR, textStatus, errorThrown) {
// your code
}
Additionally, this:
success: function (msg) {
AjaxSucceeded(msg);
},
Can be this:
success: AjaxSucceeded
Your success function also takes 3 parameters:
success(data, textStatus, jqXHR)
For reference on $.ajax parameters: http://api.jquery.com/jQuery.ajax/

Jquery Autocomplete with json and using parameters

I am trying to do an autocomplete input field. Everytime a user type a letter in that field, the value of the field is sent to the server and the server answer with words that match.
var acOptions = {
source:function (request, response) {
$.ajax({
url: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw",
type: "GET", dataType: "json",
data: { expr: request.term},
success: function (data) {
response($.map(data, function (item) {
return item.value;
}))
}
})
},
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
This is an example of data from the server:
[{"value":"Greater"},{"value":"great"},{"value":"greatly"},{"value":"Greater-Axe"}]
The previous code do the right request to the server (and the server answer right) but it does not display anything in the text field.
I tried to do the autocomplete without an explicit ajax object but then I couldn't send the current value of the field (parameter "expr" of the request) to the server:
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=",
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
Thank you for your help!
You can use jQuery to pull the value of your field to add it to URL parameter string.
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=" + $('#ID_OF_YOUR_TEXTBOX').val(),
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);