yii2 hide model name from url in GET Method - javascript

I have a script that switches images in a certain amount of time. But on my page, the images are not displayed because they get method gets the wrong URL: GET http://schedule/monitor/img/math/22.03/22.03.JPG 404 (Not Found). The correct URL should be like this:
http://schedule/img/math/22.03/22.03.JPG. How to hide the model name from image src when I get this from js script?
slider.js
$(document).ready(function () {
$.ajax({
type: 'GET',
dataType: 'json',
url: '/monitor/insert_math',
data: 'json',
success: function (data) {
var i = 0; //START POINT
var unfiltered_images = data; //UNFILTERED IMAGES ARRAY
var time = 30000; //TIME BETWEEN SWITCH
var images = unfiltered_images.filter(file => file.endsWith('.JPG')); //FILE FILTER BY EXTENSION
console.log(images);
if (images.length != 0) {
function changeImg() {
document.getElementById('slide').src = images[i];
if (i < images.length - 1) { //CHECK IF INDEX IS UNDER MAX
i++; //ADD 1 TO INDEX
} else {
i = 0; //RESET BACK TO 0
}
setTimeout(changeImg, time); //RUN FUNCTION EVERY X SECONDS
}
window.onload = changeImg(); //RUN FUNCTION WHEN PAGE LOADS
}
}
});
});
1311.php
<div class="info_block">
<img id="slide" height="626px">
</div>
Path to PHP file:

document.getElementById('slide').src = "/"+images[i];
answer by Shringiraj Dewangan

Related

Asp.net webform infinity scroll

I have a page shows product catalog populated by a webmethod.
When user click on image he is redirect to details page.
When user come back to catalog id like page scroll bottom at the product visited
How can i accomplish this
my html
<div class="articoli">
</div>
my javascript
<script>
$(document).ready(function () {
var Skip = 9;
var Take = 9;
function Load(Skip, Take) {
$('#divPostsLoader').html('<img src="Images/loading.gif" height="100" />');
$.ajax({
type: "POST",
url: "page.aspx/LoadProduct",
data: "{ Skip:" + Skip + ", Take:" + Take + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") {
//accodo dati a div
$('.articoli').append(data.d);
}
$('#divPostsLoader').empty();
},
error: function () {
alert('error');
}
})
};
$(window).scroll(function () {
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
Load(Skip, Take);
Skip = Skip + 9;
}
});
});
my c# webmethod
[System.Web.Services.WebMethod]
public static string LoadProduct(int Skip, int Take)
{
StringBuilder GetProduct = new StringBuilder();
MyDataBaseEntities db = new MyDataBaseEntities();
var prod = (from a in db.TAB
select a).Skip(Skip).Take(Take);
foreach (var a in prod)
{
var Codart = a.Codart;
var Prezz = a.Prezz;
var pathimg = a.pathimg;
GetProduct.Append("<div class=\"col-md-4\">");
GetProduct.Append("<div class=\"col-md-6 text-left\">");
GetProduct.AppendFormat(string.Format("<a href='Details.aspx?Articolo={0}' class=\"codart\" >", Codart));
GetProduct.AppendFormat("<span class=\"codart\">{0}</span>", Codart);
GetProduct.Append("</a>");
GetProduct.Append("</div> ");
GetProduct.Append("<div class=\"col-md-6 text-right\" style=\"color:gray;font-size:large;\">");
GetProduct.AppendFormat(string.Format("{0:c}", Prezz));
GetProduct.Append("</div> ");
GetProduct.AppendFormat(string.Format("<a href='Details.aspx?Articolo={0}' class=\"codart\" >", Codart));
GetProduct.AppendFormat(string.Format("<img src='{0}' class='img-responsive MyImage' alt='{1}'/>", pathimg, Codart));
GetProduct.Append("</a>");
GetProduct.Append("</div> ");
}
return GetProduct.ToString();
}
how can i scroll bottom at page load?
Try adding an Id to the item(s) you want to scroll to. You can then, depending on how you want to tackle it, either href or assign said Id through a script to initiate a scroll. Here you can see more details on how to scroll to a specific part of your page by using the component's Id.
I would add a unique Id to each item in your list.
Then I would write a script to read/set a variable to which item to scroll to.
Mind you, I'm writing this on a whim so you might need to correct or alter it to fit your needs.
You can use this to save and read cookies with jquery.
The script could be something like this:
var scrollToId;
$(document).ready(function () {
var cookie = $.cookie('last_clicked_id');
if (cookie != '') {
scrollToId = cookie;
} else {
scrollToId = '#';
}
$("html, body").animate({ scrollTop: $(scrollToId).offset().top }, 1000);
});
$('.productItemClass')
.on('click',
function() {
$.cookie('last_clicked_id', $(this).attr('id'));
});
use this and set the variable sc
var sc;
var scroll;
var loop = setInterval(function() {
sc = window.scrollTop;
if (scroll === null) {
localstorage.setItem("bgc", sc);
}
}, 10);
window.onload = function() {
scroll = localstorage.getItem("bgc");
if (scroll !== null) {
window.scollTop = scroll + "px";
}
}

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);
}

ajax function auto reload

Hello i am getting data from a php file in json format,all works fine.I would however desire that this function reloads every say 3000millisecs thus updating the data.
How do I achieve this?
function loadFbill(hsid)
{
// Display a loading icon in our display element
$('.list-item-display').html('<span><img src="img/progress.gif" /></span>');
// Request the JSON and process it
$.ajax({
type:'GET',
url:""+xhr_path+"js_on.php",
data:"hid="+hsid+"&subscribers=paid",
success:function(feed) {
// Create an empty array to store images
var thumbs = [];
// Loop through the items
for(var i=0, l=feed.response.length; i < l && i < 6; ++i)
{
// Manipulate the image to get thumb and medium sizes
var payee = feed.response[i].result_paid;
var transaction_m = feed.response[i].result_payment_details;
var ptime = feed.response[i].result_time;
var plan = feed.response[i].result_plan;
var payee_num = feed.response[i].result_num;
var localhs = feed.response[i].result_hs;
var transaction_date = feed.response[i].result_payment_date;
var diff_date = feed.response[i].result_time_diff;
// Add the new element to the array
thumbs.push("<div class=list-item><div class=list-datetime><div class=time>"+ptime+"</div></div><div class=list-info><img src=img/pesa/ps_"+transaction_m+".jpg height=28 width=28 class=img-circle img-thumbnail/></div><div class=list-text><a href=# class=list-text-name> "+payee+" </a><p>"+payee_num+" <span class=icon-calendar></span> "+transaction_date+" <span class=icon-calendar-empty></span>"+diff_date+"<span class=icon-globe></span> "+localhs+" </p></div><div class=list-controls> "+plan+"</div></div>");
}
// Display the thumbnails on the page
$('.list-item-display').html(""+thumbs.join('')+"");
// A function to add a lightbox effect
addLB();
},
dataType:'json'
});
}
You can simply add setTimeout into ajax request callback function:
function loadFbill(hsid) {
// Display a loading icon in our display element
$('.list-item-display').html('<span><img src="img/progress.gif" /></span>');
// Request the JSON and process it
$.ajax({
type: 'GET',
url: "" + xhr_path + "js_on.php",
data: "hid=" + hsid + "&subscribers=paid",
success: function (feed) {
// ... all your code untouched
setTimeout(loadFbill, 3000); // <-- and reload again
},
dataType: 'json'
});
}

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

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.

Using swipe.js with $.ajax() content

I am using Brad Birdsall's Swipe.js plugin as a touch friendly, library agnostic plugin for a slider in my current mobile project. When I populate the slider on page load, everything works great. However if I try and populate the slider with $.ajax() on click, the slider will receive all of the slides, but is not responsive to touch events, or any of the methods associated with the slider.
The general slider HTML structure looks like this:
<div id="slider" class="swipe">
<ul>
<li style='display:block;'>
<img src="/someImageUrl.jpg" />
</li>
<li style='display:none;'>
<img src="/someImageUrl.jpg" />
</li>
</ul>
</div><!-- .swipe -->
<nav>
PREV
NEXT
</nav>
I am using an $.ajax() response to populate the <li><img src="..." /></li> on a click event handler in my doc.
Here's my JS:
$.ajax({
url: "process.inc.php?vehicleId=" + vehicleId,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var swipeSlides = "";
for (i = 0 ; i < data.length; i++) {
var photoUrl = data[i].photoUrl;
var photoArray = photoUrl.split("|");
if (photoArray.length <= 1) {
list += "<img src="+photoArray[i]+" />"
} else {
for (i = 0; i < photoArray.length; i++) {
swipeSlides += "<li><img src='"+photoArray[i]+"' /></li>"
}
var prevNext = "<nav>PREVNEXT</nav>"
var sliderElement = $(self).parent().find("#data #slider ul");
sliderElement.find("li, nav").remove();
sliderElement.append(swipeSlides, prevNext);
$.getScript('../assets/js/swipe.js');
var slider = new Swipe(
document.getElementById('slider')
);
};
};
} // end success function
}); // end AJAX
This will sucessfully populate my page with all of the necessary content, but when I click one of the previous or next puttons, I get this error in my console:
Uncaught TypeError: Object #<HTMLCollection> has no method 'next'
Which tells me that my script is not being loaded into the page appropriately, or, my slider is not being instantiated at the proper time.
I have tried executing my code inside of the $.getScript() method like this:
$.getScript('../assets/js/swipe.js', function(data, textStatus, jqxhr) {
for (i = 0; i < photoArray.length; i++) {
swipeSlides += "<li><img src='"+photoArray[i]+"' /></li>"
}
var prevNext = "<nav>PREVNEXT</nav>"
var sliderElement = $(self).parent().find("#data #slider ul");
sliderElement.find("li, nav").remove();
sliderElement.append(swipeSlides, prevNext);
var slider = new Swipe(
document.getElementById('slider')
);
});
Or even just using a good old fashioned <script src="/assets/js/swipe.js"></script> before my jQuery script executes, and I keep getting the same exact error.
If anyone has any suggestions I will be forever grateful.
I figured out the problem.
In order to make the instantiation of the Swipe element recognized, I needed to use $.globalEval() inside of the $.getScript() function.
Heres my working code:
$.ajax({
url: "process.inc.php?vehicleId=" + vehicleId,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var list = "";
for (i = 0 ; i < data.length; i++) {
var photoUrl = data[i].photoUrl;
var photoArray = photoUrl.split("|");
if (photoArray.length === 1) {
list += "<img class='noPhoto' src="+photoArray[i]+" />";
var parent = $(self).parent().find("#data");
parent.find("table, .noPhoto").remove();
parent.append(list);
} else {
list += "<div id=\"slider\" class=\"swipe\"><ul>";
for (i = 0; i < photoArray.length; i++) {
list += "<li><img src='"+photoArray[i]+"' /></li>"
}
list += "</ul><nav>PREVNEXT</nav></div>";
var parent = $(self).parent().find("#data");
parent.find("table, div").remove();
parent.append(list);
$.getScript("../assets/js/swipe.js", function(data, textStatus, jqxhr) {
$.globalEval("var slider = new Swipe(document.getElementById('slider'));")
});
};
};
} // end success function
}); // end AJAX
Hopefully this helps someone else down the road.
Why use getScript in the first place? Append it to your other javascript files as (before your javascript file), then new Swipe() should work.
Also, if you want to call functions of your Swipe object later, you should declare the var outside your ajax function. Example:
var mySwipe;
document.ready(function(){
//...
});
function pullFromAjaxFunction() {
//... do some more stuff
mySwipe = new Swipe(...)
}

Categories

Resources