Dynamic pages in Wordpress, using database - javascript

I'm making by myself a site and I need some help because I'm not so good... All things I learned just by google, forums and blogs. Now I'm stucked in a part of my site very hard for me.
I will ask you step by step and see if I can complete the site with your help.
Sorry if my english is not perfect, I'm Italian.
So, let's go.
I created the site with WordPress, using a theme. I changed the font (directly in the css and not using the guide because my font was not listed), i customized every part by the panel, plugin and by edit directly the code of pages.
I tell you this so you can understand my level.
If i digit "www.mysite.com/xx" (where "xx" is a page that not exist) it go on the 404 page error.
Well, I edited that page too (404.php in the editor of WordPress) with my personal text. I didn't touch htaccess file.
So now my first purpose come.
I want use the page error for create dynamic pages.
In this page i want to write my text and the "xx" word, so i must get it from the link "www.mysite.com/xx".
It should be easy with Java script but I don't know from where to start...
I need to put that word in a Variable because i will need to process it in a second moment.
This is my 404.php code:
<?php
/**
* The template for displaying 404 pages (Not Found)
*/
?>
<?php get_header(); ?>
<div class="row">
<div class="col-md-9">
<section class="content">
<article>
<h2><?php esc_html_e( 'Attenzione', 'iamsocial' ); ?></h2>
<p><?php
$url1 = 'http://www.example.com';
esc_html_e( 'Correttore in fase di ultimazione.', 'iamsocial' ); ?></p><p><?php esc_html_e( 'Vai alla ', 'iamsocial' ); ?> <?php esc_html_e( 'home page.', 'iamsocial' ); ?></p>
</article>
</section>
</div>
<aside class="col-md-3">
<?php get_sidebar(); ?>
</aside>
</div>
<?php get_footer(); ?>
The part of the database is on the next question.
Thank you for your attention.

You don't need Javascript for this. You can do it in PHP with:
$path = $_SERVER["REQUEST_URI"]
That will return the "xx" part of the URL.
If you only need the last part of the URL, like Steven says, you can explode by / and get the last element:
// URL = site.com/page/xx
$page = explode("/", $_SERVER["REQUEST_URI"]); // = /page/xx
$lastEl = end($page); // = xx

Related

Modify a source based on strings in the current URL

I am a little bit stuck trying to get a tracking code to work for my website.
Every click to my website through a tracker inserts a randomly generated unique string within the URL. For example, http://www.examplepage.com/?sub_ref=333ktcm1ckpv2uvd
When someone does goes through a step by step process on my website, a PHP script will load containing various variables, one of which is an external javascript:
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa970aa5f018dcce821dc6251"></script>
In order for me to facilitate the tracking, I want to be able to add the unique string in the URL into the javascript. The idea is that I can track when someone clicks my website and then completes an entry with an external script. For example:
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa970aa5f018dcce821dc6251?sub_ref=333ktcm1ckpv2uvd"></script>
Could someone advise the best way to achieve this? I've been playing around with this for most of the day without success.
I should add, at the point I want the unique ID added onto the script, the URL on my website is http://www.examplepage.com/?sub_ref=333ktcm1ckpv2uvd#submit-entry
Thank you #CFP Support that's really useful.
So based on your advice, I've managed to work out that using the below displays the correct URL string that I'm looking to add within the javascript.
https://example.com/test/test.php?sub_ref=230948324095
<?php
echo __LINE__ . " here, we look at _GET "; print_r($_GET); echo "<br>";?>
8 here, we look at _GET Array ( [sub_ref] => 230948324095 )
So based on the above, I believe I should be using:
<?php echo ($_GET['sub_ref'])?>"
The problem I've got now, is that if I use the following, I end up with an error:
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=<?php echo ($_GET['sub_ref']); ?>"></script>
PHP message: PHP Parse error: syntax error, unexpected '<' in
/home/admin/web/exampledomain.com/public_html/settings.php
on line 13" while reading response header from upstream
EDIT:
This is where I am at currently. I've made the change you recommended (first one) which doesn't product an error, however the sub_ref in the button that loads the script is still blank.
settings.php file
<?php
// Set the referral network
$network = 'A';
// Set your submit code below.
$onClick_code = 'call_referral()';
// Set your the referral script below.
$script = '
<script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=' . $_GET['sub_ref'] . '"></script>';
?>
final-step.php
<?php
require_once '../settings.php';
?>
<h1>Submitting Data</h1>
<p class="second-paragraph">Please wait while we process your data.</p>
<div class="data-processing-wrapper">
<div class="data-processing-inner-wrapper">
<div class="cssload-loader-walk">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<span class="console-msg"></span>
<div class="data-verification-wrapper">
<h3>Data Verification</h3>
<p>Thank you, you are almost done submitting your data.
<br>Click on the Submit Now button below to submit your data.
</p>
<div class="button-wrapper data-verification-button-wrapper">
<a class="button data-verification-button"
<?php if ($network == 'A' || $network == 'B') {?> onclick="
<?php if (!empty($onClick_code)) { echo $onClick_code; } ?>"
<?php } ?>>Submit Now
</a>
<?php if ($network == 'A' && !empty($script)) { echo $script; } ?>
</div>
</div>
<div id="progressBarConsole" class="console-loadbar">
<div></div>
</div>
</div>
</div>
From inspecting the Submit Now button in Chrome, this is what it shows (the ?sub_ref is blank):
<div class="button-wrapper data-verification-button-wrapper">
<a class="button data-verification-button" onclick="call_referral()">Submit Now</a>
<script type="text/javascript" id="js1" src="https://www.example.com.net/test.php?id=8bb1ff8&sub_ref="></script> </div>
Am I correct in assuming that the sub_ref does not appear because the script is not being when the page is opened (only when final-step.php runs)?
Looks to me like you are close, just need to point to the right query....
src="https://www.example.com/load.php?id=8bb1ff8aa970aa5f018dcce821dc6251&sub_ref=<?php echo urlencode($_GET['sub_ref'])?>"
Looks fine (though from the example you gave you shouldn't need the urlencode).
It is really hard to tell what is going on though without some actual code.... (which is likely why nobody is answering you..... - nor can I give you much of an answer......)
However, as a 'troubleshooting' tip......
You have to know what you have as variables to work with at any given moment, so learn to stop the code at any given point and take a look what the code sees.
In this case, a good one would be to see what is in the $_SERVER array to see what links are really available before trying to build the reference link (this will tell you where you really are as well as how the user got to you, etc. - a wealth of info to be sure!)
echo __LINE__ . " here, we look at _SERVER "; print_r($_SERVER); echo "<br>";
Another good one at this point is the $_GET, which will tell you what is in the query string as an array....
echo __LINE__ . " here, we look at _GET "; print_r($_GET); echo "<br>";
Having the results of both those will tell you that you actually have the data you think you do (and that is quite often the reason things don't work like you expect!)
(you can also add a
die();
after any line to make the code stop..... Lots of ways to do this, and the most important part is just seeing what is going on!
Use the above, change your question to include more code and show what you are getting in $_SERVER and $_GET at that point and you will get some great, exact answers, I'm sure!
EDIT (after a bit more info.... - but still no full code..... :( again, seeing the script around all this would help get this done..... not sure why you aren't including it...)
Obviously you are in PHP at this moment (as it is a PHP error - the script would tell us that...) and your code won't work in PHP.
You have....
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=<?php echo ($_GET['sub_ref']); ?>"></script>
and
PHP message: PHP Parse error: syntax error, unexpected '<' in
/home/admin/web/exampledomain.com/public_html/settings.php on line 13"
while reading response header from upstream
Which is telling you the issue - - - you can't write JS inside PHP! You can make it a variable, then use it later, or you could 'jump in/out' of PHP/HTML to do it, but you must remember what language you are in and respect that language's rules.
So, you could have:
$script = '<script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=' . $_GET['sub_ref'] . '"></script>';
Or, 'jump in/out' with:
// PHP code ......
// 'jump out'....
?>
<!-- now you are in HTML and can do some JS -->
<script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=<?php echo ($_GET['sub_ref']); ?>"></script>
<!-- where you had correctly 'jumped', but improperly mixed... -->
<!-- now, back to PHP... ->
<? // and you can do more PHP code here.....
You have to respect the language - and where you are at any point in the code!
If you still have issues, INCLUDE THE FULL CODE AROUND THIS (I'm sure it isn't rocket science gov't secret stuff, so save us all some time so you can get the help you are asking for, please!
EDIT:
in your settings.php the link shows as
src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=' . $_GET['sub_ref']
However, you say in the button it is
src="https://www.example.com.net/test.php?id=8bb1ff8&sub_ref="
Your code is not clear on how things are going...... (does this sound familiar? SHOW THE CODE AS IT IS PROCESSED..... - I can't {and now, won't be able to - I've put too much time on this and am getting 'looks'...} try to guess where that weird change came from. You need to show something that is logical.....
and, prove that you have the _GET - use the print_r just before the _GET to make sure you have the data as it is being processed (sometimes with PHP you have to do some 'tricks' to keep the data on one page and use it on another..... there are several ways to do it, but until I understand your flow and what you are trying to do overall {and mostly, why you are using so many pages.... - it could be an overall design/flow issue...}, it is really hard to get a picture of what you are trying to accomplish..)
SO is not really a training facility - and I have other projects (I'm allowed a bit of time each day to answer questions, etc. - part of the 'give back to the community' policy around here, but my primary work is on paid projects {I'm sure you understand...}, so I can't do more today, but if you give some clear 'steps' on what is going on and errors you see, etc. I can look at this again tomorrow.

PhpStorm highlight part of file as JavaScript with custom start and end lines

I have inherited a PHP project that contains several HTML files with the following structure
<?php $this->placeholder('dom.ready')->captureStart(); ?>
var some = javascript.goesHere();
<?php $this->placeholder('dom.ready')->captureEnd(); ?>
<div class="some html goes here">
<h1> <?php echo "with some php in the middle"; ?> </h1>
</div>
Would it be possible to configure Phpstorm to interpret everything between the placeholder lines as JS and the rest of the file as HTML with some PHP?
I know the file structure is very unfortunate, but I can not refactor it for now...
Thanks
There are at least two interesting possibilities...
1. Heredoc notation
https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
For me the most interesting solution was to transform the JavaScript into a PHP string using the heredoc syntax:
<div>
<div>
<?php $this->placeholder('dom.ready')->captureStart(); ?>
<?= <<<JS
var some = javascript.goesHere();
JS
?>
<?php $this->placeholder('dom.ready')->captureEnd(); ?>
</div>
</div>
Ensure to place the closing identifier in the first column of line
2. Change the filename
When you change your file extension from .php into .js.php PhpStorm will also highlight your JavaScript.
I think this solution is nice because you will always be remembered that JavaScript is in your PHP file. And this has to be cleared out...
Both solutions was found on jetbrains.com. Thanks to Andriy Bazanov:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/207046645-Zend-framework-and-code-formating-in-view-files
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000790544-Syntax-Highligth-on-some-special-cases
Probably not really what you want but if you surround the javascript with a script tab phpstorm will interpret it as js. You would need to change your code to look like:
<script>
<?php $this->placeholder('dom.ready')->captureStart(); ?>
var some = javascript.goesHere();
<?php $this->placeholder('dom.ready')->captureEnd(); ?>
</script>
<div class="some html goes here">
<h1> <?php echo "with some php in the middle"; ?> </h1>
</div>
This article says you can use two file extentions to accomplish something similar without using the script tags.
https://confluence.jetbrains.com/display/PhpStorm/Syntax+highlighting+of+PHP+inside+JavaScript+(and+other+languages)

WordPress: how to open the_content() in a lightbox or new window?

I´m trying to open the_content (just pictures) in a lightbox.
I´d like a page like a Christmas-calendar so that you can see the posts (and the planned too) and if you click the published post, the image (the_content) should be shown in a shadowbox, lightbox or whatever, I think you´ll know what I mean. Right now my code looks like:
<header class="entry-header" rel="shadowbox" onclick="location.href='<?php the_permalink();?>';" style="cursor:pointer;">
<?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif; ?>
<?php if ( is_single() ) : ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php else : ?>
<?php endif; // is_single() ?>
<?php if ( comments_open() ) : ?>
<div class="kalender">
<p1> <?php the_field('nummer'); ?> </p1>
<br>
<p2><?php the_time('j. F Y'); ?> </p2>
<p3><?php the_title(); ?></p3>
</div>
<!-- .comments-link -->
<?php endif; // comments_open() ?>
</header>
I think the easiest way would be to handle the_content like a read_more link and just say onclick show in an shadowbox. But right now I just don't know how to. You can have a look here (right now just in Firefox or Safari, don't know why Chrome hates me:-))
Consider using the Fancybox plugin: http://fancybox.net/howto
Then include an anchor tag in each of your posts, like 'read more', with the content's unique ID:
<a class="fancybox" href="#content">Read More - This shows content of element who has id="content"</a>
Just ensure that each post's #content DIV has a unique ID, increment a variable in your loop and append it to read something along the lines of:
#content-01, content-02, etc.
Then just hide the content DIV's with CSS.
.fancybox { display: none; }
P.S. seems fine in Chrome 34.0.1847.131
Here's a useful pattern to pass server-side data to the client-side:
1. Use wp_localize_script to output a script fragment to the DOM.
2. Inside that script fragment, assign the value of the_content to a
JavaScript global string variable.
3. Use this JavaScript global from
inside your JavaScript to read the value of the_content

Clean way to Template an HTML code block that only takes title/content parameters, where content may be large and littered with new-lines

I am using Accordion (jQuery) on my school webserver. Currently, my coding-scheme uses PHP/HTML/CSS/Javascript. I started noticing an opportunity for automation/templating when writing the entries for the Accordion modules. I write the following code:
<h3>Title</h3>
<div class="nobg">
<p class="nobg">
<!-- Entry text -->
</p>
</div>
so I am looking for pointers for the best way to template that code based on the following needs:
Adjustable parameters: Title, Content
When making new modules with a large content 'parameter', the creation of that parameter should maintain readability.
Since I am already on PHP, I was thinking maybe some sort of template function:
<? php accordion_entry("Title", "Entry Text" ?>
But the text is usually a lot of HTML: like the following:
PDF
<p>
The release date is 2007 but the pinout seems to check out (I did some small verifications with my PCB). Also, the reference documents are all valid!
</p>
I would like to write that HTML myself in the designated spot where the module will eventually manifest as a whole. Perhaps even cooler would be something like this:
<accordion-entry title="Title">
PDF
<p>
The release date is 2007 but the pinout seems to check out (I did some small verifications with my PCB). Also, the reference documents are all valid!
</p>
</accordion-entry>
I have no idea how to get started creating such a mechanism, or if it's too much trouble to bother.
I found my temporary solution, until someone comes along with something better! Please review! I am no PHP Expert!! :D
The PHP Function:
<?php
function accordionEntry($title, $entry)
{
echo '<h3>' . $title . '</h3>';
echo '<div class="nobg">';
echo ' <p class="nobg">';
echo $entry; // <!-- Entry text -->
echo ' </p>';
echo '</div>';
}
?>
The PHP function call:
<?php accordionEntry(
"GSM0107IG001 - Integration Manual",
'PDF
<p>
The release date is 2007 but the pinout seems to check out (I did some small verifications with my PCB). Also, the reference documents are all valid!
</p>');
?>
Create a partial, and load your content into it along with settings
accordian.phtml (just use .html if you want, doesn't really matter)
<accordion-entry title="<?php $title ?>">
<?php $content ?>
</accordion-entry>
page.html
<div><?= renderPartial('accordian.phtml',array(
'title'=>'GSM0107IG001 - Integration Manual',
'content' => '<p>your html</p>'
)); ?>
partial.php
function partial($partial, $settings){
//will load html from indicated file, and merge passed settings and content into place before returning all $html
// this allows the reuse of the 'partial()' function for other snippets
$template = file_get_contents($partial);
//$settings should be an array, and then your keys can be extracted as variables that match the $settings variables (such as $title) that exist in the .html partial file
extract($settings); //will assign any keys in your array, such as 'title' to php variables of the same name... so in this case $title, and $content
echo $template;
}

How do I implement AJAX into CodeIgniter?

I am trying to understand the process of implementing AJAX Query into my CodeIgniter application. The goal is to a have a clickable division (button) in a view. When this div is clicked the AJAX query is called and retrieves 5 movies from my DB and displays them in the view. Right now I have a main page with search button, this search button orders my DB by ID and then retrieves the 1st 5 movies from the DB and displays them on a new page. The function I am trying to implement should retrieve the next 5 movies and replace the 1st 5 movies without reloading the page.
Below is all the code I assume you should take a look at, due to its necessity. Under each part of the code a short summary is provided. And at the end I try to explain what I don't understand and what I am asking you to help with.
Main Page - Controller xampInstallFolder/htdocs/application/obs/controllers/main.php
public function generate_suggestions() {
$this->db->order_by("id","desc");
$pages = $this->db->query('SELECT * FROM movies LIMIT 5');
$data['pages'] = $pages;
$this->load->view('results_v', $data);
}
This function is called when my Search button on the main page is clicked. Right now it doesn't accept any criteria for the query it only retrieves the first 5 movies in the db. Then I take the movies and store them in the pages array and load the new view with the array provided in data
Results Page - View *xampInstallFolder/htdocs/application/obs/views/results_v*
<div id="listA">
<table>
<!-- Function that splits the array in $pages into the first 5 movie suggestions -->
<?php foreach ($pages->result() as $row): ?>
<a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<p><b><?php echo $row->name ?></b></p>
</div>
<div class="details">
<p><?php echo $row->summary ?></p>
</div>
</div
</a>
<?php endforeach; ?>
</table>
</div>
<div id="next_btn" style="display: block;">
<p>Click here to display next 5 movies</p>
</div>
I have a div listA where I display the 5 movies using a for each loop on the pages array. I have much more div and information, but I was trying to keep it simple.
Javascript xampInstallFolder/htdocs/ASSETS/obs/js/myscripts.js
$( "#next_btn" ).click(function() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("listA").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnext5.php?q="true);
xmlhttp.send();
});
In the head of my results view I link the javascript with this function. It triggers when the next_btndiv is clicked. I got the code from w3schools and from what I understood you need to provide the element in which the result is displayed (listA) and the file where the query is stored (getnext5.php)
getnext5.php Where do I put this file?
$con = mysqli_connect('localhost','root','root','obs2');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5";
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
<a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<p><b><?php echo $row->name ?></b></p>
</div>
<div class="details">
<p><?php echo $row->summary ?></p>
</div>
</div
}
echo "</table>";
Here is the core function. I tried to adjust the code from w3schools, but I am not sure if it is correct. My DB is called obs2, but I am not sure if I should have it in both mysqli_connect and mysqli_select_db statements. I also know that I have to figure out how to make it always load the next 5 movies in the list, but right now I just force it on id>5. And then I have the style for the $result. I think the table and `while loop are coded properly, but I don't know how to turn the divs, anchors and original php echoes into the same syntax.
If you made this is far thank you very much for reading through. I'd say the only part I need help with is the getnext5.php. Mostly the syntax. And location, where should the getnext5.php file be stored? I don not think that the other parts of the code are wrong. But obviously if you spot anything in there please let me know as well. Again thanks for reading. I'm looking forward to your replies. If you'd need any other information just ask for it Ill add it.
I only read through the last script, and I corrected some mistakes you made. You can put that file anywhere pretty much. You can copy the code and paste it into a controller class or a views page.
<?php // I just decided to start here
mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5"; # This is an integer, no quotes necessary.
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
?> <!-- Note how we stop php right before we start printing html, since you have nested php tags throughout this block of markup -->
<a style="display:block" href="<?=base_url('core/detail/'.$row->id)?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<p><b><?=$row->name?></b></p>
</div>
<div class="details">
<p><?=$row->summary?></p> <!-- Protip, you may use <? and ?> instead of <?php and ?>. You may also use <?= as a shortcut to the "echo" function -->
</div>
</div>
<?php
} // We are opening up our PHP tags again
echo "</table>";
?>
It seems that you're kindof all over the place with your code. Instead of answering your question specifically, I'm going to give you some advice as to how you can use AJAX with codeigniter much easier. I'm not saying this is the best solution, but it's much more organized and clean that what you have going on. Hopefully it will point you on the right direction.
Let's start from the backend and then move towards the front.
First, a method in a controller which queries the movies in the database. Notice the parameters which allow us to ask for any subset of movies, and not just the first 5. (And yes, I'm only including the important lines of code instead of everything.)
public function generate_suggestions($start = 0, $count = 5) {
$pages = $this->db->query('SELECT * FROM movies LIMIT ' . $start . ',' . $count);
// send back the view as a simple HTML snippet (the <table>, perhaps?)
}
Now we need some Javascript that can call this function on the server. Since the function sends back an HTML snippet, we can just stick that snippet of html code into the page. JQuery makes all of this very easy, so you can avoid the complicated XMLHttpRequest stuff.
<script type="text/javascript">
var nextstart = 6;
var movies_per_page = 5;
$( "#next_btn" ).click(function() {
// this next line makes the ajax call for us, and the inline function
// is called when the response comes back from the server
$.get("controller/generate_suggestions/"+nextstart+"/" + movies_per_page,
function(data) {
// data is what comes back from the ajax call
// here it is the snippet of html, so let's display it as is
$( "#listA" ).html(data);
nextstart += movies_per_page; // so that the next click will load the next group of movies
});
});
</script>
Now we just need to populate the table when the page first loads, and you can do that by calling the same ajax call on page load with a similar $.get ajax call.
Once you understand all of this and have it working, then you should look into JSON, as it is a much better way of transferring data with ajax. And jQuery makes working with JSON much easier, too.

Categories