Running JS doesn't work on page load, but otherwise does - javascript

I'm fetching some JSON data to an HTML table using AJAX and jQuery.
The script is generating table rows with table data elements and is working properly.
I need to write another script which will count the number of table rows.
Logically I went with:
let rows = $('table tr').length
console.log(rows)
Running this on page load (e. g. $(document).ready) outputs a length of 0 to the console.
However, running it on any other event (e. g. click) works and outputs the correct length.
To my understanding, the browser runs the counting script before any of the table rows are loaded. Why does this happen? It appears later in the code than the table generating script.
How do I make it work properly on page load? Cheers.

What Matthew Herbst said, is totally right. Although since you are using jQuery, and according to the documentation on http://api.jquery.com/jquery.ajax/ I would suggest that you use the .done function (or alternativelly the success callback).
Examples :
Done method :
$.ajax({
url: "http://example.com/getRows.php",
})
.done(function( data ) {
// data received
doWhateverHere();
});
Success callback :
$.ajax({
url:"http://example.com/getRows.php",
success:function(data) {
// data received
doWhateverHere();
}
});

Related

How to replace php function with ajax

I am new to AJAX here. How can i replace the initial php function after the action of ajax is execute? I have found that the page will not refresh after the action is execute.
Here is the code:
javascript
function set_ddm(another_data) {
var result = $.ajax({
url: '../display/ea_form_header.php',
type: 'POST',
data: {
action: 'set_ddm',
Data_store: another_data,
},
success: function(data) {
console.log(data);
}
}).responseText;
}
php code
<td>
<?php
//initial function (customized drop down)
print ddm_jsfunc_employee("employee_list",$employee_list)
set_ddm(data);
if($_POST['action'] =='set_ddm') {
$employee_list=$_POST['Data_store'];
$employee_list_decoded = json_decode($employee_list,true);
//expected this function to replace the initial function after ajax was called
print ddm_jsfunc_employee("employee_list",$employee_list_decoded);
} ?>
</td>
I expect the function will replace the initial function and show in the main page but it only show in console after ajax(page aren't refresh to show it). Is there any wrong with the code or any solution for this? (the ddm_jsfunc_employee must be there to print the drop down)
thanks in advance
From ajax success callback you have to set that response in the html to view on web page.
like this:
$('.elementClass').html(response);
i hope this will works for you.
I think you have a slight misunderstanding about what AJAX is, it is not something to replace your PHP code with, but to asynchronously get data and update your webpage without reloading.
Let's first take a look at the .ajax function specifically interesting for us now is the .done() callback method, because JavaScript does the request realtime (async) JavaScript does not know when the request is done. But it allows us to specify a function inside the .done for it to call when it is done.
A really simple example would be:
$.ajax('https://stackoverflow.com')
.done(function(data) {
// We can do what we want with the data here.
console.log(data);
});
Now when the request is done the function we defined in .done will be called, in this case a simple log. But you would want to change this to a function that updates your HTML.
I also see you are calling JavaScript functions in your PHP, this will not work as PHP runs on your server but JavaScript runs in your browser. (Unless you use node or the likes)
Just a tip; it is advised to place JavaScript at the bottom of your HTML page as JavaScript is blocking content. (proper link explaining needed here)
Meaning your browser will stop parsing the HTML and run the JavaScript as it finds it.
Long story short, if you want to replace the PHP code, you would have to remove it. Make a PHP script which gives you your data. AJAX call it and then use .done or success and update your webpage from there.

Why does this TinyMCE AJAX integration work 9/10 times?

I've got a TinyMCE implementation that works somewhere around 80-90% of the time, but for that last percent, the content of the editor fails to populate - for lack of better phrasing.
Effectively, upon page load, a jQuery AJAX call reaches out to a PHP page that grabs some content from my database. Upon retrieval, I set the value of the TinyMCE instance to the content of the response. I've gone a few rounds with this, first with a custom AJAX build, and recently a jQuery build. In both cases I get about the same results - that the editor loads, the content comes back from the server, and every once in a while, the text area ends up blank.
The latest attempt at this is much shorter than the earlier ones, but either way, I still end up with effectively the same result. I've also tried repainting the TinyMCE instance after the content is loaded to no avail.
The result of the two console logs are identical - and the expected response from my server - even in the case of a failure. So the value IS getting set, but the content is not visible.
function LoadAgenda()
{
$.ajax(
{
url: 'http://www.example.com/agenda.php?AgencyID=' + AgencyID + '&date=' + AgendaDate,
cache: false,
dataType: 'html'
})
.done(function(Response)
{
console.log(Response);
$('#AgendaContent').val(Response);
tinyMCE.execCommand("mceRepaint");
console.log($('#AgendaContent').val());
});
}
And finally, for the record, I'm using TinyMCE 4.1.6.
If anyone needs more information than this, I'm happy to oblige.
What happens first? The editor getting loaded or the ajax call completing? If your ajax call is happening after the editor is loaded, I don't think .val() is going to work, since it's no longer a simple textarea after TinyMCE initializes it. Try this:
Make the ajax call only after the editor is initialized
Change .val() to setContent()

How to write a div with jquery or javascript?

I was looking a solution to write one table, which comes from query to a DB in PHP, to a DIV, using Jquery. I'm not looking for the append's method, which I know works, but with append every time I press the button, which executes the query, the table is append to the document. The idea is not to load every time the page, but using the Jquery option, to send the post and get data back. Thank you.
UPDATE
<script>
var values = {var1: 2, var2:"Hello"};
$.get("phpfile.php", values, function(data) {
$('#id').append(data);
});
Suppose that script is call from a "onclick()"; I don't want the append each time the data, but just write in a div.
If I get you right, you just want to "update" the contents of a single div instead of reloading the whole page and this update contains a html table?!
For this purpose you could use the .html() function of jQuery: jQuery html()
In addition you should check .ajax() function of jQuery for all options/parameters: jQuery ajax()
A sample code could look like this:
$.ajax(
{
url: "yourfile.php",
cache: false,
success: function(htmldata){
$("#IdOfYourDiv").html(htmldata);
},
error: function(jqXHR, status, errorThrown){
alert("something went wrong");
}
}
);
This would load data returned for example via an echo of the php file yourfile.php, load it in the temporary variable htmldata and write/update the html contents of YourDivID with the newly returned data.
1 - on button pressed, do ajax get request (see https://stackoverflow.com/a/5942381/1163786)
2 - server receives request
3 - server sends back json response or html fragement
4a - json arrives and you start looping over these elements to build your desired html structure, then insert into the dom
4b - html fragment arrives and you simply insert it at the desired position into the dom
It's your decision, if you return a JSON respones or a HTML response.
For 4a and 4b read:
Best way to add DOM elements with jQuery
Best Practice For Creating HTML (PHP Or Jquery)?
Every piece of these steps is already explained on StackOverflow.

JQuery, include a php file

I've been trying this for 3 days but couldn't find a solution yet. I need to load a php page with javascript. I'm using the code bellow however changing the page while the function is still working slows the page down.
$.post("connect.php?refresh_steamdata=true",{
},
function(data)
{
alert("loaded!");
});
load() is a simplified version of Post that replaces the contents of an element with the response from the server.
".load() sets the HTML contents of the matched element to the returned data."
$.post() will get you the result you are looking for but it does so Asynchronously. This means that if you plan to do something with the response you get back from the server you need to do it inside of the success function
$.post("<? echo $js_url."?refresh_steamdata=true"; ?>",{},function(data){
alert("loaded!");
// do something with data HERE
});
// not here since this will run before the data is returned

Using Jquery methods on Data Returned from Ajax, with out printing out the data

So I have a rather unique situation. I am using JQuery to gather some data based on two date ranges, what is returned as a response in the $data variable (I am using Ajax) I have set, is a html table.
Now I don't want the user to ever see this table, I want to use This jquery plugin to download the CSV file of that table. The question is, if the table sits inside of a $data and can be seen via the network tab in Chrom Dev Tools, under Response, is it possible to be manipulated with Jquery?
In our inhouse framework, we do the following to get Ajax Data:
// The following belongs to a JS class method.
data = {
startDate : $('.startDate').val(),
endDate : $('.endDate').val()
}
CT.postSynch('report/payRollReport/downloadPayRoleReport', {data : data}, function(data){
console.log(data);
});
We pass a data object to our Ajax wrapper, call a controller with an action (in this case downloadPayRoleReport translates to ajaxDownloadPayRoleReport()) which in turn returns an HTML table, which I can view via console.log(data)
I want to use the above linked plugin on data to then turn this html table into a csv and instant download.
Question is, can this be done?
You can create a jQuery object from the table. Then you can do anything to the jQuery object just like you could if it were actually on the DOM. You can always put the table on the DOM as well off screen, but I think any chance you have to not touch the DOM you should take it.
var myTable = $(data);
myTable.mySpecialTableMethodToExportToCSV();

Categories