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. :)
Related
I'm beginner in asp.net mvc,write this java script code for fetch any data from controller:
$.ajax({
url: '#Url.Action("CallService", "MyScore")',
type: 'GET',
dataType: 'json',
cache: false,
data: {
'id': 29
},
success: function(color) {
//alert(color);
},
error: function() {
alert('Error occured');
}
});
and write this action in controller:
[HttpGet]
public ActionResult CallService(string id)
{
var idNum = Convert.ToInt32(id);
string color = idNum.ToString();
ViewBag.Myfamily = "razzaqi";
return Json(color, JsonRequestBehavior.AllowGet);
}
in view page write this code:
<h1> Hello Dear #ViewBag.Myfamily</h1>
when i run the project <h1> Hello Dear #ViewBag.Myfamily</h1> not show me ,but i think show me this output:
Hello Dear razzaqi
You are returning JSON not ViewBag. You need to send the "razzaqi" to as part of JSON object. Set up HTML as
<h1> Hello Dear <span id='familyname'></span></h1>
Modify You controller to return myfamily as part of JSON object.
[HttpGet]
public ActionResult CallService(int id)
{
string color = id.ToString();
return Json(new {
color = color
myfamily = "razzaqi"
}, JsonRequestBehavior.AllowGet);
}
Consume the result like
$.ajax({
url: '#Url.Action("CallService", "MyScore")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': 29 },
success: function (data) {
$('#familyname').text(data.myfamily)
},
error: function () {
alert('Error occured');
}
});
The Viewbag object is filled into the view, server side when making the view. Your ajax call contacts the server asking about Json data after the view is already made.
So you are too late passing objects to your viewbag if you do it this way...
There are however some workarounds/solutions for this problem:
Let the Controller return the variable in the Json it's returning.
Simple, efficient way to get the data you need
Html helpers etc. Won't work however and sometimes you just need that horrible viewbag...
Reload a partialview when doing the ajax call.
Takes more time to implement, You'll have to create a new action and partialview.
Good when you want more content to change on the call and want to use html helpers etc.
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 just start using Laravel 5 and i'm facing a problem to send Ajax json data from the view to controller ..
This is my routes.php :
Route::post('ticket','TicketController#store');
Route::get('ticket', 'TicketController#index');
and this is the controller :
public function store()
{
return Response::json(Input::get('ticketname'));
}
and Finally for the View i have this simple example to pass just one input :
<script>
$(document).ready(function() {
$('#go').on("click",function(){
var ticketname= ($('.tick_name').val());
$.ajax({
url: 'ticket',
type: 'POST',
data: {ticketname:$('.tick_name').val()},
dataType: 'json',
success: function(info){
console.log(info);
}
});
});
});
**IM ALWAYS GETTING THIS ERROR : localhost:8000/ticket
500 Internal Server Error on jquery.js line 4 ..**
CAN anyone help please !
Response is an alias in the global namespace. Since you're current namespace is App\Http\Controllers you have to import the class:
use Response;
Or prepend a backslash:
return \Response::json(Input::get('ticketname'));
I am trying to create a simple web link toggle for following or unfollowing a question in my app. I got close using the info My Own Like Button: Django + Ajax -- How? but am not quite there.
My problem is that I cannot dynamically pass question.id to my JS function as the answer in the above link implies. Ie
The hard-wired JS code below DOES work. It passes '12' as a valid param for the view tied to /question/follow-unfollow-inline/. But when I try to replace '12' with a context variable '{{ question.id }}' from the template that calls this JS code, my function passes the string '{{ question.id }}' back to /question/follow-unfollow-inline/ rather than it's value. How do I fix this?
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': '12' },
success: function (e) {
alert('Success!');
}
});
});
});
For now, I'm using #csrf_exempt on my view, but I know I should pass it as data.
You could define it on your anchor tag with data- attribute:
Template:
<a id="follow_unfollow_toggle" href="#" data-qid="{{ question.id }}">Like</a>
Js file:
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': $(this).data('qid') },
success: function (e) {
alert('Success!');
}
});
});
});
I'm new at Laravel and ajax. I'm trying to get the data from a form via ajax and calling a method in the controller via that same ajax. The method in the controller searches the database and then returns a json response that gets handled by ajax(that last part I'm still thinking about, I haven't really done it yet).
Let me show you what I have now:
Routes.php:
Route::get('/', 'HomeController#getIndex');
Route::post('/', 'HomeController#postIndex');
HomeController:
public function getIndex()
{
return View::make('index');
}
public function postIndex()
{
$match = Input::get('search');
$results = Customers::where('name', 'like', '%'.$match.'%')->get();
return Response::json(array('results' => $results));
}
And my index.blade.php View :
<script>
$(document).ready(function() {
$('form#find').submit(function() {
$.ajax({
url : 'CustomerSearch/Public',
type: 'post',
dataType: 'json',
data: $('form#find').serialize(),
});
return false;
});
});
and the form:
{{ Form::open(array('url' => '', 'method' => 'POST', 'id' => 'find')) }}
{{ Form::text('search', '', array('class' => 'search-query', 'placeholder' => 'Search')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-info')) }}
{{ Form::close() }}
So I should be getting the data from the form then sending it to the "postindex" method in the controller so it gets processed and then sent back, right? Except I get the error "Controller method [index] not found." when I don't actually call any index method since they are both named differently.
I'm new at this so sorry if it's not clear.
UPDATE:
Like I said in the commentaries, I found out combining the route into a route::controller got rid of my previous problem but unfortunately I'm still unable to get the ajax to send data to my controller. I get no errors, but the ajax doesn't load anything to the controller. Any idea what might be wrong with my ajax?:
$(document).ready(function() {
$('form#find').submit(function() {
$.ajax({
url : '{{URL::to('/')}}',
type: "POST",
dataType: 'json',
data: { search: $('.search-query').val() },
success: function(info){
console.log(info);
}
});
return false;
});
});
Just use in your controller:
return json_encode(array('key' => 'val'));
For the input of data, I moved to a JQuery plugin that works nicely for me. Follow this link.
This is how a function looks like:
function someName(){
// A plugin is used for this function
$('#form_id').ajaxForm({
url: '/',
type: 'post',
dataType: 'json',
success: function(response){
alert(response.key);
}
});
}
and the corresponding form:
<form id="form_id">
<!-- Put your fields here -->
<input type="submit" onclick="someName()">
</form>
I would suggest you use this method, which may depend on the plugin but is the simplest. Of course, you could use the .submit() statement instead of binding it to the onclick event