Call javascript function on every page show. (php get variables) - javascript

I have this JavaScript function in the header of my site. On first page load everything works as expected, i get the response back onsuccess is fired and it updates the div tag specified.
I use var reqid = "<?= $_GET['id']; ?>"; to get the id of the page.
When i navigate through my app and load the same page but with a different id in the url string var reqid = "<?= $_GET['id']; ?>"; does not update and reverts to the previous value. how can i get this to update every time the page is shown?
var request = function() {
function onSuccess(data, status)
{
$("#notif").fadeIn(2000);
data = $.trim(data);
if(data == "SUCCESS"){
$("#notif").html('<div class="notification-box-green"> <img class="notification-icon" src="images/lists/list-tick.png" alt=""> <p class="notification-text">Success!</p></div>').fadeIn(4000);
$('#notif').fadeOut(4000, function() {
});
} else if(data == "LIMIT")
{
$("#notif").html('<div class="notification-box-yellow"><img class="notification-icon" src="images/lists/list-warning.png" alt=""><p class="notification-text">Please Wait!</p></div>').fadeIn(4000);
$('#notif').fadeOut(4000, function() {
});
} else if(data == "NO_WIFI")
{
$("#notif").html('<div class="notification-box-yellow"><img class="notification-icon" src="images/lists/list-warning.png" alt=""><p class="notification-text">Connect to hostspot!</p></div>').fadeIn(4000);
$('#notif').fadeOut(4000, function() {
});
}
}
var reqid = "<?= $_GET['id']; ?>";
$.ajax({
type: "POST",
url: "req_sub.php",
cache: false,
data: "id="+ reqid,
success: onSuccess
});
}
The function is called with a button click.
EDIT
I modified my code slightly and placed it into its own js file.
the id now seems to update as expected.
one problem still remains, the code in onsuccess doesnt execute second time round. first load or on a refresh the div changes as expected, navigation back to the page with a different id in the url doesnt update the div.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var request = function() {
var reqid = getUrlVars()["id"];
function onSuccess(data, status)
{
Edit 2
I cloned the div and replaced it when i was done.
var divClone = $("#notif").clone();
var request = function() {
var reqid = getUrlVars()["id"];
function onSuccess(data, status)
{
$("#notif").fadeIn(2000);
data = $.trim(data);
if(data == "SUCCESS"){
$("#notif").html('<div class="notification-box-green"> <img class="notification-icon" src="images/lists/list-tick.png" alt=""> <p
class="notification-text">Success!</p></div>').fadeIn(4000);
$('#notif').fadeOut(4000, function() {
$("#notif").replaceWith(divClone);
Doubt this has been the proper way to achieve my goal, will further test after sleep and update with results.

Related

Update image after it's been clicked, without reloading page

I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';

Automatic run a JavaScript when there is a new data get by Ajax

Now I have two javascript, one is I called auto_refresh.js which I use ajax to continuously get new data from mysql database (This part is done).
auto_refresh.js
var mainDisplayCacheData;
var mainDisplayData = $('.aside').html();
var auto_refresh = setInterval(
function()
{
$.ajax({
url: 'main_display.php',
type: 'POST',
data: mainDisplayData,
dataType: 'html',
success: function(mainDisplayData){
if(mainDisplayData !== mainDisplayCacheData){
mainDisplayCacheData = mainDisplayData;
$('.aside').html(mainDisplayData);
}
}
})
}, 1000);
display.php
<div class="aside">
<?php
$tm = TicketManager::getInstance();
$tm->displayMainTicket();
$ticket = $tm->mainTicketSound();
?>
</div>
ticketmanaget.inc
public function mainTicketSound()
{
$conn = DBManager::getConnection();
$query = "SELECT queue_id, ticket_name FROM queue
WHERE DATE(response_time) = DATE(NOW())
ORDER BY response_time DESC
LIMIT 1
";
$results = #$conn->query($query);
if ($results === FALSE or $results === NULL)
throw new DatabaseErrorException($conn->error);
if ($results->num_rows < 1)
{
$results->close();
}
else
{
while($rows = #$results->fetch_array())
{
$ticketname = $rows['ticket_name'];
return $ticketname;
}
}
}
audio function
var input = "<?php echo $ticket; ?>";
var files = ["0.mp3", "1.mp3",
"2.mp3", "3.mp3",
"4.mp3", "5.mp3",
"6.mp3", "7.mp3",
"8.mp3", "9.mp3"];
var audio = document.createElement("audio");
var audioIdx = 0;
var playById = function (id) {
audio.src = files[input[id]];
audio.play();
};
audio.addEventListener('ended', function () {
audioIdx++;
if (audioIdx >= files.length) audioIdx = 0;
playById(audioIdx);
});
audio.src = files[input[audioIdx]];
audio.play();
Then I have another script which is used to play audio files. Exactly which files to play is based on the new data get by ajax from database. In my case, I want my second script run the files based on the variable $ticket.
The audio script is done and run perfectly. However, it only play the sound when I refresh the page. I need it to run automatically when the auto_refresh.js get new data. Please help, thanks.
This might help "big picture".
Note that the code in display.php only runs one time - when page initially loads. You need that code to run each time new data is received.
Therefore, you must create a new php file that accepts via POST the new data, and returns (via echo not return) the desired $ticket value. Call this page as an AJAX call inside the success function of the first AJAX call. Something like this:
auto_refresh.js
var mainDisplayCacheData;
var mainDisplayData = $('.aside').html();
var auto_refresh = setInterval(
function(){
$.ajax({
url: 'main_display.php',
type: 'POST',
data: mainDisplayData,
dataType: 'html',
success: function(mainDisplayData){
if(mainDisplayData !== mainDisplayCacheData){
mainDisplayCacheData = mainDisplayData;
$('.aside').html(mainDisplayData);
$.ajax({
url: 'new_php_file.php',
type: 'post',
data: mainDisplayData,
success: function(axData){
var files = ["0.mp3", "1.mp3",
"2.mp3", "3.mp3",
"4.mp3", "5.mp3",
"6.mp3", "7.mp3",
"8.mp3", "9.mp3"];
//below element already exists. You should update it rather than creating another
var audio = document.createElement("audio");
var audioIdx = 0;
var playById = function (id) {
audio.src = files[axData[id]]; //axData returned by AJAX
audio.play();
};
audio.addEventListener('ended', function () {
audioIdx++;
if (audioIdx >= files.length) audioIdx = 0;
playById(audioIdx);
});
audio.src = files[input[audioIdx]];
audio.play();
}
});
}
}
});
}, 1000);
new_php_file.php
<?php
$new_data = $_POST['mainDisplayData'];
//insert code required to run lines that follow, and/or modify as required
$tm = TicketManager::getInstance();
$tm->displayMainTicket();
$ticket = $tm->mainTicketSound();
echo $ticket;
Call the sound playing function in the other script in this block:
if(mainDisplayData !== mainDisplayCacheData){
// e.g. otherScriptFunction();
}
On the Server-side: You should echo the "$ticket" variable.
On the Client-side: Call your sound playing function inside the 'success' ajax callback:
if(mainDisplayData !== mainDisplayCacheData){
PLAY_SOUND(mainDisplayData);
}

How to print JavaScript based on Ajax request?

Allow me to elaborate.
I have this Ajax script which is fetching for one thing. The refresh_on.
What does it do? It either returns 0 OR 1.
function startRefresh() {
setTimeout(startRefresh, 60000);
$.ajax({
url: 'refresh.php',
type: 'POST',
dataType: 'JSON',
data: {task: "reload"},
success: function(data) {
$.each(data, function(i, attr){
if (attr.refresh_on == 0) {
//this doesn't work
/*Write/return this in JavaScript:*/ line[1]="Offline.";
} else {
//this doesn't work
/*Write/return this in JavaScript:*/ line[1]="Online.";
};
})
}
});
}
If the ajax returns with refresh_on == 0 OR refresh_on == 1 - I want it to print its respective array item. It must be an array item.
</head>
<body>
<script type="text/javascript">
var line=new Array()
startRefresh();
//output either "line[1]=\"Offline.\""; or "line[1]=\"Online.\"";
</script>
</body>
This is the PHP file:
if (isset($_POST['task']) && $_POST['task'] == "reload") {
$stmt = $connection->prepare("SELECT refresh_on FROM refresh");
$stmt->execute();
$result = $stmt->get_result();
$encode = Array();
while ($row = $result->fetch_assoc()) {
$encode[] = $row;
}
echo json_encode($encode);
}
If it matters - this is the JSON response:
[{"refresh_on":1}]
Is there a way to insert/output/print the array item using the function?
Any help would be appreciated.
So there's a couple things that might be going on here, but to begin, you're wrapping your variable in a quote, so all that is happening is a string is being made and immediately being dropped to the floor. Let's start off by doing something like the following:
function startRefresh() {
setTimeout(startRefresh, 60000);
$.ajax({
url: 'refresh.php',
type: 'POST',
dataType: 'JSON',
data: {task: "reload"},
success: function(data) {
$.each(data, function(i, attr){
if (attr.refresh_on == 0) {
//this doesn't work
line[1] = "Offline.";
} else {
//this doesn't work
line[1]= "Online.";
};
})
}
});
}
Now, if I recall correctly, the ajax function is going to be calling your success callback, which is going to take over your local scope. I don't believe line is going to be accessible to that callback, so we should/could actually move that callback to its own function within a closure:
<script type="text/javascript">
(function() {
var line = [];
startRefresh();
function startRefresh() {
setTimeout(startRefresh, 60000);
$.ajax({
url: 'refresh.php',
type: 'POST',
dataType: 'JSON',
data: { task: "reload" },
success: refreshResponse
});
}
function refreshResponse(data) {
$.each(data, function(i, attr) {
if (attr.refresh_on == 0) {
line[1] = "Offline.";
} else {
line[1] = "Online.";
}
});
}
})();
</script>
We've wrapped that in a self executing function to give us some nice encapsulation to work with, and because line is in a function which refreshResponse is found, that variable should be accessible to it.
But we're not done yet!
For one, we could easily make that variable assignment a little easier, like so:
line[1] = (attr.refresh_on == 0) ? "Offline." : "Online.";
...and we're also going to want to triple up on that equality statement, just to avoid variable coercion:
line[1] = (attr.refresh_on === 0) ? "Offline." : "Online.";
Give that a shot and let's see where we're at.
Not sure what you are expecting "line[1]=\"Offline.\""; to do, but it's not going to do anything. Perhaps you mean: line[1]= "Offline";? Try putting this line of code there instead to test that it's working: console.log('Offline');
If the line is getting executed and you see the output in your console, you would just have to target some HTML element that you want to put the "Offline" string into, for instance:
<div id="status"></div>
<script>
....
var status = document.getElementById("status");
if (attr.refresh_on == 0) {
status.textContent = "Offline";
} else {
status.textContent = "Online";
};
....
</script>

How to use the url hash to load a particular page after a refresh?

So, I am using url hashes that helps me to bring particular content up on hashchange. Now when i'm on some particular content and i refresh the whole page, i'm having that hash in the url and still not getting the content indicated by that hash.
Say my url is :
http://localhost/user and i clicked on details and it turned my url into following :
http://localhost/user#!detailsand i'm having the details page.
But having the above as my url when i reload the page, the hash remains same and there is no change in hash which does not invoke the function that i've bind with the hashchange event.
Also i cannot get the hash to the server side without sending ajax request everytime a user reloads using beforeunload.
Any Suggestions?
My code :
var pages = {};
pages['home'] = ""; pages['details'] = ""; pages['reviews'] = ""; pages['favs'] = "";
pages['likes'] = "", pages['gallery'] = "", pages['visited'] = "", pages['coupons'] = "";
$(window).bind('hashchange', function(event) {
var curr_hash = event.target.location.hash;
var page_to_load = curr_hash.substr(2);
var loadurl = "/ci_theyaw/user/user_" + page_to_load;
load_page(loadurl, page_to_load);
});
function load_page(page, toload){
// alert(pages[toload]);
if(pages[toload] == "") {
var post_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: 'POST',
url: page,
data: post_data,
dataType: "html",
success : function(data) {
page[toload] = data;
$('.right-pane').html(data);
},
error : function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
console.log(xhr.responseText);
alert(thrownError);
}
});
}
else {
$('.right-pane').html(page[toload]);
}
}
You need to run the code attached to hashchange on load, in case someone refreshes the page, or even types it directly in to the browser. Try this:
var hashUpdate = function(curr_hash) {
var page_to_load = curr_hash.substr(2);
var loadurl = "/ci_theyaw/user/user_" + page_to_load;
load_page(loadurl, page_to_load);
}
$(window).bind('hashchange', function(e) {
hashUpdate(e.target.location.hash);
});
window.location.hash && hashUpdate(window.location.hash); // onload, if there was a fragment in the URL
$(function(){
var curr_hash = window.location.hash;
var page_to_load = curr_hash.substr(2);
var loadurl = "/ci_theyaw/user/user_" + page_to_load;
load_page(loadurl, page_to_load);
});

I don't understand AJAX callbacks

I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});

Categories

Resources