I am doing an initial ajax call to get the post title from the WordPress Rest API, but I also need to get another value (siteServer) from another ajax call, but when I try to pass this I get 'undefined'. I assume this is due to an asynchronous issue, but not sure how to pass it up. What am I doing wrong?
Here is my jQuery code, but I am open to vanilla solutions as well.
function getPosts(object, query) {
jQuery.ajax({
type: 'GET',
url: query,
})
.then( function (data, status, request) {
jQuery.each(data, function(i, post) {
let siteTitle = post['title']['rendered'];
let siteServer = '12';
jQuery(object).append(`
<div class="get-post-item">
<div class="site-title"><span>`+ siteTitle +`</span></div>
<div class="site-server"><span>`+ getServerName(siteServer) +`</span></div>
</div>
`);
});
}
})
}
function getServerName(id) {
jQuery.ajax({
type: 'GET',
url: '/wp-json/wp/v2/servers/' + id
})
.then(function (data, status, request) {
let serverName = data['title']['rendered'];
return serverName;
})
}
Since I am only able to get the ID from the initial ajax call (simplified in the above code as a static string var "let siteServer = '12'") I need to do the second/nested ajax call to get the Title and pass to the .append in the first call.
Related
I am currently learning asp.net core 3 and I can't find any help regarding this issue that I have.
I have a form that submits a value with a POST request. But I want the same button to have a GET request that populates another field with a .ajax / xmlhttprequest. But I want the POST method to be executed first and then the GET method. Is it possible to do it? I've tried doing it but I got stuck.
These are the methods inside my controller.
[HttpGet]
public async Task<IActionResult> GetConvertedAmount()
{
var rate = await _db.ExchangeRates.Where(x => x.Name.Equals(_tM.Currency)).ToListAsync();
_tM.convertToCurrency(rate[0].Rate);
var amount = _tM.Amount;
return Json(amount);
}
[HttpPost]
public ActionResult CalculateExchangeRatio(int amount_give, string type_to_give)
{
_tM.Amount = amount_give;
_tM.Currency = type_to_give;
return Ok();
}
And this is my JS script
$('#calculateButton').on("click", function () {
$.ajax({
url: "/trade/getconvertedamount",
type: "get",
success: function (amount) {
console.log(amount);
alert(amount);
}
});
})
You can use the $.ajax 'done' chaining to complete the entire process:
$('#calculateButton').on("click", function () {
$.ajax({
url: "/trade/calculateexchangeratio",
data: { amount_give: 9.99, type_to_give: 'blahblah' },
type: "post"
})
.done(function(){
$.ajax({
url: "/trade/getconvertedamount",
type: "get"
})
.done(function (amount) { console.log(amount); alert(amount); });
});
})
You can add the similar to the end of the POST method implementation return RedirectToAction("CalculateExchangeRatio", new { amount_give = 1, type_to_give = 2 });
So your POST method will be called first and it will call the GET method.
Here is the documenttation.
I try to make dropdown option dependent using ajax . i want to see the data in console whether the data is success or else. I expect the data was shown in console log but error given
http://localhost/fic/public/sla/sla/getbranch/180 404 not found
Here is my code for view ajax
if(country_id) {
//console.log(country_id);
$.ajax ({
url: 'sla/getbranch/'+country_id,
//url: "{{ route('sla.getbranch') }}"+country_id,
type: 'GET',
datatype: 'json',
success: function(data){
console.log(data);
}
})
My controller
public function index()
{
$custList = $this->hdcustomermaster->getAllCustomerActiveSts();
return view('sla.slm.SLAList', compact('custList'));
}
public function getbranch($id)
{
$data=HDCustomerBranch::where('cb_customer_ID',$id)->pluck('cu_customer_ID','cu_customer_Name');
return json_encode($data);
}
my web.php
Route::group(['prefix' => 'sla'], function () {
Route::get('/','SlaController#index');
Route::resource('sla', 'SlaController');
Route::get('sla/getbranch','SlaController#getbranch')->name('sla.getbranch');
});
Replace your route like this
Route::group(['prefix' => 'sla'], function () {
Route::get('/','SlaController#index');
Route::resource('sla', 'SlaController');
Route::get('sla/getbranch/{id}','SlaController#getbranch')->name('sla.getbranch');
});
Here the problem is you are passing 180 as an param in that route. But you dont declare that param in your route.
Also you can add a '?' if it is an optional param, like this
Route::get('sla/getbranch/{?id}','SlaController#getbranch')->name('sla.getbranch');
I am using a method in my controller which imports data from an API. This method I am wanted to be called from two locations. First the view (currently working) and secondly a javascript function.
Start of controller method:
[ActionName("ImportRosters")]
[HttpPost]
public ActionResult PerformImportRosterData(int id, int? actualLength, int? rosterLength)
{
var authenticator = Authenticator(id);
var rosters = authenticator.Api().RosterData().ToDictionary(x => x.Id);
var databaseRosterDatas = SiteDatabase.DeputyRosterData.Where(x => x.SiteID == id)
.ToDictionary(x => x.Id);
Javascript Function:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster, ActualLength, RosterLength }
});
SiteIDRoster = null;
location.reload();
$("#btnRunDeputyNow").modal("hide");
toast.show("Import Successful", 3000);
});
All values are being set but i am getting a 404 error on the url line
POST https://example.org/deputy/PerformImportRosterData 404 ()
I need a way to be able to call this c# method from both html and JS
This can be done if you will modify the URL in your AJAX. It should look something like
url: '<%= Url.Action("YourActionName", "YourControllerName") %>'
or
url: #Url.Action("YourActionName", "YourControllerName")
one more thing, I don't see if you do anything with the result of the call. your script does not have success part
success: function(data) {//do something with the return}
and would be very helpful to have error handler in your call.
full example on how AJAX should look like:
$.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
success: function (data, status, jqXHR) {
$("#container").html(data);
alert("Local success callback.");
},
error: function (jqXHR, status, err) {
alert("Local error callback.");
},
complete: function (jqXHR, status) {
alert("Local completion callback.");
}
})
For a good tutorial on AJAX read this document
Change after Comment:
my current code is below:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: '<%= Url.Action("PerformImportRosterData", "DeputyController") %>',
data: { SiteIDRoster, ActualLength, RosterLength },
success: function(data) {
console.log(data);
console.log("TESTHERE");
}
});
}
UPDATE:
Noticed one more thing. Your parameters in the controller and AJAX do not match. Please try to replace your a few lines in your AJAX call with:
url: "/deputy/PerformImportRosterData",
data: { id: yourIDValue, actualLength: youractualLengthValue,
rosterLength :yourrosterLengthValue }
remember to set all variable values in javascript , if they have no values set them = to null.
Can you try copy paste code below
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster:999, ActualLength:1, RosterLength:2 }
});
And let me know if it wall cause any errors.
After attempting to solve for a few days, I created a workaround by creating two methods for importing the data. one for the httpPost and the second for import calling from javascript.
Not a great solution but it works. Thanks for your help Yuri
I am currently working on a React-Rails app and am trying to figure out how to pass a deleted record to a parent component from the success function to update the parent component's view.
Here is the code in question:
handleDelete (e) {
var that = this;
var url = "/records/" + this.props.data.id;
e.preventDefault();
$.ajax({
method: 'DELETE',
url: url,
dataType: 'JSON',
success: (data) => {
console.log(data);
that.props.handleDeleteRecord(data);
}
});
}
The console.log(data) above returns undefined.
My problem is that Ajax doesn't seem to be passing anything to the success function. Is that true?
You need to edit the Rails RecordsController so that it renders some type of data after the request. I recommend JSON.
def destroy
record = Record.find(params[:id])
record.destroy
render json: record
end
With that you will have the JSON form of the record that you just delete passed back to the success function of the AJAX call.
I'm currently dealing with refactoring my code, and trying to automate AJAX requests as follows:
The goal is to have a context-independent function to launch AJAX requests. The data gathered is handled differently based on the context.
This is my function:
function ajaxParameter(routeName, method, array, callback){
//Ajax request on silex route
var URL = routeName;
$.ajax({
type: method,
url: URL,
beforeSend: function(){
DOM.spinner.fadeIn('fast');
},
})
.done(function(response) {
DOM.spinner.fadeOut('fast');
callback(response);
})
.fail(function(error){
var response = [];
response.status = 0;
response.message = "Request failed, error : "+error;
callback(response);
})
}
My problem essentially comes from the fact that my callback function is not defined.
I would like to call the function as such (example)
ajaxParameter(URL_base, 'POST', dataBase, function(response){
if(response.status == 1 ){
console.log('Request succeeded');
}
showMessage(response);
});
I thought of returning response to a variable and deal with it later, but if the request fails or is slow, this won't work (because response will not have been set).
That version would allow me to benefit the .done() and .fail().
EDIT : So there is no mistake, I changed my code a bit. The goal is to be able to deal with a callback function used in both .done() and .fail() context (two separate functions would also work in my case though).
As far as I can see there really is nothing wrong with your script. I've neatened it up a bit here, but it's essentially what you had before:
function ajaxParameter (url, method, data, callback) {
$.ajax({
type: method,
url: url,
data: data,
beforeSend: function(){
DOM.spinner.fadeIn('fast');
}
})
.done( function (response) {
DOM.spinner.fadeOut('fast');
if (callback)
callback(response);
})
.fail( function (error){
var response = [];
response.status = 0;
response.message = "Request failed, error : " + error;
if (callback)
callback(response);
});
}
And now let's go and test it here on JSFiddle.
As you can see (using the JSFiddle AJAX API), it works. So the issue is probably with something else in your script. Are you sure the script you've posted here is the same one you are using in your development environment?
In regards to your error; be absolutely sure that you are passing in the right arguments in the right order to your ajaxParameter function. Here's what I am passing in the fiddle:
the url endpoint (e.g http://example.com/)
the method (e.g 'post')
some data (e.g {foo:'bar'})
the callback (e.g function(response){ };)
Do you mean something like this, passing the success and fail callbacks:
function ajaxParameter(routeName, method, array, success, failure) {
//Ajax request on silex route
var URL = routeName;
$.ajax({
type: method,
url: URL,
beforeSend: function () {
DOM.spinner.fadeIn('fast');
}
}).done(function (response) {
DOM.spinner.fadeOut('fast');
success(response);
}).fail(function (error) {
var response = [];
response.status = 0;
response.message = "Request failed, error : " + error;
failure(response);
})
}
Called like:
ajaxParameter(
URL_base,
'POST',
dataBase,
function(response){
//success function
},
function(response){
// fail function
}
);