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(),
Related
Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py).
My Hmtl form does have a csrf_token, so I added the header in ajax function, but still got 500 internal erorr. The data is saved into database but the response is not sent to ajax function.
View.py
## Ajax
#login_required
def SubmitModal(request):
if request.method == 'POST':
text = request.POST['Text']
date = request.POST['DatePicker']
time = request.POST['TimePicker']
T = SText()
T.User = request.user
T.Text = text
T.STime = date + ' ' + time
T.save()
return HttpResponse(json.dumps({'success': True}), content_type="application/json")
else:
return JsonResponse({'success': False})
file that contains ajax
$(document).ready(function () {
// Show the modal window when a button is clicked
$('#open-modal').click(function () {
$('#modal').modal('show');
});
// Close the modal window when a button is clicked
$('.close-modal').click(function () {
$('#modal').modal('hide');
});
// Handle the form submission
$('#modal-form').submit(function (event) {
event.preventDefault(); // Prevent the form from being submitted
var formData = $(this).serialize(); // Get the form data
// Submit the form data to the server using an AJAX request
$.ajax({
type: 'POST',
url: '/submit/',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: formData,
dataType: "json",
success: function (response) {
if (response.success) {
$('#success-message').show();
} else {
$('#error-message').show();
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
$(".textarea-input")[0].value = '';
$(".date-input")[0].value = '';
$(".time-input")[0].value = '';
});
});
If you're reproducing this in a non-production environment, you can set DEBUG=True in the settings file. Then when you make the call from your browser, the response will include details about what the issue is. You can also set the ADMINS variable to send exception tracebacks to the specified emails when they're encountered. More details here.
You can view the data being sent and received in the developer tools of the browser you are using.
im passing a array data in my ajax to controller and use the data to the queries but when i already return the data it's blank when i alert it but in my network it have a data. Can someone help me about this?
routes:
Route::get('/member/page/press_release_email/view_send_email_press_release/sent_email', 'Member\Press_Release_Controller#pass_id');
ajax:
$.ajax({
type: "GET",
url: "/member/page/press_release_email/view_send_email_press_release/sent_email",
data: {ids:myArr},
dataType:"json",
success: function(data){
alert(data)
}
});
controller:
public function pass_id(Request $req)
{
$emails = Tbl_press_release_recipient::select('research_email_address')->whereIn('recipient_id', Request::input('ids'))->get();
return json_encode($emails);
}
You are trying to select research_email_address with their recipient_id but your ids are currently strings (As seen in your network's tab screenshot.)
You need to fill myArr with the recipient_id data.
I have created different class-based views on Django. On the HTML i created some forms make a request with AJAX. My problem is that it gives me
Method Not Allowed (POST)
I don know if i'm doing it rigth, or if i need to modify something for it to work.
My view.py is something like this
class Landing(View):
def get(self,request):
if request.method == 'POST':
if request.is_ajax():
data = {"lat":20.586, "lon":-89.530}
print request.POST.get('value')
return JsonResponse(data)
return render(request,'landing.html',{'foo':'bar'})
And i send the reques from Javascript
$(document).ready(function() {
$('#productos').on('change', function(e) {
//Call the POST
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var value = $('#productos').val();
$.ajax({
url: window.location.href,
type: "POST",
data: {
csrfmiddlewaretoken : csrftoken,
value : value
},
success : function(json) {
console.log(json);
drop(json);
},
error : function(xhr,errmsg,err){
console.log(xhr.status+": "+xhr.responseText)
}
});
});
});
I got some of the code from a web, but i really don't know how to use it, since they used it without class-based views.
So, What does need my code to accept the POST method?
The dispatch method of a class based view determines which function is called, so far you've written a get function, but no post function so just move the logic into a post function.
class Landing(View):
def post(self,request):
if request.is_ajax():
data = {"lat":20.586, "lon":-89.530}
print request.POST.get('value')
return JsonResponse(data)
def get(self, request):
return render(request,'landing.html',{'foo':'bar'})
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 am trying to implement file upload using ajax with Django but facing some problem.
When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.
{"status": "error", "result": "Something went wrong.Try Again !!"}
Django Version: 1.6.2
Python Version: 2.7.5
Also, testing on Django Development Server.
views.py
def upload(request):
logging.info('Inside upload view')
response_data = {}
if request.is_ajax():
logging.info('Is_AJAX() returned True')
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
logging.info('Uploaded Data Validated')
upload = Upload( upload=request.FILES['upload'] )
upload.name = request.FILES['upload'].name
upload.save()
logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded !!"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "Something went wrong.Try Again !!"
return HttpResponse(json.dumps(response_data), content_type='application/json')
Template
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>
Javascript 1:
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Javascript 2
var options = {
url: '/upload/',
type: "POST",
error: function(response) {
alert('Something went Wrong. Try Again');
},
success: function(response) {
if ( response.status == 'success' ) {
alert('success');
}
}
};
$('#uploadForm').ajaxSubmit(options);
Question:
1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.
2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?
There is another similar question here but with no result.
This works for me. You need a jquery.form.js
$("#uploadForm").submit(function(event) {
$(this).ajaxSubmit({
url:'{% url upload_file %}',
type: 'post',
success: function(data) {
console.log(data)
},
error: function(jqXHR, exception) {
console.log("An error occurred while uploading your file!");
}
});
return false;
});
Here's the similar question here with answers.
Make sure that javascript code block
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.
1) why is_ajax() not working?
Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.
Take a look at http://jquery.malsup.com/form/
If it's already done, you might take a look at the HTTPRequest object
Django Documentation says HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.
2) Why page redirects?
As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()
$('#uploadForm').submit( function (){
$(this).ajaxSubmit(options);
return false;
});
Hope this was helpful :)