Unexpected end of JSON input only on one table - javascript

I've made some code with jQuery that whenever I press a button I shall retrieve some information. This works fine with 3 of my tables, but of some reason that last table wont work.
My jQuery code looks like this
$.ajax({
url: "ajax.php",
type: "get",
datatype: "json",
success: function(data){
var parsed = jQuery.parseJSON(data);
$.each(parsed, function(i){
var oldhtml = $('p').html();
$("p").html(oldhtml + "<br>Name: " + parsed[i]['name']);
});
}
)};
So I have this connected to a button and an onclick function. So my PHP code echoes an associative array, and it works fine with my tables moment1, moment2, moment4. But whenever I try to use it on my table called konsult, I get syntax error.
"Unexpected end of JSON input at Function.parse [as parseJSON] (anonymous)".
It it something with my table or what is the problem? I use the same code to get info from the first tables. I only switch the tablename and instead of "parsed[i]['name']" I have "parsed[i]['titel']"
EDIT: It seems to be fixed. One of my cells had a "ö" which for some reason gave me syntax error.

Related

TypeError: obj is undefined and refers to a line with $.each

I am trying to add an item to database and reload it in my ajax datatable. However, every time I click the add button after filling down the form, I get TypeError: obj is undefined in the browser console and the item won't be added to the database nor the datatable. The error refers to the line with $.each(res.errors, function(key,value). How to fix this? Or is there another way to do it.
Another scenario is I click the add button without filling down the form, so some styling classes will be added to warn the user that the form must be filled, and the code works.
I use Firefox and Laravel.
The error only shows up when I fill the form and click add.
$('#modal-btn-save').click(function(e){
e.preventDefault()
var form = $('#modal-body form'),
url = form.attr('action'),
method = $('input[name=_method]').val() == undefined ? 'POST' : 'PUT'
$.ajax({
url: url,
method: method,
data: form.serialize(),
success: function(response){
form.trigger('reset')
$('#datatable').DataTable().ajax.reload();
},
error: function(xhr){
var res = xhr.responseJSON;
if ($.isEmptyObject(res) == false){
$.each(res.errors, function(key,value){
$('#' + key)
.closest('.form-group')
.addClass('has-error')
.append('<span class="help-block"><strong>' + value + '</strong></span>')
})
}
}
})})
I expect the item would be added to the datatable just like in this tutorial and without the TypeError message in the console. https://www.youtube.com/watch?v=B2CeceGOVy8 I've tried to copy paste the code to see if I've missed a character, but nope, I still get the same error. Please help.

Ajax doesn't get to success function. Always error function. It fails to post data to another file

Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.

Can't make DataTables work by using jQuery .post()

I am working on a form where a uses chooses a date range in order to display information by using DataTables.
When the user clicks on the button, the dates are sent through jQuery .post() function and it retrieves the info as expected.
Here is the piece of the code related to it:
//Sending the dates range
$.post(url_route, datos, function(data,status){
if(status=='success'){
var response = jQuery.parseJSON(data);
//checking if data were found
if(response.list_events.length === 0){
console.log('No data available');
}
else{
//Let us display the info with DataTables inside div #list_events and
//table #table_id
$('#list_events').html('<table class="table table-striped table-hover" id="table_id"></table>');
$('#list_events table').append('<thead><tr><th>Event</th><th>Type</th><th>Attendance</th><th>Coordinators</th><th>Participants</th><th>Institutes</th><th>Talks</th></tr></thead><tbody></tbody>');
//retrieving the info for each row and append it to the table:
$.each(response.list_events,function(i,item)
{
$('#list_events').find('tbody').append('<tr>');
$('#list_events').find('tbody').append('<td>'+item.Event+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Type+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Attendance+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Coordinator+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Participant+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Institute+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Talk+'</td>');
});//end of each
//initializing DataTables
var table = $('#table_id').DataTable();
}//end of else (info found)
}//end of if success
}//end of post()
So far, the info is displayed in the DataTables but it is not totally working, since only the information is displayed. The DataTables search, next, and previous buttons, as well as the number of results dropdown menu are not shown.
In the console.log I get the following error:
Uncaught TypeError: Cannot read property 'length' of undefined
Any ideas? Can anyone shed some light on this?
Solved
The problem was with the append function.
If I type just one append with only the <tr> like this:
$('#list_events').find('tbody').append('<tr>');
The result in HTML is <tr></tr> That is to say, the tag is closed automatically ... no matter what. So, the solution was to put all the appends in one line like the following:
$('#list_events').find('tbody').append('<tr><td>'+item.Event+'</td><td>'+item.Type+'</td><td>'+item.Attendance+'</td><td>'+item.Coordinator+'</td><td>'+item.Participant+'</td><td>'+item.Institute+'</td><td>'+item.Talk+'</td></tr>');
And that was it ☺
My first thought is that perhaps "response.list_events" is undefined. Certainly your error:
"Uncaught TypeError: Cannot read property 'length' of undefined"
seems to imply that.
My second thought is that I have recently done something similar where I had trouble with the .post method, and found success with the .ajax method.
Try something along these lines:
$.ajax({
type: "POST",
url: url_route,
data: datos,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(returned_from_server){
// your function here
}
});
My third thought is that I don't see where you put your closing row tags.
$.each(response.list_events,function(i,item)
{
$('#list_events').find('tbody').append('<tr>');
$('#list_events').find('tbody').append('<td>'+item.Event+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Type+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Attendance+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Coordinator+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Participant+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Institute+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Talk+'</td>');
$('#list_events').find('tbody').append('</tr>'); // <--- I believe you might be missing this!!
});//end of each
Hopefully this was some help.
If you are using a remote source for your data, it is far more elegant and efficient to let DataTables itself render the data for you.
In your example, you fetch the data, build the table, and then turn it into a "DataTable". If it meets the requirements and gets the job done, you've written perfectly fine code and you should read this answer no more!
But DataTables itself is awfully smart about rendering data detached from the DOM and then slotting it all in place. You get the benefit of more efficient updates while simultaneously having cleaner code.
Here's a basic example. Without testing it in your environment, I can't say for sure it will do your job, but I think it should:
var myTable = $('#table_id').DataTable( {
"ajax": {
"url": url_route,
"data": function(customData) {
customData.datos = datos // need some way to have access to datos
}
}
});
And then on click, if you want to retrieve newer data based on whatever has changed (the date range?) you just have to redraw.
myTable.draw();
I can imagine a few ways to get datos in there-- wrap it up in a function that accepts and uses datos. Declare a namespaced or otherwise quasi-global (or actually global if you're that guy!) variable that myTable would have access to at any given point in time... or even just destroy the current table and call the whole DataTable() on it again.

Display function result in all items javascript

I am trying to return the function result for all the items using an AJAX function, as it is only showing the data for the latest item. Code is working fine when it only has to show the data for 1 item, however when it has to show it for more than 1, it shows the same one for all of them.
I was testing with alert and it was working fine, it was rendering the data from the image size correctly for each of the items..
I am using this:
var xhr = $.ajax({
type: "HEAD",
url: imageBase,
success: function(result){
$(".banner-block .title").html(xhr.getResponseHeader('Content-Length') + ' bytes');
}
});
What is missing so each item displays its particular image size correctly?
Thank you in advance
Your probelm might be that jquerys .html() function replaces. Does it work if you change it to $(".banner-block .title").append(xhr.getResponseHeader('Content-Length') + ' bytes');

Unable to loop through javascript object

I have a object district_boundaries which is leaflet geojson object
var district_boundary = new L.geoJson();
and the data is added through ajax call to a geojson file of district
$.ajax({
dataType: "json",
url: "data/district.geojson",
success: function(data) {
$(data.features).each(function(key, data) {
district_boundary.addData(data);
district_boundary.setStyle(district_boundary_styles["default"]);
});
}
});
So in the _layers there are 75 values, one example of such values is the one in the picture with key 149.
I need to loop through all these 75 values and get the values from features key. i.e the name of districts and use them to label the districts.
I tried with this
_test = district_boundary._layers;
for (var aht in _test) {
console.log('inside the loop');
var b = _test[aht];
console.log(b.feature.properties.NAME_3);
}
This works fine when tried in the console and shows the result
But when i tried with by running in the script of my page this doesnot work the though _test is populated with the values in district_boundary._layers, loop is not executed. What could be the reason can anyone please help me with this?
the output of msg and msg.d is
I am guessing your JSON data is getting wrapped in a d variable. Try the following -
$.ajax({
dataType: "json",
url: "data/district.geojson",
success: function(msg) {
//console.log(msg); //try this to see whether the data is really getting wrapped in d
var data = msg.d; //msg.d contains the actual data
$(data.features).each(function(key, data) {
district_boundary.addData(data);
district_boundary.setStyle(district_boundary_styles["default"]);
});
}
});
Solved. Everything in the code is fine except the flow of execution. I was trying to use the data which would be defined later according to the flow, so in the part of script where i tried to loop through _test it is not populated yet, but when i tried in console it was after all the data was loaded and hence it worked.

Categories

Resources