Recently I made a small refactor of my application and the paginated tables have stopped working and I think it is because it is not taking the current page that is passed by GET parameters in the URL.
Before the refactor I had a class index.php that included all code HTML along with PHP code, but to optimize and not duplicate code, I started to separate what would be, the navigation menu, the top navbar, and the content in different files .php, so that when I enter a website using this code I load the entire page:
$(function () {
$.get("../navbar.php", function (data) {
$("#navbar-menu").append(data);
});
$.get("../menu.php", function (data) {
$("#sidebar-wrapper").append(data);
});
$.get("./content.php", function (data) {
$("#divPersonal").append(data);
});
});
When I enter for example one of these pages where I have a table with pagination and type links:
http://localhost/app/modules/users/index.php?page=2
When I reload the index.php and it loads with javascript the "content.php" where I have the PHP call of "getUsers()", it should take the URL and the "page" parameter but it is not doing it, and it seems that it is due to the way my index.php is being mounted. I can not find an optimal solution to solve this problem. I take the parameters directly when I call the function with an if:
if (empty($_GET['page'])) {
$firstPage = 0;
$actualPage = 1;
} else {
$actualPage = $_GET["page"];
$firstPage = ($actualPage - 1) * $SIZE;
}
If anyone can help me, thank you.
Name the pages with them titles and make like this to switch between pages:
if(isset($_POST["page"]))
{
switch ($_POST["page"]) {
case "login":
include '/folder/page.php';
}
}
Related
I have a webpage which is in some state currently, that is, some divs are shown and some are hidden. I am using cookies to post data to Python CGI scripts. So now, when I click a button, I want it to send data to the python cgi file, and so, I want the button reload the page, so that, due to reloading the cookie can be updated and thus, the updated cookie can be sent to the python-cgi file. (Also, I am using iframe to display the python-cgi file inside my html webpage).
Now, the methods such as location.load() doesn't work as it reloads the webpage into the initial state where all my divs were hidden but I want it to be in the same state as before reloading where some divs were shown and some were hidden.
How can I achieve that? Please help me with that! Thanks!
The are two solutions I can think of to this problem:
JavaScript State-Saving Solution
Rewrite code as a REST API
Solution 1: JavaScript State-Saving Solution
You can write a JavaScript function for when the button is clicked. And another one for when the page is loaded. Using the localStorage API, you can then save the current state of the page.
function buttonClickedEvent() {
const div1Visible = !document.querySelector('#div1').hidden || true;
const div2Visible = !document.querySelector('#div2').hidden || true;
const userInput = document.querySelector('#user-input').value || '';
localStorage.setItem('page-state', JSON.stringify({
div1Visible,
div2Visible,
userInput
}));
window.location.href = '/path/on/server';
}
function setupPage() {
const state = localStorage.getItem('page-state');
let stateObj;
try {
stateObj = JSON.parse(state);
} catch (e) {
return;
}
document.querySelector('#div1').hidden = !stateObj.div1Visible;
document.querySelector('#div2').hidden = !stateObj.div2Visible;
document.querySelector('#user-input').value = stateObj.userInput;
}
With the following HTML:
<body onload='setupPage()'>
<button onClick='buttonClickedEvent()'>
Click Me
</button>
</body>
Solution 2: REST API (Ideal solution)
What I would recommend you do instead, is rewrite your server code such that it is a REST API, rather than using HTTP redirects. Then on the frontend, instead of changing the page, you use a library such as Axios to create HTTP requests:
axios.get('/path/on/server', (response) => {
if (response.status === 200) { // HTTP success
// Code to run upon successful response
}
});
Please let me know if there is anything you would like me to clarify.
I have a form that I am trying to have redirect to http://www.example.com upon successfully sending an email. I have tried different approaches including on_sent_ok in the additional settings as well as
if(jQuery('.wpcf7-mail-sent-ok').length > 0)
window.location.replace("http://stackoverflow.com");
in my JavaScript, but that does not seem to work as well.
Edit: I forgot to mention that upon the user clicking submit, I do a prevent default in order to do some calculations and generate a PDF. Once it is all done I do
$("form.wpcf7-form").unbind('submit').submit();
to allow the submission to happen. Could this be causing any issues with the redirection?
Contact Form 7 made a ajax call. After success the element is inserted. Then you can check if element exist:
jQuery(document).ajaxComplete(function() {
if (jQuery('.wpcf7-mail-sent-ok').length) {
alert(1);
//window.location.replace("http://stackoverflow.com");
}
});
Well, maybe I'm writing late, but this code will definitelly will do the job. (If you're working in wordpress). I'm using it so far and it's working normally.
Remember to place this code at your functions's file and as final note remember that you must use one or the other, not both...!
add_action('wp_head', 'RedirectsCF7');
// Start of function.
function RedirectsCF7() {
if(is_page("contact-page-or-whatever-page-name-is")) {
echo "<script>document.addEventListener('wpcf7mailsent', function(event) {location = 'https://www.google.com/';}, false);</script>";
}
}
// Or simply add this code to all pages, like this.
if(!is_admin()) {
echo "<script>document.addEventListener('wpcf7mailsent', function(event) {location = 'https://www.google.com/';}, false);</script>";
}
}
Reference here
I should start by saying that I'm running my site from PHPStorm's inbuilt webserver, but I think the problem is in my method, not the environment.
I'm redesigning my outdated games website. I thought it would be a good idea to have my PHP dependant content load by AJAX instead of includes at the top of a page that can only be run once.
In this example, the page loads very quickly but there are 2 sections that have independent AJAX loaded content that take unusually long to load. The 3 blue lines inside the boxes animate to indiciate it is loading.
The relevant jquery and javascript stuff is in the html body, as the site uses a template (containing the header, footer and basically everything that is require for each page) and simply includes the unique page content in the middle, eg - include 'main.php'; index.php doesn't have a head or body, it just contains js and html.
However, I wait until $(document).ready to run any javascript so I don't think this is important.
The first to load is the news section, because it is called first in the javascript. This simply grabs a single element from a mysql table. This alone takes upto 2 seconds.
Next is the last 3 tweets on my timeline, I run a very efficient, simplified Twitter timeline retrieving PHP script, this also takes around 2 seconds.
Also consider I've yet to implement a getGames.php for retrieving all the necessary game info from the database, the wide thumbnails are currently just placeholders, so in total my site will be taking even longer to load all of its content.
Anyway, I realised that if I just do include 'getTweets.php' and 'getNews.php', the raw content appears to load much much quicker, no ajax necessary. However the echoed data gets printed on the page.
The thing is, I'm likely never to call those AJAX function again on this particular page, so the reason for using AJAX on this page is simply consistency and thinking ahead, but there are other pages (the news section for instance) where I will have to use AJAX to get news articles via getNews.php.
Obivously I don't want to have 2 files with almost the exact same PHP code, but I can't see any elegant solution for using both AJAX and includes.
Perhaps I could have one great big ajax.php which can return all the necessary page data in a single call instead of calling AJAX multiple times with different PHPs?
I don't know...
I'm sure there's nothing wrong with the php code itself (getting tweets or news from the database were coded with efficiency in mind), just my method.
I wasn't going to include any code, I don't think it makes my problem any easier to understand, but anyway:
index.php, javascript section:
function ajax(page, inputData, outputHandler, errorHandler) {
$.ajax({
type: "POST",
url: page,
data: inputData,
success: function(data){
outputHandler(JSON.parse(data));
},
error:errorHandler
});
}
$(function() {
$("#tweet-container").append($.parseHTML(loadingIcon));
$("#news-container").append($.parseHTML(loadingIcon));
ajax("/ajax/getNews.php", { }, function(data) {
$("#news-container").empty();
for (var i = 0; i < data.length; i++) {
var date = data[i].dateadded;
date = $.timeago(date);
var text = data[i].news;
text = text.replace(/<br\s*[\/]?>/gi, "\n");
text = $.trim($(text).text());
//'+ data[i].author+'
text = '<img src="/images/Frosty.png" alt="%s" align="left" style="padding:6px 5px; background:pink; margin-right:5px;"/>' + text;
var title = data[i].title;
var newsData = { header: date, title:title, content:text };
var article = Mustache.render(newsTemplate, newsData);
$("#news-container").append(article);
}
$(".news-content").dotdotdot( { height:200 } );
$($(Mustache.render(footerTemplate, { link:"/news", target:"_self", content:"Read More"} ))).appendTo($("#news-container"));
} );
ajax("/ajax/getTweets.php", { count:3 }, function(data) {
$("#tweet-container").empty();
for (var i = 0; i < data.length; i++) {
var text = processTweetURLs(data[i].text);
var date = $.timeago(data[i].date);
var tweetData = { header:date, content:text };
var tweet = Mustache.render(tweetTemplate, tweetData);
$(tweet).appendTo($("#tweet-container"));
}
$(".twitter-content").dotdotdot();
$($(Mustache.render(footerTemplate, { link:"https://twitter.com/gp_studios", target:"_blank", content:"More Tweets"} ))).appendTo($("#tweet-container"));
} );
createGameBoxGrid(GAME_BOX_WIDE, ".featured-games-list", 3, [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]);
$(".main-left").height( $(".main-center").height() );
createGameBoxGrid(GAME_BOX_SMALL, ".main-category-games-list", 9, [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]);
} );
getNews.php
<?php
include($_SERVER["DOCUMENT_ROOT"]."/class/Connection.php");
$mysql = new Connection();
$articles = [];
//SUBSTRING(news,1,1000)
if ($result = $mysql->query("SELECT id, title, news, author, dateadded FROM news ORDER BY dateadded DESC LIMIT 1")) {
while ($row = $result->fetch_assoc()) {
array_push($articles, [ "id"=>$row["id"], "title"=>$row["title"], "news"=>$row["news"], "author"=>$row["author"], "dateadded"=>$row["dateadded"] ] );
}
}
echo json_encode($articles);
?>
What I've written above is a bit waffley but was necessary to get across all the relevant info. So in simpler terms and phrased more like questions:
why is AJAX so slow compared to just running it before the page has fully loaded?
my AJAX PHPs echo a long and often complex JSON, how can I use the same script for AJAX and includes? I've tried surrounding the include in div tags (a method I don't like at all) but if the json contains html it get's interpreted as such and get's somewhat mangled.
Any general hints for making this work a lot better?
The problem you are probably running into, is the fact that browsers limit the number of connections to the same server. See also this question on SO.
So if you put your code in a $(document).ready() function, what actually happens, is that the DOM is ready, so all images start loading and your ajax call will not go through until there is a connection available to the same server.
So your ajax request can be fast, but it starts late, giving the impression of a long-during call.
You can solve this for example by putting all static assets like images on a different sub-domain.
However, you can also use the same script you use for your ajax call as an include so that you don't have to duplicate code. Then you can include it or call it using ajax and get the same results.
You could use something like:
if (!isset($some_enviroment_variable))
{
// ajax call
// set up environment
}
// do your php controller stuff
// output the results
I would like to include html data loaded from ajax request and trigger click event on images in my html data. I understand that this is wrong in SPA world but I need displays data from wysiwyg editor...
This is code refactored from version with jQuery:
$http.get('Help/Help/GetHelp', {
params: {
helpId: contentKey
}
})
.success(function(data) {
if (data.success) {
// viewData is html from wysiwyg editor
$scope.viewData = data.viewData;
// HERE is problem because now images isn't in DOM. This is too early
angular.element('div#content').find('img').click(function () {
// Show image in gallery
});
} else {
$scope.viewData = "";
}
});
But it does not function because images isn't in DOM when I trigger click event on them... What is the best practice to solve this issue?
Thanks!
I'm not exactly sure what viewData represents, but I think you are going about this in the wrong way.
When using angular, you shouldn't be loading html from the server (unless it's a template, via templateUrl).
Instead your server should return data which you then display using a template.
So for images, for example, you might return something like this from your server:
[
{
name: 'image1',
url: 'some/url.jpg'
},
{
name: 'image two',
url: 'some/other/url.jpg'
}
]
Then your html could have something like the following:
<img ng-src="image.url"
ng-click="showInGallery(image)"
alt="{{image.name}}"
ng-repeat="image in images"/>
And your controller:
app.controller('ImageController', function($scope, imageService){
imageService.getImages().then( function(images){
$scope.images = images
});
$scope.showInGallery = function(image){
//your gallery code here.
}
});
I would suggest reading more about angular and S(ingle)P(age)A(pplication)s, as you are trying to use a framework in a way other than how it was designed. This means you'll hit lots of stumbling blocks and won't benefit from the power of the great community that surrounds it.
Anyone can tell me what I'm doing wrong?
I am creating a simple system to get people in and out of user groups and for that purpose I am using Dojo and Perl. (If I could have it my way it would be PHP but I am not the boss.)
At the moment I only use three files, one for Perl, one for JavaScript and one for CSS styles.
The start of the CGI script routes to different functions as follows:
if ($search = $cgi->param('psearch')) {
dbConnect();
jsonSearchPersons($search);
dbDisconnect();
} elsif ($user_id = $cgi->param('person')){
dbConnect();
create_form($user_id);
dbDisconnect();
} elsif ($user_id = $cgi->param('saveuser')) {
save_user();
} else {
mainPage();
};
...
sub save_user {
print $cgi->header(-type=>'text/plain',-charset=>'utf-8');
print("success");
}
The problem I have now is when I want to save the new groups for the user though an Ajax call (a call to this URL: users.cgi?saveuser=xx). This should (in my point of view) be a POST call, so I made this and tried to append the resulting HTML/text in a <div> but it didn't work:
dojo.xhr.post({
url: "/cgi-bin/users.cgi?saveuser="+user_id,
content: {
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
When I do it with dojo.xhr.get(); it works fine, but when I do it with the POST it's like it jumps over that part of the if statement and just appends the mainPage() function. Is there something basic I don't understand between Dojo and Perl? Do I have to set up the pages so it will accept a POST call? Or what am I doing wrong?
NOTE: This is the first "system" I have made though Dojo and Perl. (I'm normally a PHP/jQuery kind of guy who makes everything UI by hand, so I'm kinda new to it.)
Try adding the saveuser-parameter to the content-object of dojo.xhrPost instead of passing it in the url.
You're trying to pass the saveuser-parameter as GET and the other as POST, maybe that confuses your serverside part.
Try it like that:
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
new_groups: group_ids.toString(),
saveuser: user_id
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Found a solution.
The problem was my javascript. When posting to a perl script you use $cgi=new CGI; and all that. This takes both GET and POST variables and validates them. In my javascript/dojo code, i then used an url with GET vars and then made a POST as well. This meant perl could not find out (or was mixing) the two variable types. So when i changed my ajax code (as below) it worked, since $cgi->param('saveuser') both fetches GET and POST of "saveuser" (no change to the perl was needed):
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
saveuser: user_id,
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Kinda wack bug, but im glad since it works great now :D
Line 675 of CGI.pm :
# Some people want to have their cake and eat it too!
# Uncomment this line to have the contents of the query string
# APPENDED to the POST data.
# $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
Made me laugh !