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.
Related
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.
I am working in a Django project where one of the functionalities will be that user could search a name (using a form), the view will search that name in database (after some transformation), and the results will be displayed below the form.
At the moment, It is necesary that the entire page loads every time a search is submitted. I am working in apply ajax to make this dynamic. The problem is that when I return the search result as a JsonResponse, I am not able to see the data in the success function of ajax.
Views.py
def indexView (request):
form = FriendForm ()
friends = Friend.objects.all ()
return render (request, "index.html", {"form": form, "friends": friends})
def searchFriend(request):
if request.method =="POST":
form = FriendForm (request.POST)
if form.is_valid():
if request.is_ajax():
name = form.cleaned_data['name']
query = Friend.objects.filer(first_name__contains=name)
print(query)
return JsonResponse(list(query), safe=False)
else:
return JsonResponse(form.errors)
Main.js
$(document).ready(function() {
$("#form1").submit(function() { // catch the form's submit event
var search = $("#searchField").val();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
method: 'post',
dataType: 'json',
url: "search/ajax/friend/",
success: function(data) { // on success..
console.log(data)
}
});
return false;
});
});
Is your query getting printed in terminal ?
Friend.objects.filer use filter instead of filer
and use type: 'post' instead of method: 'post',
and add data: $(search).serialize(), instead of data: $(this).serialize(),
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');
suppose my URL is example.com/controller/method/
when I use this ajax code it makes URL like example.com/controller/method/method which not getting data.
function getProductList() {
var category = document.getElementById('Category').value;
$.ajax({
type: 'POST',
url: 'GetProductList',
data: {CategoryId: category},
dataType: 'json',
cache:false,
success: function (response) {
}
});
}
but when my URL is example.com/controller/method then ajax getting data correctly. but i want to get data from the database on both situations.
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. So you can not use example.com/controller/method/method.The segments in a URI normally follow this pattern: example.com/class/function/id/ , So your last method argument treated as a id. so create method in controller with the default argument Ex. public function mymethod($method = ''){ /** Your logic goes here */ }
I came from a Rails background thus the question may seem stupid.
In Rails, when we create a Ajax request, then we can update a view by rendering a partial using the javascript selector like the following:
$("#dashboardEmails").html("<%=j render partial: 'emails', locals: {emails: #emails} %>");
How can I do that in Django template? I've tried the following:
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize() + "&submit=connect",
success: function (data) {
if(data['tables'].length > 0){
$('#data-connection-info').html("{% include 'projects/connection_info.html' with data='"data"' %}");
}
console.log(data);
},
error: function (data) {
console.log("Error");
}
});
Here, I want to update the view with a template projects/connection_info.html, also passing a javascript variable (data) to the template using with. But it is not working.
Any idea how can I achieve that?
UPDATE
I passed the template from the view like:
template = render_to_string('projects/connection_info.html', json_data)
return HttpResponse(json.dumps(template), content_type='application/json')
Then in the ajax success function updates the DOM:
success: function (data) {
$('#data-connection-info').html(data);
}
In this way the problem is solved. :)
I passed the template from the view like:
template = render_to_string('projects/connection_info.html', json_data)
return HttpResponse(json.dumps(template), content_type='application/json')
Then in the ajax success function updates the DOM:
success: function (data) {
$('#data-connection-info').html(data);
}
In this way the problem is solved. :)