I have ths code tyng to make a call to my django backed using ajax
but it gives me this error: Reverse for 'delete_skill' with arguments '('',)' not found. 1 pattern(s) tried: ['jobs/delete_skill/(?P[0-9]+)$']
<a href="{% url 'freelance:delete_skill' id_number %}"
class="glyphicon glyphicon-trash delete_skill"
style="padding:0px; margin:0px; background:grey;
color:red; border:0px;" id="{{skill.id}}"></a>
</span>
{% endfor %}
{% endif %}
<script>
$(document).ready(function() {
$(".delete_skill").click(function(){
var id_number = this.id;
alert(id_number);
$.ajax({
type: 'DELETE',
url: "{% url 'freelance:delete_skill' id_number %}",
dataType: "json",
data: 'identifier='+id_number, 'csrfmiddlewaretoken': '{{ csrf_token }}
success: function(){
if(data) {alert("Success! skill has been deleted")}
});
});
});
my url is like this
url(r'^delete_skill/(?P<identifier>[0-9]+)$', views.delete_skill, name='delete_skill'),
any help on what is going on or what I should add please
Ok, to help you move forward, here a principle that I use:
Create data-* attribute for href such as data-href. You can read more about data-* attributes here.
<a href="#" data-href="{% url 'freelance:delete_skill' skill.id %}"
class="glyphicon glyphicon-trash delete_skill" style="padding:0px; margin:0px;
background:grey; color:red; border:0px;" id="{{skill.id}}"></a>
You can access this data-href attribute in javascript with getAttribute() or via dataset property. Below is jQuery example since you're using jQuery already.
$(".delete_skill").click(function() {
var url = $(this).attr("data-href");
$.ajax({
type: "DELETE",
url: url,
dataType: "json",
data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
success: function(data){
if(data) {
alert("Success! skill has been deleted");
}
}
});
});
This way your code won't break when you change urls.
Related
Picture 1 Picture 2 Picture 3 I am building a page in Django that first renders a blank page with a loading picture, and then calls an Ajax get function to one of my views. Once my Ajax get function succeeds, it is supposed to load one of my HTML files. I get a 404 error saying that the template cannot be found, but the template is in the same folder as my other file. Is my file path wrong?
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
{% extends "stocks_sites/base.html" %}
<!-- The loading image -->
{% block loader %}
<div id="loading">
<p>Loading</p>
</div>
<div id="articles">
</div>
<script>
// AJAX call when page has loaded
$(document).ready(function(){
$.ajax({
type: "GET",
url: "{% url 'stocks_sites:get_news_articles' %}",
success: function(response) {
const news_articles = response;
const posts = news_articles.posts;
const search = news_articles.search;
document.getElementById("loading").style.display = "none";
$("#articles").load("news_articles.html");
}
});
});
</script>
{% endblock loader %}
I am working on GitHub Pages with Jekyll. The Disqus code is located in _includes/disqus.html and has the following code:
<div class="comment">
<button class="show-comments"><i class="fa fa-comments" aria-hidden="true"> Load/Add comments</i></button>
<div id="disqus_thread"></div>
</div>
<script src={{ "/js/jquery.min.js" | prepend: site.baseurl }}></script>
<script>
$(document).ready(function() {
$('.show-comments').on('click', function(){
var disqus_shortname = '{{site.disqus-shortname}}';
$.ajax({
type: "GET",
url: "http://" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
$(this).fadeOut();
});
});
</script>
In the layouts folder I have a blue.html file with the following code for Disqus:
{% include disqus.html %}
{% else %}
{% endif %}
And in the config.yml I noted my Disqus short name:
#comments disqus-shortname: eudemonis
But nothing of Disqus is loaded when clicking on the load comment section, see test post.
With or without the YAML front matter set as comments: true it doesn't work in neither Safari nor Chrome. I'm seriously at a loss.
I already tried a complete new file following Disqus documents with the Universal code but it doesn't work. Changing the Liquid tags manually with my Disqus short name also doesn't work.
I think the problem is that your website is hosted with HTTPS but you are linking to Disqus with HTTP protocol in your _includes/disqus.html:
$.ajax({
type: "GET",
url: "http://" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
Error from Chrome console (hit F12 and see):
Mixed Content: The page at 'https://eudemonis.github.io/blog/test//' was loaded over HTTPS, but requested an insecure script 'http://eudemonis.disqus.com/embed.js'. This request has been blocked; the content must be served over HTTPS.
To solve this, change the protocol to HTTPS:
url: "https://" + disqus_shortname + ".disqus.com/embed.js",
Or leave the protocol out and let the browser decide:
url: "//" + disqus_shortname + ".disqus.com/embed.js",
I am getting the JSON object back TO the HTML request (I am using GlassFish on localhost just to demo). I am not, however, able to display any of my JSON objects. (I am a rookie when it comes to HTML.)
Here is my attempt at HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<title>Dss</title>
<script>
function onSubmit() {
alert(document.getElementById('text').value);
$.ajax({
url: 'rest/dss/acceptInput',
type: 'GET',
dataType: 'jsonP',
data: {'UserInput': document.getElementById('text').value },
statusCode: {
200: function(data) {
alert(data);
$.each( data.items, function(item ) {
alert(item.Type);
$( "<p>" ).attr( "value", item.Type ).appendTo( "#Test" );
});
},
404: function() {
alert("Page NOT found");
}
},
done: function(data) {
alert("NOPE" + data);
$.each( data.items, function(item ) {
alert(item.Type);
$( "<p>" ).attr( "value", item.Type ).appendTo( "#Test" );
});
}
});
alert("at the end");
};
</script>
</head>
<body style="background-color:black;">
<img src="http://i.imgur.com/97.png" alt="DSS_Thumbnail" style="display: inline;width:120px;height:120px;">
<h1 style="display: inline;color:rgb(241,85,50)">Search for details:</h1>
<br>
<input id="text" type="text" name="UserInput" value="Enter search criteria">
<br>
<button id="submit" onclick="onSubmit()" type='button'>Submit</button>
<br><br>
<div id="Test"></div>
</body>
</html>
I run this in the Chrome browser, and the alerts show me the object Object returns within the status code 200. I am not sure HOW to display this information... I thought I had it, but I have tried for a few hours.
After running the HTML I receive these acknowledgements:
Initial acknowledgement of input:
Acknowledgement of finish:
Displaying the object after status code 200 received:
I understand that it is asynchronous which is why I would get them out of order, but what do I do with said object Object?
What do i have to add to the HTML file to display the JSON to the current page? (Or even populate a new page with the information on it?)
I've been trying to convert an HTML form into Json. When I submit the form my alert is just returning an empty array. Any help is greatly appreciated!
Here is the form
<form action="" method="post" name="myForm">
Code (xxxx-xxx):<input type="text" name="drugcode" /> <br/>
<p><input type="submit" onClick='submitform()' /></p>
</form>
And here is the javascript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script language ="javascript" type = "text/javascript" >
function submitform() {
var formData = JSON.stringify($("form[name*='myForm']").serializeArray());
alert(formData);
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json",
processData: false
});
}
</script>
All that this is returning is:
[]
EDIT:
It now returns:
[{"name":"code","value":"1234"},{"name":"blah","value":"4321"}]
how would I would I have it return:
{"code":"1234","value":"4321"}
$("#myForm") is not going to match the form for you. # specifies an id. You need to match on the name:
$( "form[name='myForm']" )...
You can also use simple javascript and select the form using
document.querySelector("form[name='myForm']")
or
document.forms[0]
New to ajax and sorry for asking such a basic question. I am using ajax:
to submit a form (written in python)
to conduct some calculation and generate output page, and
to redirect the browser to the output page
Currently, Steps 1 and 2 are done, but when the browser tries to redirect, I got a 405 error. I appreciate any suggestions.
HTML form
<form method="post" id="form1">File to upload:
<input type="file" id="upfile1" name="upfile" class="required input_button" accept=".csv" />
<input class="submit_button" type="button" value="Submit" />Upload the file!
</form>
JS code
$('.submit_button').click(function () {
var form_data = new FormData();
$.each($('input[name^="upfile"]')[0].files, function (i, file) {
form_data.append('file-' + i, file);
});
$.ajax({
type: "post",
url: "/geneec_batchoutput.html", ///////NOTE 1/////////
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function () {
window.location = '/geneec_batchoutput.html'; ///////NOTE 2/////////
},
error: function (data) {
console.log('error');
}
});
});
NOTE 1
Form firebug, I can tell the calculations have been finished and the output page is generated.
NOTE 2
Here is the place I got 405 error. So my guess is ajax did not redirect the browser to the "correct" output page, instead it let the browser go to a generic one. So without data support, I got 405 error.
So it seems like my question is how to redirect the browser to the output page generated in ###note 1 at location ###note 2.
update
I have attached a "working" scenario, but this is not the real ajax approach, since I use .submit() to send the form.
html form
<form method="post" id="form1" enctype="multipart/form-data" action=geneec_batchoutput.html>File to upload:
<input type="file" id="upfile1" name="upfile" class="required input_button" accept=".csv" />
<input class="submit_button" type="submit" value="Submit" />Upload the file!
</form>
JS code
form.submit();
$.ajax({
type: "post",
url: "/geneec_batchoutput.html",
success: function () {
window.location = '/geneec_batchoutput.html';
}
});
Update 2
I tried to check the content of url by posting it to the console. It looks like the url has everything I need, which is the output page. So temporally I use $("body").html(url); to replace current page content. But the url is still the /geneec_batchinput.html. Is there a way to update the url as well?
$.ajax({
type: "post",
url: "/geneec_batchoutput.html",
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function(url) {
console.log(url)
$("body").html(url);
},
error: function(data) {
alert('error')
}
});
Thanks!
It looks like the location redirect is getting called as a POST request because it's inside the submit action. Try tweaking your submit handler like so:
$('.submit_button').click(function (event) {
event.preventDefault();
// carry on...
so that you can use event.preventDefault to avoid needing to return something from the submit event.
Update:
This may be it. Using your original code:
$('.submit_button').click(function (event) {
event.preventDefault();
// .. blah blah ..
$.ajax({
type: "post",
url: "/geneec_batchoutput.html", ///////NOTE 1/////////
// .. blah blah ..
success: function () {
window.location = '/geneec_batchoutput.html'; ///////NOTE 2/////////
},
error: function (data) {
console.log('error');
}
});
retun false;
});
Because it's asynchronous, the outer event handler is ending before the location change is issued in the success callback function. I thought the preventDefault would avoid the need to return false, but other similar questions suggest not.