I have a function that uses an AJAX request to fetch data from a view and returns data in the form of a list that is in the model.
In my model the data is entered with a new line character, however in my jQuery output the \n character is ignored. Can anyone help?
Data in Model object:
ankit: Hi govind!
go358938: Hi Ankit, how are you ?
Data passed as list to jquery:
{ 'list': 'ankit: Hi govind!\r\ngo358938: Hi Ankit, how are you ?' }
Data visible in Modal :
ankit: Hi govind! go358938: Hi Ankit, how are you ?
$('#chatbox').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var recipient = button.data('whatever')
$.ajax({
url: "{% url 'fetcher' %}",
data: {
'search': recipient
},
dataType: 'json',
success: function (data) {
list = data.list;
$('#chatbox').find('.modal-body').html(list);
}
});
});
Views.py
def fetcher(request):
if request.is_ajax():
name = User.objects.get(username=request.GET.get('search', None))
b = ChatMessage.objects.get(user2 = name)
print(b.message)
data = {
'list': b.message,
}
return JsonResponse(data)
First, what do you mean with "jquery"-output?
Your output in the HTML as Website? Well, "\n" is not considered there as "break" but <br/>.
Your html file technically looks like this:
<div>\n
<p>Whatever</p>\n
<p>Something different</p>\n
</div>
You don't want to count every \n as <br/>.
You have two options:
Print your results inside a html element which supports \n (e.g. <pre>, <code> and <textarea> do) or replace your \n with a <br/>).
Solution 1:
<textarea class="modal-body-content">
This is a new line\nhere
</textarea>
$('#chatbox').find('.modal-body-content').html(list);
Solution 2:
$('#chatbox').find('.modal-body').html(list.replace(/\n/g, '<br/>');
Related
i am creating a simple like button with ajax, i have followed the tutorial but it seems, that i am missing something, i am not getting any error either in the console in my django terminal but when i click the button no data get sent, evrything just remains the same way, and this is not what i am expecting, i know i am missing something somewhere and i cannot really tell where this error is coming from.
views.py
#login_required
def like(request):
if request.POST.get("action") == 'post':
result = ""
id = int(request.POST.get('courseid'))
course = get_object_or_404(Course, id=id)
if course.like.filter(id=request.user.id).exists():
course.like.remove(request.user)
course.like_count -= 1
result = course.like_count
course.save()
else:
course.like.add(request.user)
course.like_count += 1
result = course.like_count
course.save()
return JsonResponse({'result': result})
urls.py NOTE:I don't know if i need a slug in this url path
path('like/', views.like, name="like"),
base.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
course-detail.html
<li><button id="like-button" value="{{course.id}}">like</button><span id="like-count">{{course.llke_count}}</span></li>
<script type="text/javascript">
$(document).on("click", '#like-button', function(e){
e.preventDefault()
$.ajax({
type: 'POST',
url: '{% url 'course:like' course.slug %}',
data: {
courseid: $('#like-button').val(),
csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(),
action: 'post'
},
success: function(json){
document.getElementById("like-count").innerHTML = json['result']
console.log(json)
},
error: function (xhr, errmsg, err)
console.log(xhr)
console.log(errmsg)
console.log(err)
})
})
</script>
this is all the code i have written for the functionality, if there is any other thing to be provided i will update the question
UPDATE AFTER FIRST ANSWER
#####################################################################
Now when i click the like button is does show an visible error but the like count now shows undefined and in my chrome dev tools is shows failed to load response data because this request was redirected
Update your code like this and I've doubt about your like table provide that inside your question.
inside your views.py
#login_required
def like(request):
if request.method == 'POST':
result = ""
course_id = int(request.POST.get('courseid'))
course = get_object_or_404(Course, id=course_id)
if course.like.filter(id=request.user.id).exists():
course.like.remove(request.user)
course.like_count -= 1
result = course.like_count
course.save()
else:
course.like.add(request.user)
course.like_count += 1
result = course.like_count
course.save()
return JsonResponse({'result': result})
inside your course-detail.html
<script type="text/javascript">
$("#like-button").on("click", function (e) {
e.preventDefault()
$.ajax({
type: 'POST',
url: "{% url 'course:like' %}",
data: {
courseid: $('#like-button').val(),
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function (json) {
document.getElementById("like-count").innerHTML = json['result']
console.log(json)
},
error: function (xhr, errmsg, err) {
console.log(xhr)
console.log(errmsg)
console.log(err)
}
})
})
</script>
Note :
You don't have to check for action instead you can check for method eg. request.method.
You've provided wrong url inside your ajax call '{% url 'course:like' course.slug %}' it should be '{% url 'course:like' %}' without passing slug.
Do not use id as avariable because it will conflict with python id() function, you can check for all available built-in functions in python here.
I sent an Ajax request to server to get some filtered data and here is a sample I receive from server:
(3) [{…}, {…}, {…}]
0: {id: 1, title: "12 Rue Longueil", slug: "12-rue-longueil", latitude: null, longitude: null, …}
1: {id: 2, title: "15 Rue Sherbrooke LM", slug: "15-rue-sherbrooke-lm", latitude: null, longitude: null, …}
2: {id: 3, title: "Cycle Neron", slug: "cycle-neron", latitude: "-73.5987000000000000", longitude: "45.4799000000000000", …}
length: 3
__proto__: Array(0)
above data is logged from console.
I want to display these data in HTMl tags within cards below.
but for that I need to use that received data and create children using JavaScript e.g. document.createElement('DIV'). and then place these data.
$(document).on('submit', "#filterform", function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: "{% url 'listing:search' %}",
data: {
listing_for: $('#listing_for').val(),
// cutted
},
success: function (response) {
const listings = eval(response);
const content = document.getElementById('content');
for (let i = 0; i < listings.length; i++) {
const div = document.createElement('div');
div.className = 'listing mgb-1';
div.innerHTML = data[i].title;
content.appendChild(div);
// have to create, add lots of divs and classes
}
}
})
})
I was wondering if there is a way to sent Ajax request data as template variable? Or do I have to hardcode all HTML tags using Javascript?
Edit: Edited content based on first answer creating a separate HTML.
def search(request):
...
lst = list()
for listing in queryset:
ser = ListingSerializer(listing)
lst.append(ser.data)
return render(request, 'listing/newHtmlFile.html', {'listings': json.dumps(lst)})
separate HTML:
{% for list in listings %}
<div class="jumbotron">
<h1>{{ list.title }}</h1>
</div>
{% endfor %}
and ajax request:
success: function (response) {
document.querySelector('#content').insertAdjacentHTML('beforeend', response);
}
Yes, you can. Basically the idea is to make a separate HTML file that's going to be rendered by the view that handles the AJAX request. Then, you can use JavaScript and the insertAdjacentHTML() function to insert it in your original HTML file.
Take a look at this example:
view:
def ajax_handler(request):
# ... logic
return render(request, 'newHtmlFile.html', {'your_context': data})
Original HTML file
<div id='container'>
</div>
newHtmlFile.html
<p>{{ your_context }}</p>
JavaScript part (in this example I use Vanilla, not JQuery)
let ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if (this.readyState === 4){
if (this.status === 200){
document.querySelector('#container').insertAdjacentHTML('beforeend', this.responseText);
}
}
}
ajax.open('GET', '/ajax-handler-url', true);
ajax.send();
If you are interested to know how this works, we can break it down as follows:
You have some data (like a queryset, in your case) in your view
You call the render() method and you pass that data as the context data to a template
The render() method what actually does is to (let me be redundant here) render a HTML file (combining the HTML itself with the context data you passed) and return a HTTPResponse object containing a rendered text.
That rendered text (which is a bytestring that represents the content of the rendered HTML) is given as a response to the client. In this case, it's given specifically to the $.ajax() function that made the request.
We use the insertAdjacentHTML() function to append that rendered text to the desired element (in the example above, the #container div).
A quick, and possibly "dirty", way of doing it is to use the backtick strings in javascript:
success: function (r) {
const listings = JSON.parse(r); // with the correct headers from django, this should't be needed.
listings.forEach(e => $('#content').append(`
<div class="listing mgb-1">${e.title}</div>
`));
}
You should return your data from django with the appropriate headers so you automatically get json and don't need to eval(response).
I'm confused about how to do it via Ajax or Json, but how can I send the selection array (curCheck) on-click to Django views and receive it as a python array
javascript
document.getElementById('results').addEventListener('click', function(){
html_table = '<thead><tr><th>Currency</th><th>Amount</th><th>Symbol</th>><tr/><thead/>'
var checkElements = document.getElementsByClassName('ch');
for(var i =0; i< curname.length; i++){
if (checkElements[i].checked) {
var curChecked = curname[i];
var JsonArr = JSON.stringify(curChecked);
postcurChecked(JsonArr)
html_table += '<tr><td>' + curname[i] + '</td>';
}
}
document.getElementById('result_table').innerHTML = html_table;
},false;
ajax
function postsubChecked(curChecked) {
$.ajax({
"url": "http://127.0.0.1:8000/results/",
"type": "POST",
"data": {"checkbox": curChecked},
"headers": { 'X-CSRFToken': getCookie('csrftoken')}
})
}
in django
def currencyChecked(request):
body_unicode = request.body.decode('utf-8')
body_unicode = body_unicode.replace('%22','')
print(body_unicode) json_data = json.loads(body_unicode.read())
I would like to see the python array print to see it is passed to the back
but I keep getting this error:
json_data = json.loads(body_unicode.read()) AttributeError: 'str' object has no attribute 'read'
For getting the selected checkbox values and sending as an array using ajax you can use jquery like this:
consider you have multiple checkboxes and a button.
<input type="checkbox" name="imageName">
<input type="checkbox" name="imageName">
.......
<button id="deletePhoto">Delete</button>
after selecting multiple checkbox values click on this button. On clicking the below jquery will be triggered to make an arrya of selected checkbox values.
//jquery for getting the selelcted checkbox values
$(document).on("click","#deletePhoto",function(){
var favorite = [];//define array
$.each($("input[name='imageName']:checked"), function(){
favorite.push($(this).val());
});
alert("Photo Selected: " + favorite.join(", "));
if(favorite.length == 0){
alert("Select Photo to delete");
return false;
}
//ajax for deleting the multiple selelcted photos
$.ajax({type: "GET",
url: "/olx/deletePhotoFromEdit",
data:{
favorite:favorite
},
success: function(){
// put more stuff here as per your requirement
});
}
});
});
In the view you can get the array like this:
selected_photo = request.GET.getlist('favorite[]')
I have the below code in Ajax to display the data from python stored in MongoDB.
<script>
function f(){
$(document).ready(function(){
$.get('ajax1', function(result){
$.each(result, function(index, element) {
alert(JSON.stringify(element));
});
});
});
}
</script>
Python call for the same:
#route('/ajax1')
def func():
client = MongoClient()
db = client.collection
result = db.collection.find({},{'_id':0}).limit(2)
arr = []
for document in result:
arr.append(doc)
return (dict(items=arr))
I am getting the result as below:
[{"Name":"abc","Place":"SomePlace","Designation":"des"}]
[{"Name":"NextName","Place":"NextPlace","Designation":"Nextdes"}]
I want to print it in this format or in the form of a table:
abc Someplace des
NextName Nextplace Nextdes
Can somebody tell me how to do it? Seems simple but I am unaware of it.
Thanks!
To me it would make more sense to use the property names in the javascript as it's easier to understand and more verbose.
<script>
function f(){
$(document).ready(function(){
$.get('ajax1', function(result){
$.each(result, function(index, element) {
var row = element.Name + " " + element.Place + " " + element.Designation;
console.log(row);
});
});
});
}
</script>
I am new to web development and trying to solve the following problem. My app has several checkboxes and I need to get values of checked checkboxes. Later, I use those values in further data manipulations and pass the final result using ajax. When I try:
values = request.args.getlist('check')
print values
the list is empty.
values = request.values.getlist('check')
doesn't work ether.
Flask portion:
#app.route('/smiles_to_chemfig')
def smiles_to_chemfig():
smiles_mol = request.args.get("smiles_mol")
values = request.args.getlist('check')
print values
lst = ' '.join(values)
chemfig, pdflink = smiles_mol_to_chemfig(lst,'-i direct', smiles_mol)
return jsonify(outcome = chemfig, pdf_link = pdflink)
ajax:
$(function(){
$("button#smiles").on('click', function(){
if ($('textarea[name=smiles_mol]').val()=="") {
//$("#txt_area").html("PLEASE FILL OUT THIS FIELD !")
alert("PLEASE FILL OUT THIS FIELD !");
}
else {
$.getJSON('/smiles_to_chemfig', {
smiles_mol: $('textarea[name=smiles_mol]').val()
}, function(data) {
$("#txt_area").text(data.outcome);
console.log(data.outcome);
$("#pdf").attr('src', data.pdf_link);
});
}
return false;
});
});
I suspect, that it has something to do with ajax because if I do not implement ajax everything woks good but I need to use ajax. Any suggestions and comments are highly appreciated!