How to send javascript object to php via ajax? - javascript

I looked at some other questions such as this and this, but it does not me help me solve my problem. When I console-log my data, I get this:
Object["row_LM#00000010", "row_LM#00000002", "row_LM#00000009", "row_LM#00000008"]
How can I get this in php as a key value pair like row_ : LM#00000010, row_LM#00000002, row_LM#00000009,LM#00000008, so that I can loop each value? I tried JSON.stringify(), I got TypeError: cyclic object value
Here's what I have tried:
$.ajax({
type:'POST',
url:'delinvoices.php',
data:{del_id:JSON.stringify(deleteInvoice)},
success: function(data){
//other codes
}
});
The console.log of deleteInvoice gave me:
Object["row_LM#00000010", "row_LM#00000002", "row_LM#00000009", "row_LM#00000008"]
The base data comes from datatable
var deleteInvoice = dt.rows( { selected: true } ).ids();
Please help.

According to this page (https://datatables.net/forums/discussion/30848/trying-to-get-get-the-row-ids-using-rows-ids), you are getting a dataTables object instance. To get an array, you'd do this:
table.rows( { selected: true } ).ids().toArray();
It might help to simplify what you're working with, the dataTables object might be what's going cyclic on you.

Related

Ajax request, fetch JS array and make it available

I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.

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.

How to get a JSON string result from a database for later use

I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.

Jquery suddenly unable to drill into json?

I have a weird scinario. I have been using $.ajax() to make ajax calls to my server for data and have been using the same sort of format for these server calls. All has been going fine but suddenly I wrote a function and returned a JSON object that jQuery is unable to drill into. I looked at it in Firebug and everything appears normal. Can someone help me here to understand why suddenly I am unable to drill into this particular data object?
Here is the ajax code:
$.ajax(
{
type: "GET",
url: "php/getoptions.php",
dataType: 'json',
data: 'id='+id,
success: function(j)
{
alert(j.isdefault);
}
});
when I try to do this, the alert gives me "undefined." I have tried "alert(JSON.stringify(j))" and I see the valid json being returned. I have even taken the json that I saw in Firebug and run it through JSONLint and it returned valid.
Here is a sample of the json coming back:
[{"isdefault":"1","option1":"1","option2":"0","option3":"0","option4":"1","option5":"1"}]
WHAT IS GOING ON? Why can jQuery suddenly not drill into this data set?
thanks!
You need...
alert(j[0].isdefault);
...because the object that has the isdefault property is at index 0 of an Array.

pass array and individual string to php file using ajax call

I try to implement the following code
var flag = new Array();
var name = $("#myselectedset").val();
$.ajax({
type: 'post',
cache: false,
url: 'moveto.php',
data: {'myselectset' : name,
'my_flag' : flag
},
success: function(msg){
$("#statusafter").ajaxComplete(function(){$(this).fadeIn("slow").html(msg)});
}
});
You can see that the name is a single string and the flag is an arry, am I using the right format for passing them throw ajax call, anyone could help me, thanks
It is impossible to pass arrays in a POST request. Only strings.
You will either need to stringify your array, or consider posting as JSON instead.
You should be able to do something quite simple, like replace your "data" property with:
data : JSON.stringify( { myselectset : name, my_flag : flag } )
That will convert the data into a JSON string that you can turn into PHP on the other side, using json_decode($_POST["my_flag"]);
Very important note:
For JSON.stringify to work, there can't be any functions in the array - not even functions that are object methods.
Also, because this is a quick example, make sure that you're testing for null data and all of the rest of the best-practices.

Categories

Resources