why $(element) not works directly. but works in function - php

When i try to select any element which is the result of ajax call it don't get selected using $(element)
but when i try to select that element in any function it will selected
Example: if i select an element with id change.
hello.php is
<?php
echo '<span id="change"> hello </span>';
?>
html in main.php is
<div id="content">
</div>
and script in main.php
<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
$("#change").css({"backgroundColor":"red"});
</script>
this script don't change the color of span , I know it will not work because at the time when 2nd statement is executed their was no element with id change,
and $("#element") can't find the element with id change
But when i try $("#change") in any function it will change the color of span.
for example if i use
<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
setTimeout(function(){$("#change").css({"backgroundColor":"red"});},0);
</script>
Please note i set the delay time to 0 sec. But this works and change the color of span with id change. I mean now the $("#change") can find the element with id #change
and if i use $("#change") in ajax function then also it works.
<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
$.post("example.php",function(r,s){$("#change").css({"backgroundColor":"red"});});
</script>
Can someone explain why this happen , why in other two examples $("#change") selects the element. even their is no delay in executing the function

Is all about timing. When you get content from the server and you try to inject it in DOM, it will take a bit to render. When you use setTimeout with whatever value, you push the inner function in the event loop. The result is that it will be executed after minimum time that you specify - in your case 0, but only when the stack is empty. During this time, things are rendering in DOM and you get to have access to those elements. You should watch this video for a much better explanation of what is going on: https://www.youtube.com/watch?v=8aGhZQkoFbQ

This is due to the asynchronous nature of your post command. The rest of the script doesn't get halted till the post get finished. Rather than that, it get's executed even though the post command is already under progress. What you do with the timeout function is that you delay the execution of the jquery selection by a fraction of time, and this gives the time for the post to finish.

Related

PHP timer output into HTML div every second

I developed a PHP countdown timer (3hrs specifically in hrs, mins and secs) - countdown.php. The output is within a <div> tag in another page - index.html.
I want an AJAX or Javascript that would make the output dynamic (that is changing figures like normal timer). I do know that AJAX can make the page refresh every second in the background (asynchronously), but I've not been able to achieve that.
Presently, the output only changes when I refresh the HTML page. I also want a PHP script to be triggered when countdown gets to zero.
countdown.php
<?php
//some codes left out
$remainingHour=floor($secsdiff/3600);
$remainingMinute=floor(($secsdiff-($remainingHour*60*60))/60);
$remainingSecond=floor(($secsdiff-($remainingHour*60*60))-($remainingMinute*60));
?>
index.html
<div id="timer">
<?php echo "$remainingHour hours, $remainingMinute minutes,
$remainingSecond seconds";?>
</div>
Make sure your using JQuery in your HTML page (Follow the tutes on the JQ website if this is new to you, It's really very easy)
Then once your up and running with that, use JQuerys Get function to update your div:
http://api.jquery.com/jQuery.get/
You should be able to get it up and working in 30 mins or less, it's very simple.
If this is just a small item on a larger page, I would use Ajax or JavaScript. With Ajax you should be able to check for 0 values and if it is reached, notify that to the server, where server will perform specification action.
You probably can do that with JavaScript a s well which might be more desirable for such small tasks.
You should use setTimeout function in javascript, see https://stackoverflow.com/search?q=[javascript]+setTimeout&submit=search
When the timer will be over, simply call a new URL to execute the next php script (still in javascript), like :
document.location.href = http://foobar.tld/new_page

How do i use this javascript variable properly?

I am trying to expand on some code written by someone else, but I am having trouble using one of the javascript variables. If I set it in the title of a div or something similar like so:
$("#test12").attr("title" , ccode);
then it works fine and the title of the div is 'CA', which it should be. But if I try to put it into the text area of the div, then it tries to run a function or something but I can't see where it's doing it.
Is there a way I can convert it to simple text and stop it from running any functions?
Thanks for any help
Edit:
This is all of the code I can see at the moment:
<script>
//<!--
function loadForeignOffices(ccode){
//load window with details...
$('#iframe_3').attr("src", "<?php echo $html->url("/", true); ?>erc/maps/contacts/"+ccode);
$("#test12").attr("title" , ccode);
}
//-->
</script>
Basically what I'm trying to do is use the ccode variable because I want to display CA on the screen, but when I try to do that it seems to run some other function and fails, and doesnt show CA.
You may need to brush up on your jQuery dot-operators:
.load() is an ajax call that will load the contents of () into the selected element. In one of your comments you mention you are trying to do this $("#test12").load(ccode); which is inherently silly, if ccode is the string "CA"
.attr() will change the attributes of the selected element. If you are trying to display "CA", $("#test12").attr("title" , ccode); this will clearly not accomplish that -- As "CA" is added to the title attribute. As in <div id="test12" title="CA"></div>
Perhaps what you are looking for is .html() which inserts the string into the selected element. Or even .innerText()
Why don't you spend some time reading the jQuery documentation. A little bit goes a long way!
Keep in mind your PHP code is executing first on the server, then your javascript.
Here's a JS Fiddle as a start: http://jsfiddle.net/QsFJ4/3/

update JS Var on chaging of a php var

I got this prob. In a web page I have a DIV that display a counter ( a PHP variable, $count). I have also a JS function that change the INNERHTML property of the DIV. I'm not able to change the js var on the changing of the PHP one.
HTML
<DIV id="counter">0</DIV>
PHP
while (----) {
do_something;
$count++;
}
JS
function ChangeDiv() {
document.getElementById("counter").innerHTML = // here the value of $count;
}
setinterval("ChangeDiv()",3600);
I want to to refresh the DIV every sec inserting in it the value of $count... but doing
document.getElementById("counter").innerHTML = <?php echo($count); ?>;
is wrong 'cause it will output just the initial value of $count.
I tried to insert a parameter in the function ChangeDiv, but in that way I had to call the function every time $count changed, echoing a
echo("<script>ChangeDiv('".$count."');</script>");
...that's really not functional.
Someone knows a simpler way to do it??
You need to use some sort of AJAX implementation to get this to work.
It will allow Js to query your PHP script to get a new value for $count
It looks like you might be writing some sort of progress bar?
Note that PHP runs on the server side and generates HTML / Javascript. Javascript runs on the client side.
What you would have to do to show a progress bar like that is to output <script> snippets that update your DIV element. If you put the line
document.getElementById("counter").innerHTML = "<?php echo($count); ?>";
(notice the quotes)
into the loop, and output buffering is turned off, and the counter HTML element was output before, you will get some sort of progress bar.
However, depending on what you want kind of action you are running behind that progress bar, an Ajax driven progress indicator may be much, much more elegant.

strategy to split up php output into smaller outputs (ajax, php) (nested ajax calls, ajax within ajax?)

I don't know the correct terminology to search for the solution. Please suggest a strategy to break up the php output into small chunks and pass them stepwise to ajax's responseText.
The project is an ajax webpage that takes a text string (lastname) and passes it to a php program. The php code takes the last name and randomly fetches 3 people with different first names, and puts it into an array. Once that is done, the php code will contact outside servers to retrieve info associated with each name, and output the info to a div of the webpage. The process of getting data from the outside servers is very slow.
This code is basically done, but the whole process takes a very long time to generate the output on the screen. Is there a way (a strategy) to output each step of the php code immediately instead of having to wait for the complete code?
My pseudo php code is like this:
<?
get 3 names; //output this immediately
foreach name { get phone number }
?>
Alternatively, I could get a name and the phone#, and output it immediately before moving to the next name.
Are there php or ajax codes/functions/strategies that would achieve this? Please suggest solutions or search keywords.
Addition/Edit:
Thanks for the suggestions. Is it possible to execute another ajax call after the parent ajax call? I initially went that route, but my testing of nested js/ajax call did not work. It could be due to syntax errors, please look over the code.
The test code in the testajax.php (or testajax.html) file for the ajax call XHR.responseText is
<div id="name" >JAM <div id="numa" >
<br />
<br />text holder >>
<script type="text/javascript">
var pid=document.getElementById("numa").parentNode.id;
alert (pid);
document.getElementById('numa').innerHTML += 'append text>> ';
document.write(' docwrite');
</script>
</div>
</div>
<br />
<br />ending text
If I view the file testajax.php (or testajax.html) directly, I would see
JAM
text holder >> (an alert window) append text>> docwrite
ending text
but if I do an ajax call of the testajax.php file, all I would see is
JAM
text holder >>
ending text
The code inside the <script> </script> tags does not run after the ajax call
can someone explain this, and offer a fix?
TIA
Without knowing the actual code and code-based answer is hard. But, here's an idea.
When you get the three names, return them to the page and display them. Then, for each one, in a different AJAX call, call the phone info. I'm not positive if javascript will make all three calls independently of each other, but that would at least display all 3 names, and then each phone info one at a time.
Edit
Workflow:
Javascript sends a name to php via ajax.
PHP returns 3 names to js
js appends 3 divs to the page, one with each name.
js makes 3 requests to php, sending 1 name per request.
php returns phone info / whatever else to js
js takes info and adds it to the respective div
In theory, yeah, you can call flush() (and ob_flush() as necessary) to ensure output is sent from PHP.
However, the web server may add buffering of its own outside of the scope of PHP (most commonly, if mod_deflate is in use on Apache); and you'd have to be careful about delimiting your response chunks so they're not read by the browser until a chunk is complete.
In any case not all browsers can read the responseText from an XMLHttpRequest until the request is fully complete. So for it to work on all clients, you'd have to try a different mechanism, such as the old-school HTML-iframe-containing-multiple-<script>s.
Summary: it's a bunch of hassle, and perhaps not really worth it. A simpler-to-deploy possibility would be separate AJAX requests for each name.

Value of variable changes once out of the click function in jQuery

this is the continuation of my previous question. Since I just logged in that day without an Open Id, I don't know how to login to that account and edit further. So I created a new Open Id enabled account and posted this as a new question.
Now I have the code like this. Inside the onclick event, the value is stored in the $selectedId correctly. But When I try to pass that value in the url, I do not get the correct value. The last value in the for loop is passed.
<script type="text/javascript">
$(document).ready(function(){
<?php foreach ($Forms as $r): ?>
$("<li><a id='<?=$r['Form']['id'];?>' data-attr='Formentries' href='#'><?=$r['Form']['name']?></a></li>").appendTo("#headers").click(function () {
<?php $selectedFormId=$r['Form']['id'];?>
alert("selId: "+<?php echo $selectedFormId;?>); //here the selected id is alerted
});
alert("outside the loop"+<?php echo $selectedFormId;?>); //here the last value in the loop is alerted
});
Once out of the click function, the value of $selectedFormId changes to the last value in the array. Can someone help me with this?
Actually what I am trying to achieve is, I list a set of Forms as links, and when I select the links I want its id to be saved in a php variable. I want it particularly be saved in a php variable coz after I select a Form I have an option to export the entries in the form through another link
<a href="localhost/FormBuilder/reports/export/<?php echo $selectedFormId;?>" class="thickbox button" title= "Export" >Export</a> .
So I want the id in there,so that I could pass it to the export function in the controller.
I also get the selected id in a javascript variable as
formid=$(this).attr("id");
but I do not know how to pass this value to the export function in the controller.
I don't know if i've understood your question very well but the $selectedFormId value is set inside the loop, so everytime the loop is executed the variable is set and when the loop finishes $selectedFormId gets the last processed value. I think you should set it outside the loop.
as you are declaring it inside the block so it is not available outside;
either you declare it before the $(document).ready block or finish its usage it inside this block itself.
As far as I can see you are setting $selectedFormId inside each loop in the iteration, so the assignment code will only be set when the click event is fired.
Therefore, logically, when you exit the loop, $selectedFormId will be the last item in the array. Are you meaning to put a condition around the assignment? Don't forget, the server side code will execute regardless! It won't care about client side conditions or closures!
if (something){
<?php $selectedFormId=$r['Form']['id'];?>
}
And, again echoing the above comments, you should really be trying to achieve code separation. The above really is tag soup!
You are mixing client and server-side code -- the code you wrote seems like you're expecting a JavaScript function on the client-side to magically set a PHP variable on the server-side, when in reality that type of operation is not possible.
What you should maybe do is have your click event set a variable on the client-side. Then set an onclick on your export link to construct a URL and redirect to it based on the locally stored variable value.
That's probably not the best solution, but it would be one option.

Categories