I've got following javascript code. It's simply class, that should receive some data from REST WCF client.
class EmployeesWcfClient {
constructor(url) {
if (url == null) {
url = "http://localhost:35798/MyCompanyService.svc/";
}
this.url = url;
}
doGetRequest(relUrl) {
return $.ajax({
type: 'GET',
contentType: 'json',
dataType: 'json',
url: this.url + relUrl,
async: false
});
}
doPostRequest(relUrl, data) {
return $.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
url: this.url + relUrl,
async: false
});
}
getEmployees() {
return doGetRequest('Employees');
}
}
And I don't know why it's raises exception: 'doGetRequest is not defined'. Could someone help?
The answer is simple:
Use this operator in 'return this.doGetRequest('Employees');'. In first code example the this operator was missing.
inside ajax of doGetRequest the this.url will not refer to EmployeesWcfClient.url, instead it will point to the ajax options object itself. So take the reference of this before calling ajax request.
doGetRequest(relUrl) {
var _this = this;
return $.ajax({
type: 'GET',
contentType: 'json',
dataType: 'json',
url: _this.url + relUrl,
async: false
});
}
But I am not sure returning this ajax function will exactly return you the response from the request though you made it async: false. Better use callbacks or promise.
Related
I am trying to send a CKeditor value post with ajax but i cant response anyway! I cant find anything
function send_days(tourId){
var url = baseUrl + "tour/save_days/" + tourId;
var value = CKEDITOR.instances.tour_textarea_days.getData();
$.ajax({
url: url,
method: "POST",
data: dataString,
contentType: false,
processData: false,
cache:false,
success: function (data) {
$('.tour_popup_container').html(data);
}
});
}
but when i chance ajax method like this. It is succesfull
$.post(url, {data:value}, function (response) {
$('.tour_popup_container').html(response);
})
here is my codeigniter php file (it is not important actually)
public function save_days($tourId)
{
$value=$this->input->post("data");
print_r($value);
}
It looks like you used dataString instead of value.
var url = baseUrl + "tour/save_days/" + tourId;
var value = CKEDITOR.instances.tour_textarea_days.getData();
$.ajax({
url: url,
method: "POST",
data: value /*dataString*/,
contentType: false,
processData: false,
cache:false,
success: function (data) {
$('.tour_popup_container').html(data);
}
});
Once again I've been beating my head against the wall, trying to pull this part of returned data from ajax to a variable outside the function.
When I return the value it always comes up undefined when I alert() inside it shows the proper values.
function getItemInfo(itemHashPass) {
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
return data.Response.data.inventoryItem.itemName;
}
});
}
I've also tried
function getItemInfo(itemHashPass) {
var tmp = null;
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
tmp = data.Response.data.inventoryItem.itemName;
}
});
return tmp;
}
Like Jonathan said you should write your business logic in the callback or you can try Deferred syntax. In this case it will looks like
function yourBusinnesLogicFunction() {
...
getItemInfo("password_hash_value").done(
function(data){
alert(data.Response.data.inventoryItem.itemName);
}
)
}
function getItemInfo(itemHashPass) {
var tmp = null;
return $.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
})
}
How to call multiple ajax calls one after another in a chained way?
Hi,
I am having a controller method which returns json based on the start limit and end limit which needs to done by ajax call.
So, initially in first ajax call start limit =1 and end limit=100 and on success of this ajax, same ajax call should be called with updated start limit =101 and end limit=200.
Like wise multiple ajax reuqests needs to be sent till actual dead line of 1000 i reached.
So totatlly 10 ajax calls from 1-100,101-200,201-300 e.t.c till 1000 have to be sent.
Actually i am sending these chained ajax;s this way,
$.ajax({
url: getdata/100/200",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
//some logic
//2nd ajax
$.ajax({
url: getdata/101/201",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
//some logic
//3rd ajax
$.ajax({
url: getdata/201/301",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
}
}
But all the time only my first ajax is getting success and rest of the ajax;s are not getting executed and giving 404 error.
Is there any timeinterval needs to be set for calling one ajax inside?
What is the mistake i am doing here..?
can anyone help me in this issue?
Thanks
You can solve these issue by using function like following :-
// Make initial call to function with your data
myAjaxCall(data, 1, 100);
function myAjaxCall(data, startLimit, endLimit)
{
$.ajax({
url: "getdata/"+startLimit+"/"+endLimit, // Concat variables as per your codes
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
myAjaxCall(data, endLimit+1, endLimit+100);
}
}
});
}
If you need to chain Ajax call try to use Jquery.Deferred
it will looks like:
$.when($.ajax(...)).then($.ajax(..)) ...
You can achive this by recursive function
function ajaxRun(data){
$.ajax({
url: "getdata/201/301",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(resultData) {
json=JSON.stringify(resultData);
console.log("json" + json);
console.log(JSON.stringify(resultData));
if(json != null && json != "") {
ajaxRun(data);
}
}
});
}
Hello change your parameter name every ajax success method like
success: function(resultData)
second time
success: function(secondresultData)
I am working on a real estate web app in ASP.NET MVC. My problem is in my Reservations section.
I am using AJAX to post in a Controller which returns a JSONResult. Here is my code:
Controller
[HttpPost]
public JsonResult SubmitReservation(ReservationViewModel rvm)
{
return Json(rvm, JsonRequestBehavior.AllowGet);
}
Main AJAX
var rvm = new ReservationViewModel();
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
$.ajax({
url: "/Reservations/SubmitReservation",
data: JSON.stringify(rvm),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function () {
console.log(clientData);
console.log(siteData);
console.log(unitData);
//Assignment of data to different output fields
//Client Data
$('#clientName').html(clientData.FullName);
$('#clientAddress').html(clientData.Residence);
$('#clientContact').html(clientData.ContactNumber);
//Site Data
$('#devSite').html(siteData.SiteName);
$('#devLoc').html(siteData.Location);
////House Unit Data
$('#unitBlock').html(unitData.Block);
$('#unitLot').html(unitData.Lot);
$('#modelName').html(unitData.ModelName);
$('#modelType').html(unitData.TypeName);
$('#lotArea').html(unitData.LotArea);
$('#floorArea').html(unitData.FloorArea);
$('#unitBedrooms').html(unitData.NumberOfBedrooms);
$('#unitBathrooms').html(unitData.NumberOfBathrooms);
$('#unitPrice').html(unitData.Price);
$('#reservationDetails').show();
alert("Success!");
},
error: function (err) {
alert("Error: " + err);
}
});
Functions for fetching data
function getBuyerInfo(id, cb) {
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getSiteInfo(id, cb) {
$.ajax({
url: "/Sites/GetSiteByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getUnitInfo(id, cb) {
$.ajax({
url: "/HouseUnits/GetUnitByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function ReservationViewModel() {
var buyerId = $('#SelectedBuyerID').val();
var siteId = $('#SelectedSiteID').val();
var unitId = $('#SelectedUnitID').val();
var rsvDate = $('#ReservationDate').val();
var me = this;
me.ReservationDate = rsvDate;
me.SelectedBuyerID = buyerId;
me.SelectedSiteID = siteId;
me.SelectedUnitID = unitId;
}
function clientCallback(result) {
clientInfo = result;
clientData = clientInfo[0];
}
function siteCallback(result) {
siteInfo = result;
siteData = siteInfo[0];
}
function unitCallback(result) {
unitInfo = result;
unitData = unitInfo[0];
}
The whole code WORKS well for the second time. However, it does not work for the FIRST time. When I refresh the page and I hit Create, it returns undefined. But when I hit that button again without refreshing the page, it works well. Can somebody explain to me this one? Why does AJAX returns undefined at first but not at succeeding calls? Thanks in advance.
You are calling several ajax requests in your code, inside these functions:
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
and finally $.ajax({...}) after them, where you use results from pervious ajax calls.
Your problem is that the first ajax calls do not necessarily return results before your start the last ajax because they are all async. You have to make sure you get three responds before calling the last ajax. Use promises or jQuery when, like this:
var rvm = new ReservationViewModel();
$.when(
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + rvm.SelectedBuyerID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/Sites/GetSiteByID/" + rvm.SelectedSiteID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/HouseUnits/GetUnitByID/" + rvm.SelectedUnitID,
type: "GET",
contentType: "application/json",
dataType: "json"
})
).done(function ( clientResponse, siteResponse, unitResponse ) {
clientInfo = clientResponse;
clientData = clientInfo[0];
siteInfo = siteResponse;
siteData = siteInfo[0];
unitInfo = unitResponse;
unitData = unitInfo[0];
$.ajax({ ... }) // your last ajax call
});
AJAX calls are asynchronous. You last ajax call will not wait until your above 3 ajax calls finishes its work. so you can make use of $.when and .done here as below..
$.when(
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
).done(
$.ajax({
//Ajax part
})
);
This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});