Why my database-ajax call and the buttons are not working? - ajax

guys, I try to create a simple full stack application including the database. The users can delete the form row easily. However, I checked my ajax and view file, there is nothing wrong why I got
jquery.min.js:2 DELETE http://localhost:3000/delete/[object%20Object] 404 (Not Found)
send # jquery.min.js:2
ajax # jquery.min.js:2
(anonymous) # main.js:6
dispatch # jquery.min.js:2
v.handle # jquery.min.js:2
main.js:14 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
jquery.min.js:2 XHR failed loading: DELETE "http://localhost:3000/delete/[object%20Object]".
AJAX:
$(document).ready(function () {
$("#Delete-button").on('click',function(){
var id = $(this).data(id);
var url = '/delete/' + id;
if(confirm('Delete Recipe?')){
$.ajax({
url: url,
method: "DELETE",
success: (result)=>{
console.log("Sucess! Deleting the item!");
window.location.href = '/';
},
error:(err)=>{
console.log(err);
}
})
}
})
});
index.html file
<button id = "Delete-button" type="button" class="btn btn-danger" data_id = "{id}">Delete</button>

jquery.min.js:2 DELETE http://localhost:3000/delete/[object%20Object] is the issue.
The problem is : var id = $(this).data(id); which give you an object.
I suggest you to use var id = $(this).attr("data_id"); instead.
You should see this tho : https://api.jquery.com/jQuery.data/
Hope it helped.

The issue is in Delete
how is the id value populated
Also the below statement, doesn't return a plain string but rather an object.
var id = $(this).data(id);
in the below statement
jquery.min.js:2 DELETE http://localhost:3000/delete/[object%20Object] 404 (Not Found)
[object%20Object] <- This is what is the issue

Related

parsererror and Unexpected token < in JSON at position in ajax and django?

please look into below code
AJAX FUNCTION
<script>
$(document).ready(function() {
$("#id_module").on('change', function(){
var mod1 = $(this).val();
alert(mod1);
$.ajax({
url: 'submodule/'+ mod1,
type:'GET',
dataType:'json',
success: function(response){
alert(JSON.stringify(response));
submod=response['submod'];
alert(submod);
$('#submodule').empty();
$("#submodule").prepend($('<option>',
{
value: '',
text: '-- Select Sub Module Type --'
}));
$.each(submod, function(ind){
$("#submodule").append($('<option>',
{
value: submod[ind]['sub_module'],
text: submod[ind]['sub_module']
}));
});
$('#submodule').selectpicker("refresh");
}
});
});
});
</script>
My Django -- URL:
from django.urls import re_path
from django.conf import settings
from django.conf.urls.static import static
from E_Ticketing import views
urlpatterns = [re_path(r'^eForm/report$',views.reports{'template_name':'reports.html'},name='report'),re_path(r'^eForm/resolution$',views.resolutionForm{'template_name':'Resolution_Form.html'},name='resolution'),
re_path(r'^eForm/assign$',views.assignForm,{'template_name':'assign_form.html'},name='assign'),
re_path(r'^eForm',views.eticket, {'template_name':'e_ticket_form.html'},name='eticket'),
re_path(r'^eForm/submodule/(?P<n_moduleid>\d+)$',views.submodule,name='submodule'),
re_path(r'^eForm/fillemp/(?P<n_empid>\d+)$',views.fillemp,name='fillemp'),
]
if settings.DEBUG:
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
My Django --Views:
def submodule(request,n_moduleid):
try:
if request.method=='GET':
submod=[]
submod=TblTxEticketdetails.objects.using('ETicketing').values('sub_module').filter(Q(module_id=n_moduleid)).distinct()
else:
messages.error(request, 'Error Occurred!!!')
data = {'submod': list(submod)}
return JsonResponse(data, safe=False)
except Exception as e:
messages.error(request, "Error Occured!!!")
This is my first time pasting question in stack overflow.I think i have messed up posting my question. please fell free to ask questions regarding code
i have gone through all of my code and i couldn't find where my code is wrong. while running, alert box appears but it does not go to ajax function. i need little help please!!!
i am getting error in this way
text status: parsererror
eForm:1676 error: SyntaxError:Unexpected token < in JSON at position 0
sorry guys,
I found the answer,
in url.py I have changed
re_path(r'^eForm',views.eticket{'template_name':'e_ticket_form.html'},name='eticket'),
to
re_path(r'^eForm$',views.eticket,{'template_name':'e_ticket_form.html'},name='eticket'),
after '^eForm' have to add '$' while excetuting ajax, it is going to other views. so i am not getting the correct answer
Thanks guys for responding to my question:)

Django - Making an Ajax request

Im having a hard time figuring out how to integrate this ajax request into my view. I'm still learning how to integrate django with ajax requests.
My first question would be: Does the ajax request need to have its own dedicated URL?
In my case I am trying to call it on a button to preform a filter(Preforms a query dependent on what is selected in the template). I have implemented this using just django but it needs to make new request everytime the user preforms a filter which I know is not efficient.
I wrote the most basic function using JQuery to make sure the communication is there. Whenever the user changed the option in the select box it would print the value to the console. As you will see below in the view, I would to call the ajax request inside this view function, if this is possible or the correct way of doing it.
JQuery - Updated
$("#temp").change( function(event) {
var filtered = $(this).val();
console.log($(this).val());
$.ajax({
url : "http://127.0.0.1:8000/req/ajax/",
type : "GET",
data : {
'filtered': filtered
},
dataType: 'json',
success: function(data){
console.log(data)
},
error: function(xhr, errmsg, err){
console.log("error")
console.log(error_data)
}
});
Views.py
def pending_action(request):
requisition_status = ['All', 'Created', 'For Assistance', 'Assistance Complete', 'Assistance Rejected']
FA_status = RequisitionStatus.objects.get(status='For Assistance')
current_status = 'All'
status_list = []
all_status = RequisitionStatus.objects.all()
status_list = [status.status for status in all_status]
# This is where I am handling the filtering currently
if request.GET.get('Filter') in status_list:
user_req_lines_incomplete = RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status=request.GET.get('Filter')))
current_status = request.GET.get('Filter')
else:
user_req_lines_incomplete = RequisitionLine.objects.filter(parent_req__username=request.user).exclude(status__status='Completed')
user_reqs = Requisition.objects.filter(par_req_line__in=user_req_lines_incomplete).annotate(aggregated_price=Sum('par_req_line__total_price'),
header_status=Max('par_req_line__status__rating'))
return render(request, 'req/pending_action.html', { 'user_reqs':user_reqs,
'user_req_lines_incomplete':user_req_lines_incomplete,
'requisition_status':requisition_status,
'current_status':current_status,
'FA_status':FA_status})
def filter_status(request):
status = request.GET.get('Filter')
data = {
'filtered': RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status=status)),
'current_status': status
}
return JsonResponse(data)
Urls.py
path('pending/', views.pending_action, name='pending_action')
First: you have to divide your template to unchangeable part and the part that you want to modify with your filter.
Second: for your goal you can use render_to_string. See the followning link https://docs.djangoproject.com/en/2.1/topics/templates/#usage
code example (views.py):
cont = {
'request': request, #important key-value
'your_models_instances': your_models_instances
}
html = render_to_string('your_filter_template.html', cont)
return_dict = {'html': html}
return JsonResponse(return_dict)
In your js file you need to determine relative url "{% url 'name in yours url file'%}"
And in success you need to add next line:
success: function(data){
$(".filter-block").html(data.html);
}
i hope it will help you! Good luck!

Django Ajax Form Works but Throws 500 (Internal Server Error)

I've researched this to death, but have not found exactly what I need to get the last part of my form completed.
I have a simple 2-field form in my footer for newsletter signup. I am utilizing an inclusion_tag since I need to include the form on every page.
The form works; with a couple of hitches, for arguments sake, it works, I hit submit and the email is sent to me. The problem is that I am getting a 500(internal server error) in console on the ajax url. I am assuming that its not really supposed to redirect to the url, but rather just process the form. Below is my code; I hope someone can easily point out my issues. Thanks.
Inclusion Tag
#register.inclusion_tag('includes/cta_form.html', takes_context=True)
def footer_newsletter_signup(context):
title = 'Newsletter Signup'
form = CTASignupForm()
context = {
'form': form,
'title': title,
}
return context
Ajax
$('#sendSignupForm').click(function (e) {
e.preventDefault();
var mForm = $('#signupForm').serialize();
console.log(mForm);
$.ajax({
type: 'POST',
url: '{% url 'pages:cta_signup' %}',
data: mForm,
success: function (data) {
$("input").val('')
},
error: function (data) {
$("input").addClass('error')
}
})
})
cta_form.html
<form action="{% url 'pages:cta_signup' %}" method="POST" id="signupForm">
{% csrf_token %}
{{ form.name }}
{{ form.email }}
<button class="btn btn-black no-margin-bottom btn-small" type="submit" id="sendSignupForm">Submit</button>
</form>
View
def cta_signup(request):
if request.method == "POST":
form = CTASignupForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
subject = 'This is a response from Soledad Footer Signup Form'
from_email = settings.DEFAULT_FROM_EMAIL
recipient_list = [from_email, 'charles#netfinity.net']
ctx = {
'subject': subject,
'name': name,
'email': email
}
message = get_template('email_forms/cta_signup_email.html').render(Context(ctx))
msg = EmailMessage(subject, message, from_email=from_email, to=recipient_list)
msg.content_subtype = 'html'
msg.send()
messages.success(request, "Thank you, we received your message")
if form.errors:
json_data = json.dumps(form.errors)
return HttpResponseBadRequest(json_data, content_type='application/json')
else:
raise Http404
Screenshot of Console Error
A view must always return a response. You don't, if the form is valid; that's a server error.
Return HttpResponse() at the end of the is_valid block.

dojo.xhrpost getting status code as 0

I am submitting a for using dojo's xhrpost. My app runs on ruby on rails. In the controller I am performing a redirect. I store the redirected URL the response headers. I access the redirected URL on the client and then load the redirected URL on the client. The following is the code.
In the view, performing ajax submit using dojo.xhrpost
function () {
var form = dojo.byId("form_id");
dojo.connect(form, "onsubmit", function(event){
// Stop the submit event since we want to control form submission.
dojo.stopEvent(event);
var xhrArgs = {
form: dojo.byId("form_id"),
handleAs: "text",
load: function(data, ioargs){
//getting redirected url from response header
var new_url = ioargs.xhr.getResponseHeader("new_url");
//redirecting to the url
document.location.href = new_url;
},
error: function(response){
//handling error
}
}
//submitting for to action1 of controller
var deferred = dojo.xhrPost(xhrArgs);
});
}
Code in controller
def action1
new_url = url_for(:controller=>"controller", :action => "action2")
#passing the new URL as parameter in the redirection
redirect_to :action2, :new_url => new_url
end
def action2
#getting the new url from the params and saving it in respone header so that it can be accesses in client
response.headers["new_url"] = params[:new_url]
end
This worked fine on my local host. But when I put it on my server its failing.
I am getting the ioargs.xhr.status as "0". data is " ". Though the form is getting saved response is empty and no response headers are getting set.
Please Help.
I had to modify the controller a bit.
def action1
if request.xhr?
render :json => new_url.to_json
else
#follow normal redirection
redirect_to :action2
end
Also in the ajax call
var xhrArgs = {
form: dojo.byId("form_id"),
handleAs: "json",
load: function(data, ioargs){
//getting redirected url from data
document.location.href = data;
},
error: function(response){
//handling error
}
Basically I found out returning the entire HTML page as response in not the right way.
Only the URL should be returned in the response and redirection should be done from the View,

jQuery AJAX request error status 0

I've been developing an application locally and am running into trouble on the actual server.
Whenever I submit an AJAX request with jQuery it gives me an error with error status:0 and and statusText: 'error'.
The Chrome inspector doesn't even show a response code for the request, it just says failed.
When I inspect it closer, I notice that all of the data was sent and the PHP file actually processed it. For example, in the request below, the user was indeed created. The bad response code is preventing other requests from executing (since they depend on a 'successful' response).
Here is a sample request:
var cct = $.cookie('ttc_csrf_cookie'); // csrf protection
var sUrl = "<?= base_url(); ?>user/create/";
var serialized = {
name: me.name,
email: me.email,
oauth_provider: 'facebook',
oauth_uid: me.id,
ttc_csrf_token: cct
};
$.ajax({
url: sUrl,
type: "POST",
data: serialized,
error: function(someStuffHere) {
//* THIS CODE RUNS. SHOWS ERROR STATUS: 0 */
},
success: function(user_id) {
//******** THIS HERE NEVER RUNS ***********///
}
});
And here is the corresponding PHP code:
public function create() {
if($this->input->post()) {
$user['name'] = $this->input->post('name');
$user['email'] = $this->input->post('email');
$user['oauth_provider'] = $this->input->post('oauth_provider');
$user['oauth_uid'] = $this->input->post('oauth_uid');
$user['last_activity'] = date('Y-m-d H:i:s');
$user_id = $this->Users->create_user($user);
$this->session->set_userdata('user_id', $user_id);
echo $user_id;
}
}
These two snippets are only an example. All AJAX requests won't work on the live sever.
What could it possibly be? Thanks!
UPDATE: I've narrowed it down and the issue occurs when echo'ing a result. When I comment out the echo, no error is thrown (but, of course, no result is sent).
Turns out that the issue was caused by the compress_output option in CodeIgniter. When it's set to true, the echo's don't work. Thanks for everyone that tried to help!

Resources