I'm pretty sure response.model.model_to_return is wrong, I try to display on screen the content of the array but my JS structure might be wrong.
JS:
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: "/trafic",
success: function check(response) {
//CODE WORKSPACE //
console.log(response);
$("#variat").empty();
for (var model of response.model.memory_return) {
}
//CODE checkview //
console.log(response);
$("#display").empty();
for (var model of response.model.models_to_return) {
}
},
error: function(response){
//alert('An error occured')
}
});
}, 10000)
})
</script>
Python view:
def trafic(request):
user_msg = request.user
get_Messages = Message.objects.filter(user=user_msg).values()
allm = get_Messages.all()
get_Memory = Memory.objects.filter(user=user_msg).values()
allm2 = get_Memory.all()
c = {"models_to_return": list(allm)}
d = {"memory_return": list(allm2)}
return JsonResponse([c, d], safe = False)
JS error:
Uncaught TypeError: Cannot read properties of undefined (reading 'memory_return')
at Object.check [as success] ((index):613:44)
at i (jquery-3.1.1.min.js:2:27983)
at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2:28749)
at A (jquery-3.1.1.min.js:4:14203)
at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4:16491)
Related
I have a js code (in index.php) as shown below which makes an ajax call to save.php file.
<script>
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.post({
url: 'save.php',
data: $(this).serialize(),
}).done(response => {
console.log(response);
response = JSON.parse(response);
if (response.message) {
alert(response.message);
}
});
});
});
</script>
The issue which I am facing right now with the code above is when we hit save button I am getting the following error message on the console:
VM68:1 Uncaught SyntaxError: Unexpected token I in JSON at position 0
at JSON.parse (<anonymous>)
at Object.<anonymous> (index.php:1011)
at c (jquery-3.5.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.5.1.min.js:2)
at l (jquery-3.5.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.5.1.min.js:2)
Here line#1011 is response = JSON.parse(response); from the js code above.
Problem Statement: I am wondering what changes I need to make in the js code above so that on hitting save button I do not get that error message on the console.
If are aware of the error and just want to ignore it/handle it use a try/catch block. That error is usually because response isn't a valid json string so JSON.parse will keep failing.
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.post({
url: 'save.php',
data: $(this).serialize(),
}).done(response => {
try{
response = JSON.parse(response);
if (response.message) {
alert(response.message);
}
}
catch (e) {
//do something like alert user the request failed
alert('Request to server failed');
}
});
});
More on try/catch from mozilla.
I want to delete a register in a table instrumentos, I'm using codeignite with AJAX and I have this function in my controller
public function deleteInstrument(){
$id = $this->input->get('id');
$sql = $this->db->where('id',$id)->delete('instrumentos');
$r['response'] = 2;
$r['content'] = 'deleted';
echo json_encode($r);
}
And I have in my JavaScript the next function to delete:
function confirmarEliminar(){
$("body").on("click","#tablaInstrumentos button",function(event){
idseleccion=$(this).attr("value");
alertify.confirm('Eliminar Registro',
'Esta seguro de eliminar el registro?',
function(idseleccion){
$.ajax({
url: base_url+'admin_ajax/deleteInstrument',
type: 'GET',
data:{id:idseleccion},
beforeSend:function(){
},
success:function(r){
if(r==2 ){
alert(id)
}
},
error:function(xhr, status, msg){
console.log(xhr.responseText);
}
});
}
, function(){ alertify.error(idseleccion)});
});}
I have this error in the console output
Uncaught TypeError: Illegal invocation
at i (jquery-3.3.1.min.js:2)
at jt (jquery-3.3.1.min.js:2)
at jt (jquery-3.3.1.min.js:2)
at jt (jquery-3.3.1.min.js:2)
at jt (jquery-3.3.1.min.js:2)
at jt (jquery-3.3.1.min.js:2)
at Function.w.param (jquery-3.3.1.min.js:2)
at Function.ajax (jquery-3.3.1.min.js:2)
at Object.<anonymous> (configuracion.js?1550431424:80)
at Object.callback (alertify.min.js:3)
Please try this code in js:
function confirmarEliminar(id) {
$.post(base_url + "admin_ajax/deleteInstrument", {id: id}, function (data) {
if (data.code == '1') {
bootbox.alert(data.message, function () {
$("#your row id" + id).remove();
});
} else {
bootbox.alert('Something went wrong');
}
$(window).unblock();
});
}
Controller Code:
public function deleteInstrument($id){
}
I have the following code that is part of a Jquery plugin:
var Model = {
loadData: function() {
var self = this;
$.ajax({
url: 'some.php',
type: 'GET',
dataType: 'json',
//contentType: 'application/json',
data: {'quality' : 'quality'},
success: (function(data) {
self.toggleButton(data);
})
});
},
toggleButton: function(data) {
/*
if the checkbox is ticked, alert the data from the ajax call
*/
// the data can be displayed here
console.log(data);
if ( $(this).is(':checked') ) {
alert(data);
} else {
Do something else...;
}
},
};
When I load the page I get the following error in the console:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
at Array.checked (jquery.min.js:2)
at jquery.min.js:2
at o (jquery.min.js:2)
at vt (jquery.min.js:2)
at vt (jquery.min.js:2)
at nt (jquery.min.js:2)
at Function.nt.matchesSelector (jquery.min.js:2)
at Function.filter (jquery.min.js:2)
at init.is (jquery.min.js:2)
at Object.toggleButton (....)
What I'm trying to achieve is that when user ticks the checkbox, the data to be alerted. I know the data is being passed successfully since I can see it in the console.log statement in the toggleButton method. But when I tick the checkbox I get the following message in the console: I
v.Event {originalEvent: MouseEvent, type: "click", isDefaultPrevented: ƒ, timeStamp: 563856.225, jQuery183032448186288432224: true, …}
In the toggleButton method, the $(this) selector refers to the checkbox element whereas the data parameter is a JSON object.
So what is the best way to access data once the checkbox is ticked? Any help on this is greatly appreciated as I'm not sure how to move forward with this. Thank you
I am trying to retrieve data by using ajax and successfully the data appears, but there is my problem when data is not there I want to try to change its value, but it fails what is wrong with my script? and its error message is
Uncaught TypeError: Cannot read property 'id' of null //this error
$('[name="changeID"]').change(function () {
var url = base_url+'tools/get_id';
var idTools = $('[name="number_tools"]').val();
$.ajax({
url : url,
type: 'POST',
dataType: "JSON",
data: { id : idTools},
success: function(data) {
var result = data.id;
var getNewID = parseInt(result.substr(result.length -3)) + 1;
if (!data) {
$('[name="id"]').val("000"); //error here
}else{
$('[name="id"]').val(getNewID);
}
console.log(result);
},
error: function (request, jqXHR, textStatus, errorThrown) {
console.log(request.responseText);
}
});
});
Change your ajax response to below format,
if(!data)
{
$('[name="id"]').val("000");
}
else
{
var result = data.id;.
var getNewID = parseInt(result.substr(result.length -3)) + 1;
$('[name="id"]').val(getNewID);
}
You are use data object before checking null. If data is null then obviously you will get error of Uncaught TypeError: Cannot read property 'id' of null. You have to use data in if (!data) { } condition.
I'm trying to edit a record through AJAX, but it fails intermittently with the following error
Uncaught TypeError: Cannot read property 'split' of undefined
Here is the code:
$.ajax({
type: "POST",
url: url + "/customer/" + customer_id + "/order/" + order_id + "/cust_inline_editing",
data: {
'_token': token,
'order_id': order_id,
'hourid': hourid
},
async: false,
success: function(data) {
$("#inline_submit").text('Update');
var result = JSON.parse(data);
alert(result.dato);
var edit_date = result.dato.null.split("-").reverse().join(".");
$("#dato").val(edit_date);
}
});
What is the cause of the error?
Check condition if result.dato not null then only split.
if(result.dato != null) {
var edit_date = result.dato.split("-").reverse().join(".");
$("#dato").val(edit_date);
}