calling ajax inside form before submit showing `Uncaught ReferenceError` - javascript

I am trying to call an ajax function from inside a form to extract value for the drop down.
mypython.py
#app.route('/new_data', methods = ['POST', 'GET'])
def new_data():
#Filter data and return the data(data_list,filter_function_url) to myhtml.html file
myhtml.html
<div>
<form ....method="POST" action="{{url_for('submit_new_data')}}" method="POST" enctype="multipart/form-data">
....
....
<select id="selected_data" onchange='get_subdata_filters("{{ filter_function_url }}")'>
<option disabled selected>Please Select Partner State</option>
{% for f in data_list %}
<option value="{{f}}">{{f}}</option>
{% endfor %}
</select>
</form>
</div>
myjsfile.js
This does work fine the value from the id selected_data from the html file and the selected_option_data_filter_url got from html filter_function_url does get displayed properly on the console without any error
function get_subdata_filters(selected_option_data_filter_url) {
var selected_data = document.getElementById("selected_data").value;
// make the user selected data into a dictionary/json
var new_selected_data = {
s_data:selected_data
};
console.log(new_selected_data);
console.log(selected_option_data_filter_url);
}
When I add an ajax call inside my js function upto select
function get_subdata_filters(selected_option_data_filter_url) {
var selected_data = document.getElementById("selected_data").value;
// make the user selected data into a dictionary/json
var new_selected_data = {
s_data:selected_data
};
console.log(new_selected_data);
console.log(selected_option_data_filter_url);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: selected_option_data_filter_url,
traditional: "true",
async:false,
timeout: 40000,
data: JSON.stringify({new_selected_data}),
dataType: "json",
success: function(fselected_data){
console.log(fselected_data)
};
});
}
I get this error
Uncaught ReferenceError: get_subdata_filters is not defined when I check the console
What is doing wrong?
How can I correct this?

There is an error in your ajax call.
Remove the ; after the success and add an ; after your console.log()
function get_subdata_filters(selected_option_data_filter_url) {
var selected_data = document.getElementById("selected_data").value;
// make the user selected data into a dictionary/json
var new_selected_data = {
s_data:selected_data
};
console.log(new_selected_data);
console.log(selected_option_data_filter_url);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: selected_option_data_filter_url,
traditional: "true",
async:false,
timeout: 40000,
data: JSON.stringify({new_selected_data}),
dataType: "json",
success: function(fselected_data){
console.log(fselected_data);
}
});
}

Related

pre-selection of fields with ajax for select2

When I try to pre-select the value with ajax everything except the shown value is working.
Does anyone know where I've made the mistake?
I call the pre_select() function for each <select>.
When I look in to the code, everything is OK, but the label on the page is showing me the ID instead of myTitle. After submitting the form, the data is also ok! I need only the right label...
function pre_select(pre_id, query_id) { //my ID of selection, the query
var mySelect = $('#form_my_id'+pre_id);
$.ajax({
type: 'GET',
dataType:'json',
url: '?search&id='+query_id
}).then(function (data) {
var option = new Option(data.myTitle, data.id, true, true);
mySelect.append(option).trigger('change');
mySelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
}
Here is the HTML output
<select name="form_select[]" class="form-control select2bs4 select2-hidden-accessible" id="form_my_id1" width="100%" required="" data-select2-id="form_stok_id1" tabindex="-1" aria-hidden="true">
<option value="1" selected="" data-select2-id="5">The Title Of Product</option>
</select>
This function has done my job :-)
function pre_select(pre_id, query_id) { //my ID of selection, the query
var mySelect = $('#form_my_id'+pre_id);
$.ajax({
type: 'GET',
dataType:'json',
url: '?search&id='+query_id
}).then(function (data) {
mySelect.select2("trigger", "select", {
data: data
});
});
}

Problems with selecting option with loading data with Ajax request with the object select option

I have performed a rest service performed with C # with ajax request in a combo box, this object shows the data of my rest service, this combo box must fill data from many cities and this shows the cities that I perform in the service, but the inconvenience is in the object combo box or select option in html5, whenever I give in the object, it loads the data and I cannot select my city that I want, reloading it, as an infinite loop when I want to select the data Annex code
https://es.stackoverflow.com/questions/279794/problemas-en-mostrar-datos-en-combo-box-en-pantalla-con-petici%c3%b3n-ajax
<div class="form-group has-feedback">
<label>Ciudad</label>
<select class="form-control" data-rel="chosen" id="Ciudad" name="Ciudad" onclick="ValidarExisteCiudad()">
<option/>
<option/>
</select>
</div>
function ValidarExisteCiudad() {
//$("[data-rel='chosen']").chosen();
//var ddlCiudad = $("[data-rel='chosen']");
var ddlCiudad = $("#Ciudad");
ddlCiudad.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
$.ajax({
type: 'GET',
url: "CargaCiudad",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
ddlCiudad.empty().append('<option selected="selected" value="0">Seleccione ...</option>');
$.each(data, function () {
ddlCiudad.append($("<option></option>").val(this['Value']).html(this['Text']));
});
// After updated data from database you need to trigger chosen:updated.
//$("[data-rel='chosen']").trigger("chosen:updated");
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
existeUsuario = false;
}
});
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> CargaCiudad()
{
List<Cuidad> Items = await drHelpPrueba.Cuidad.ToListAsync();
List<SelectListItem> ciudad = new List<SelectListItem>();
for (int i = 0; i < Items.Count; i++)
{
ciudad.Add(new SelectListItem
{
Value = Convert.ToString(Items.ToList()[i].IdCiudad),
Text = Items.ToList()[i].Nombre
});
}
return Json(ciudad);
}
ddlCiudad.append($("").val(this['Value']).html(this['Text']));
undefined
my friend. Because you don't get true data from the response.
Try following this. Hope to help, my friend :))
function ValidarExisteCiudad() {
var ddlCiudad = $("#Ciudad");
ddlCiudad.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
$.ajax({
type: 'GET',
url: "CargaCiudad",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
ddlCiudad.empty().append('<option selected="selected" value="0">Seleccione ...</option>');
$.each(data, function () {
ddlCiudad.append($("<option> </option>").val(this.value).html(this.text)); //Modified this line
});
// After updated data from database you need to trigger chosen:updated.
//$("[data-rel='chosen']").trigger("chosen:updated");
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
existeUsuario = false;
}
});
}

Refresh content in a for loop using jquery in Django

I am creating a website that allows users to search for a list of papers. Once a list of papers is returned, the user can click "like" or "dislike" to one or more papers. The like count should dynamically update as the user click the like button.
I am using jquery to handle the dynamic update of the like count. However, I am not sure how to tell the success function in the ajax WHICH id to update. The reason is that the id is generated on the fly, and it is determined by which papers are returned as search results to the user.
So far, I have the following in the template:
{% for result in results %}
<li >
{{ result.title}},
<span class="like_span fa fa-thumbs-up"></span>
<strong id="like_count_{{ result.pk }}">{{result.likes}} </strong>
</li>
{% endfor %}
As you can see, i specify the id of the part where I want the dynamic update to happen as "like_count_{{ result.pk }}". I am not sure if this is the best way to go about it.
The jquery part looks like this:
<script>
$(document).ready(function(){
$(".like_button").click(function(){
$.ajax({
type: "GET",
data: {'pk': $(this).data('pid'),
'liked': $("span").hasClass('fa fa-thumbs-up') },
url: "{% url 'search:paperpreference' %}",
success: function(response) {
var pk = $(this).data('pid');
$(?????).html(response.likes )
},
error: function(response, error) {
alert(error);
}
});
});
});
</script>
Simply put, I don't know how can i specify the ????? part such that when success, the new like count is only updated to that specific paper, not the first paper in the loop.
The views.py has the following so far:
def paperpreference(request):
# if request.method == "GET":
pid = request.GET['pk']
paper = Paper.objects.get(pk=pid)
likes = paper.likes + 1
paper.likes = likes
paper.save()
data = {'likes': paper.likes}
return JsonResponse(data)
I am new to Jquery, any help would be much appreciated!
Thanks to suggestions by #dirkgroten, the like count can now be dynamically updated by the following jquery function. The trick is to move the pk declaration to before the ajax.
<script>
$(document).ready(function(){
$(".like_button").click(function(){
var pk = $(this).data('pid')
$.ajax({
type: "GET",
data: {'pk': pk,
'liked': $("span").hasClass('fa fa-thumbs-up') },
url: "{% url 'search:paperpreference' %}",
success: function(response) {
$("#like_count_"+ pk).html(response.likes )
},
error: function(response, error) {
alert(error);
}
});
});
});
</script>
another option is return the id from the server.
def paperpreference(request):
# if request.method == "GET":
pid = request.GET['pk']
paper = Paper.objects.get(pk=pid)
likes = paper.likes + 1
paper.likes = likes
paper.save()
data = {'likes': paper.likes,'pid':pid}
return JsonResponse(data)
<script>
$(document).ready(function(){
$(".like_button").click(function(){
var pk = $(this).data('pid')
$.ajax({
type: "GET",
data: {'pk': pk,
'liked': $("span").hasClass('fa fa-thumbs-up') },
url: "{% url 'search:paperpreference' %}",
success: function(response) {
$("#like_count_"+ response.pid).html(response.likes )
},
error: function(response, error) {
alert(error);
}
});
});
});
</script>

Attribute from class iteration return object instead of string

I have multiple divs that have an attribute on my page e.g.:
<div class="followCallout" id="follow_123" data-follow-id="123">
WHATEVER
</div>
....
<div class="followCallout" id="follow_456" data-follow-id="456">
WHATEVER
</div>
With a timer i loop through these divs and make an ajax call for each, to see if sth has changed:
function checkFollows() {
var t = setTimeout(checkFollows, 5000);
$('.followCallout').each(function(){
var $that = $(this);
var $id = $that.attr('data-follow-id');
var $url = $('#ajax-route-check-follow').val();
console.log($id); //THIS RETURN 123 etc...
$.ajax({
url: $url,
data: {
id: $id
},
type: "get",
contentType: false,
processData: false,
cache: false,
dataType: "json",
error: function (err) {
},
success: function (data) {
}
});
})
}
The $url is from here <input type="hidden" id="ajax-route-check-follow" value="/cCRM/web/app_dev.php/admin/_ajax/_checkFollow" />
However, the URL I'm sending looks like this:
http://localhost/cCRM/web/app_dev.php/admin/_ajax/_checkFollow?[object%20Object]&_=1497624513190
So instead of checkFollow?id=123 it gives me checkFollow?[object%20Object] so I assume sth is wrong with my ajax call? I am using the exact same call (w/o the $.each, only single calls though) on other parts as well. Where am I wrong?

Show succes message from ajax

I have a question, So I create a sistem that update in database a row when onChange a select box. All goes well, but I want to drop a succes message if update was with succes.
My view :
<form action="" id="updateStatus" method="post">
<select id="statusSelect"
name="{{ gift.id_instant_gagnant }}"
class="form-control"
onChange="updateCadeauStatus({{ gift.id_instant_gagnant }})">
{% for key,statut in form_logistique.statut.choices %}
<option value="{{ key }}"
{% if gift.etat == key %}selected="selected"{% endif %}>
{{ statut }}
</option>
{% endfor %}
</select>
</form>
<script>
function updateCadeauStatus(id) {
var id = id;
var selectedName = $("#statusSelect option:selected").val();
var url_deploy = 'http:localhost/updateStatus'
console.log(id);
console.log(selectedName);
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
});
}
</script>
The controller :
public function updateStatus(){
$iGiftId = $_POST['id_cadeau'];
$iNewStatus = $_POST['id_status'];
$bUpdate = $this->updateStatusByGiftId($iGiftId, $iNewStatus);
return $this->render('logistique.twig');
}
The model :
public static function updateStatusByGiftId($iGiftId, $iStatusId){
$request = sprintf( ' UPDATE `%s` set etat = %d WHERE id = %d ', $table, $iStatusId, $iGiftId);
return Mysqli::query($request, $database);
}
So everything goes well but I want to drop a message after every update, too be displayed in the view. Please help me!!! Thx in advance, sorry for my english.
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName},
success : function(data){
console.log('success');
},
error: function(){
console.log('error');
}
});
You can drop the response of the check file on ajax.
$.ajax({
url: url,
type: "POST",
...
success: function(response){
window.alert(response);
}
})
To be more specific, if you want to give a message only when you successfully changed the row. Modify the validation file (url:) and print a messagge only when you had success..
There are other ways to do that..
You can print a "message id" and get it with the script and drop a message:
$.ajax({
url: url,
type: "POST",
...
success: function(response){
if(response == '1'){
window.alert('Successfully changed!!');
}else if(response == '0'){
$("#foo").html("Error, not changed :(");
}else{
------ something else ------
}
}
})
Hope I could help !
Im not sure if you have your response in another file.
Cuz your response now is in the var data in the line with the code:
}).done(function(data){
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
}).done(function(data){
$("[SuccesDiv]").append("[Succes MSG]");
});
The text between the [ - ] is ment to put there your own element or data.
[EDIT]
I did'nt look good...
You are not looking when it is changed.
To do that, do this:
$("select").on("change", function(){
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
}).done(function(data){
$("[SuccesDiv]").append("[Succes MSG]");
});
});

Categories

Resources