A part of the django view which is executed is as follows:
def traxio_advice(request):
.......
.......
elif calculation['statusCode'] == 400:
response = JsonResponse({'message': 'The calculation is not available! Please try another mileage.'}, status=500)
return response
And in django template I have ajax call as follows :
$.ajax({
type: 'POST',
url: '{% url 'traxio_advice' %}',
data: {
firstname: $('input[name=firstname]').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
......
},
error: function (data) {
var message = $.parseJSON(data.responseText).message;
$('#calculation-error').removeClass('hidden').html(message)
},
beforeSend: function () {
$('#result-content').html('<div class="loader"></div>');
}
})
The problem is in the error function. I get what I want, thus, the data is correct.
message = "The calculation is not available! Please try another mileage."
But the message isn't showing in the div with the id calculation-error.
Instead I see the loader from the beforeSend function on the screen and in the console I get
POST http://127.0.0.1:8000/master/traxio_advice/ 400 (Bad Request)
What am I missing?
Just for the info, If anyone else would have a similar problem.
Actually the problem was in the beforeSend function and the template .
The div with id #calculation-error (where I wanted to show the error) was inside the div with id #result-content.
But in the beforeSend function I replaced the content of the div with the id #result-content.
Thus in the template like this :
<div id="result-content">
<div class="loader"></div>
</div>
I tried to show error in the div with the id #calculation-error. It couldn't be shown because that div doesn't exist.
Related
Im using JaxaScript(Jquery with Ajax) and my HTML Page all in the same file, but when I tried to code my JS and HTML in different files, I get an error when trying to ajax with Django.
JS:
$(document).on('click', '#add-button', function (e) {
e.preventDefault();
value = $(this).data("forloopcounter");
value = value - 1
let variation_id = document.getElementsByClassName("select-variations")[value].attributes[2].nodeValue
console.log(variation_id)
$.ajax({
type: "POST",
url: '{% url "cart:add" %}',
data: {
variationid: variation_id,
productquantity: 1,
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post'
},
success: function (json) {
document.getElementById("cart-quantity").innerHTML = json.quantity
},
error: function (xhr, errmsg, err) {
console.log(xhr)
}
});
})
Note: I have a guess it's because of this url: '{% url "cart:add" %}', but I don't know how to fix.
Note: when I ajax with all in the same page it works.
Note it's not an importation error, when i execute console.log it
works
Error I get in the web:
`jquery.min.js:4 POST http://127.0.0.1:8000/%7B%%20url%20%22cart:add%22%20%%7D 404 (Not Found)
HTML:
{% for variation in product.variation_set.all%}
{%if forloop.first%}
<!--pra fazer ajax passando id da variação selecionado(não aparece pra usuário)-->
<small id="select-variations1" class="small select-variations"
value="{{variation.id}}"></small>
{%endif%}
{%endfor%}`
My template.html:
...
<button class="btn btn-success" onclick="save_post(event, 'publish')">Publish</button>
...
My javascript.js:
function save_post(event, action) {
event.preventDefault();#new line
var tag_string=document.getElementById('id_tags').value;
if (action=='publish' || action=='draft') {
var url_post='/blog/post/new/'
} else {
var url_post='/blog/post_edit/'
};
$.ajax({type: 'POST',
url: url_post,
data: {
tagstring: tag_string,
action: action
},
success: function (lista) {
//code
}
});
};
My views.py:
#staff_member_required
def post_new(request):
context_dict=[]
if request.method == "POST":
if request.is_ajax():
#code
...
else:
form = PostForm()
return render(request, 'blog/post_edit.html', context_dict)
My url.py:
app_name = 'blog'
urlpatterns = [
...
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
...
My views is called by the url (browser), then the button call a javascript function and it call (with ajax) again the same view, this time with request.method = "POST" and this works, but request.is_ajax() gives False.
For call post_edit (probabily) I need the id of the post. Where can I get it?
Should I pass it to save_post() from the template?
Edit: ignore these lines below
Also should I use preventDefault() somewhere?
Thank you
Edit: now I use preventDefault() but it gives this error:
Not Found: /blog/post_new/
[26/Jan/2018 19:07:20] "POST /blog/post_new/ HTTP/1.1" 404 10871
and ajax dosn't call the view. Edit: I solved this problem, but I continue tomorrow :)
Your Ajax code some problems and view is correct
I have attached my Code attached Image and code
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myajaxview', // the url where we want to POST
data :{
'csrfmiddlewaretoken': '{{csrf_token}}',
'text': text,
'search': search,
'email': email,
'url': url,
'telephone': telephone,
'password': password,
'number': number,
},
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
I am using Ajax call for upload file in server. So I want to show success & failure message as per file upload
$.ajax({
url: "https:my_url",
data: {my data: my_data},
method : "POST",
success: function(result) {
alert(result);
},
error: function(error){
alert("Error in File Upload");
}
});
And using this in react component
<input id="file-input" type="file" className="fileInput" onChange=
{this.myfile} multiple />
So help me out for print message as bootstrap or any good way i.e.
need to be as below
<div class="alert alert-success">
<strong>Success!</strong> You should <a href="#" class="alert-
link">File uploaded </a>.
</div>
Have a CSS class invisible like this
.invisible{
display:none;
}
And then have a state variable uploaded with initial value anything say uploading
this.state = {uploaded:'uploading'}
Then create the two alert messages
<div className=`alert alert-success ${this.state.uploading === 'success'?'':'invisible'}`>
<strong>Success!</strong> You should <a href="#" class="alert-
link">File uploaded </a>.
<div className=`alert alert-danger ${this.state.uploading === 'failure'?'':'invisible'}`>
<strong>Failure!</strong> Failed <a href="#" class="alert-
link">File uploaded </a>.
</div>
What is happening here is that the success message only gets displayed when this.state.uploading is equal to 'success' and the failure message when it is equal to 'failure'.
And then in the ajax call
$.ajax({
url: "https:my_url",
data: {my data: my_data},
method : "POST",
success: (result) => {
this.setState({uploading:'success'})
},
error: (error) => {
this.setState({uploading:'failure'})
}
});
The ajax call sets the this.state.uploading to success or failure depending on the result of the ajax call and the appropriate message is displayed.
For ES5 style
var _this = this
$.ajax({
url: "https:my_url",
data: {my data: my_data},
method : "POST",
success: function (result) {
_this.setState({uploading:'success'})
},
error: function (error) {
_this.setState({uploading:'failure'})
}
});
I'm trying to consume a mashape api using ajax, javascript.
I have a text area and a button in my html :
<div>
<textarea id="message" placeholder="Message">
</textarea>
<br><br>
<button id="mb" onclick="success();">Analyse</button>
</div>
And a really simple javascript success() function :
function service(){
$.ajax({
url: 'https://loudelement-free-natural-language-processing-service.p.mashape.com/nlp-text/', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
type: 'GET', // The HTTP Method
data: {text: $("#m").val()}, // Parameters go here
datatype: 'json',
success: function (data) {
alert(data);
},
error: function (err) {
alert(err);
},
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "<MY MASHAPE KEY>"); // Enter your Mashape key here
}
});
};
however when i trigger the function, the following error is displayed in my browser console :
ReferenceError: success is not defined
Any idea on how to solve this error ?
The function success() dosn't exist however you have a service() function either you change the invocation success() -> service() or you change the function name from function success -> function service
I have a list containing news articles in the backend of a site which is then displayed on a homepage. I'd like the homepage to always display the most recent news.
I've never used AJAX before but in pseudo it would need to do the following:
call the homepage using an AJAX-get
Compare the article div with the same div from the AJAX-get.
If the AJAX-get has different content inside the div, display that
Can I do this with Jquery load, or do I need to go into AJAX for this functionality. and if so, could anyone give me a hand with the AJAX itself
trying to use AJAX, i have started using the following code, to no avail
$.ajax({
url: ctx.HttpRoot,
data: { "id": $("newsSliderWrapper").attr("id") },
success: function (data) {
data = $(data).find('div#newsSliderWrapper')
alert(data)
},
error: function () {
// your error logic
alert("AJAX failed");
}
})
AJAX in your case will do the following:
Ajax call will send the recent article ID to the server.
The server will compare the article ID. If the article ID is different, then the server will return the new article content. If the id is same, return different status message.
Ajax call will simply render the content
So
$.ajax({
url : "backendurl",
data : {"id" : $("recentarticleDivId").attr("id")},
// id must be the article ID which you need to match
success : function(data) {
$("#articleDivId").html(data);
},
error : function() {
// your error logic
}
})
$.ajax({
url: "homepage.php",
type: "GET",
data: { id : article_id },
success:function(data){
console.log(data);
// your logic
},
error:function(){
}
});