Stripping HTML from jQuery load() result - php

This is a followup to the solution for this question.
I am using jQuery's load() function to pull a headline within a div tag from one page to another within my site. This works wonderfully.
The problem is, load() also pulls the div tag itself, which I do not want, as it then gets formatted via CSS like the source page.
Here is the PHP:
function get_team_articles($team_id, $feat=0) {
.
.
.
while ($row = mysql_fetch_assoc($r)) {
$page = explode('_', $row['page_id']);
(is_numeric($page[1]))
? $pre = 'wk_'
: $pre = '';
$arr[] = $page[0] . " | " . $pre . $page[1] . ": " . "
<a linked_div='news_header'
linked_path='../news/" . $page[0] . "/" . $pre . $page[1] . "/" . $page[1] . "_" . $page[2] . ".html'
href='index.php?view=news&yr=" . $page[0] . "&wk=" . $page[1] . "&pg=" . $page[2] . "'></a>";
}
$articles = implode('<br/>', $arr);
return $articles;
}
Notice the linked_div and linked_path attributes within the anchor tag, which are used in my jQuery:
function set_team_headlines(){
$('#section-articles > a').each(function() {
var a = $(this);
a.load(a.attr('linked_path') + ' #' + a.attr('linked_div'));
});
}
Obviously I cannot strip the HTML tags within the anchor tags in PHP, because the server doesn't have the text within the anchor tags upon loading; so I assume I need to strip the HTML in jQuery after the load() call...and that is what I cannot figure out how to do. :)
The result I want is:
My headline
The result I'm getting is:
<div id="news_header">My headline</div>
Hopefully this makes sense. I think I provided more detail than I needed to. Thanks!

Navigate down one more level in your .load selector
a.load(a.attr('linked_path') + ' #news_header');
If your news_header id isn't unique, it isn't valid to select by that id (ID's must be unique!)
To get around that issue, use this:
a.load(a.attr('linked_path') + ' #' + a.attr('linked_div') + ' div');
Edit:
.load actually includes the targeted element when appending html instead of appending the target element's children. I would move to using $.get().
$.get(a.attr('linked_path')).done(function(html) {
a.text($(html).filter("#news_header").text());
});

Related

PHP not loading inline

I have a php file with the following code which is run inside a switch statement:
switch($valueFoo) {
case 'bar':
echo "<select id=\"selTheme\">";
$path = './files/css/themes/';
$files = array_values(array_diff(scandir($path), array('.', '..')));
for ($i = 0; $i < count($files); $i++) {
$cVal = substr($files[$i], 0, -4);
$cTitle = ucwords(substr($files[$i], 0, -4));
if ($cTitle==$_SESSION['setTheme']) {
echo "<option value='" . $cVal . "' onclick=\"changeColors('" . $cVal . "')\" selected>" . $cTitle . "</option>";
} elseif ($i>=count($files)) {
echo "<option value='" . $cVal . "' onclick=\"changeColors('" . $cVal . "')\">" . $cTitle . "</option></select>";
} else {
echo "<option value='" . $cVal . "' onclick=\"changeColors('" . $cVal . "')\">" . $cTitle . "</option>";
}
}
echo "...";
This is intended to create a list of options from a folder on my server. And it does indeed work. The problem is that it ONLY works AFTER the page is refreshed. I have been banging my head on my table trying to figure out why it does this only after the page is refreshed. I have no clue. I want the element to be filled with options as soon as it loads on page. I don't want the page to reload at all. It works by itself to populate an unordered list but I want it to be selectable options.
I don't see anything wrong with the code at all. I don't understand why the options list aren't being populated without a reloading of the page. I don't understand why it fills in perfectly when the page reloads. I would think that if it would do it properly AFTER the reload, it would do it just fine the first time it loads! Why isn't?
Please help me understand.
EDIT: This code comes as a return from an AJAX call. I am trying to run the for loop from that AJAX call. The loop doesn't run until the page reloads. Is there a way to force the AJAX call without the page load?
if you want a dynamic display of the folders content you'll have to use Ajax.
make sure that the session is already created and you're using 'session_start()' in the beginning of all your pages,
clarify your question/code to get precise answers

AJAX call from inside a Widget in Yii2?

I would like to create a Widget for my Yii2 project that will based on a few parameters given in the View create an AJAX call that updates a portion of my View.
Basically I have a Postcode field that when updated will look up the corresponding town in a different PHP file. I created something that works, but I was wondering if this is the right (or only?) way to do what I'm looking for. I don't want to have to rewrite the AJAX call as I want to be able to reuse this functionality on several forms and thus fields in my project.
I call the Widget in my View like this:
<?= SearchWidget::Widget(['id' => 'customerform-postalcode',
'dataTarget' => 'cities',
'targetId' => 'customerform-city',
'targetType' => 'dropdown']);?>
and in the Widget I basically have only a run() function which echoes the AJAX call to the page.
public function run()
{
$jScript =
'<script>'
. '$("#' . $this->id . '").change(function(){'
.'$.ajax({'
. 'url: "../scripts/search.php",'
. 'data: {'
. 'needle: $("#' . $this->id . '").val(),'
. 'haystack: "' . $this->dataTarget . '"'
. '},'
. 'type: "POST"'
. '}).done(function(data){'
.'var targetType = "' . $this->targetType . '";'
.'if (targetType=="dropdown") {'
. '$("#' . $this->targetId . '").empty();'
. 'var obj = jQuery.parseJSON(data);'
. '$.each(obj, function(key, value) {'
. '$("#' . $this->targetId . '").append("<option>" + value + "</option>");'
. '});'
. '} else {'
. 'var obj = jQuery.parseJSON(data);'
. '$("#' . $this->targetId . '").val(obj);'
. '}'
. '});'
. '})'
.'</script>';
echo $jScript;
}
First off, I've only just started working with Yii and frameworks so I'm really unsure if this is the correct way to go about it. My first instinct says this is too messy and there should be a better way to do it. Any help is appreciated.
Personally I don't like to write JS code in my PHP files. So I would try to get the JS in a separate .js file.
I would change my SearchWidget to echo an input field with some additional attributes that will provide the JavaScript with the right variables. So my postcode input field would look something like:
<input type="text" name="postcode" id="postcode" class="search-field" data-target="cities" data-targetid="customerform-city" data-targettype="dropdown" />
Then you can rewrite your JS to something like below (untested).
$('.search-field').change(function() {
var id = $(this).attr('id');
var data_target = $(this).data('target');
var target_id = $(this).data('targetid');
var target_type = $(this).data('targettype');
$.ajax({
url: "../scripts/search.php",
data: {
needle: $("#" + id).val(),
haystack: data_target
},
type: "POST"
}).done(function(data) {
if (target_type == "dropdown") {
$("#" + target_id).empty();
var obj = $.parseJSON(data);
$.each(obj, function(key, value) {
$("#" + target_id).append("<option>" + value + "</option>");
});
} else {
var obj = $.parseJSON(data);
$("#" + target_id).val(obj);
}
});
});
Then put this JS file somewhere and register it in the init part of your widget.

Modifing generated links from url library in opencart

First lemme tell you what i am trying to achieve here . Suppose there is a url like this http://www.example.com/?id=12345 now what i want is if there is an id parameter available in the url i want to append the same parameter to every url on that page . Opencart has a url library that generates url i am sure you all must be familiar with it too , i found a way to do what i want but it's working at just some random parts of the website like categories url's are generating with id parameter appended to it and other's dont .
here's what i tried so far
File : System/libray/url.php
here's the function
public function link($route, $args = '', $connection = 'NONSSL') {
if ($connection == 'NONSSL') {
$url = $this->url;
}else {
$url = $this->ssl;
}
$url .= 'index.php?route=' . $route;
if ($args) {
$url .= str_replace('&', '&', '&' . ltrim($args, '&'));
}
foreach ($this->rewrite as $rewrite) {
$url = $rewrite->rewrite($url);
}
if(isset($_GET['id']))
{
if(!empty($this->request->get['id']))
$url .= '&id='.$this->request->get['id'];
if(!empty($_GET['id']))
{
$url .= '&id='.$_GET['id'];
}
}
return $url;
}
The problem is that not everything uses this method to generate its URLs.
For example, anything to do with banners (e.g. the Carousel module) uses links that the admin sets manually in System->Design->Banners, so you would also need to edit the code for this too. The simplest and probably the correct way is to edit the data that the models spit out e.g.
model_design_banner->getBanner() becomes
public function getBanner($banner_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "banner_image bi LEFT JOIN " . DB_PREFIX . "banner_image_description bid ON (bi.banner_image_id = bid.banner_image_id) WHERE bi.banner_id = '" . (int)$banner_id . "' AND bid.language_id = '" . (int)$this->config->get('config_language_id') . "'");
if (isset($_GET['id'])) {
array_walk($query->rows, function(&$value) {
$value['link'] .= '&id=' . $_GET['id'];
});
}
return $query->rows;
}
It's either that, or edit the output in every single controller that uses this method.
That's just an example for banners, though. I don't recall off-hand which other modules will need to be edited, but if there's a particular one that's making you scratch your head, let me know and I'll give you another example to fix it.

Echo not printing anything (It was before)

I am having a bit of a headache with a echo on my php code, the problem is that it isn't printing anything on screen, even though it was before, granted I added a function but when I used firebug to debug it it showed that it was getting the information out of a database correctly, just not printing it on-screen.
Where a list should be displayed there is nothing but empty space, staring into my soul.
I would appreciated if someone could point me out if I am missing something, as well why it is happening so I many not have to bother anyone anymore and if needed share my newly acquired knowledge.
PHP
function displayInfoLabs(){
if(isset($_POST['pId'])){
$id = $_POST['pId'];
$info = getSpecificLabs($id);
while($row = mysql_fetch_assoc($info)){
echo '<ul>' .
'<li>Laboratorio # ' . $row['codigolab'] . '</li>' .
'<li>Capacidad: ' . $row['capacidad'] . '</li>' .
'<li>Carrera: ' . $row['carrera'] . '</li>' .
'<li>Ubicación: ' . $row['ubicacion'] . '</li>' .
'</ul>';
}
}
}
function getSpecificLabs($pId){
$query = "SELECT bk.idlab , bk.codigolab , bk.capacidad, bk.carrera, bk.ubicacion FROM labs as bk WHERE bk.idlab = $pId";
$result = do_query($query);
return $result;
}
For reference I am also including the html and JS code of this function.
JS
$("#lnkInfo").click(function() {
var id = $('#txtId').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'displayInfoLabs',
'pId':id},
dataType: 'json',
success: function(response){
alert('exito')
}
});
});
HTML created via PHP, mind the lnkInfo which calls the JS that in turn calls the PHP
function displayList(){
$lista = getLabs();
while($row = mysql_fetch_assoc($lista)){
echo
'<div class="box" id="lab'.$row['idlab'].'">
<p id="labName">Lab #'.$row['codigolab'] . '</p>
<p class="info">Info</p>
<p class="info">Reservar</p>
<input type="hidden" name="txtId" id="txtId" value="'.$row['idlab'].'">
</div>';
}
}
Thanks a lot in advance.
EDIT:
Changing the success function made the list appear but it overrode the div's style including the buttons it had and all. This is the div's code.
div class="popUp1 hide" id="popUpCorrecto1">
<div class="estiloPopUp">
<span>Información de laboratorio</span>
<span value="Cerrar" id="btnCerrar">x</span>
</div>
<input type = "button" value = "Eliminar" id = "btnEliminar" onclick="eliminar()" />
<input type = "button" value = "Modificar" id = "btnModificar" onclick="window.location='modificarLab.html';" />
</div>
As you said in the comments, your data is being captured, but you aren't appending it to the document. you are simply doing:
alert('exito');
What you want to do is append the response to an element that is present in your page.
For examples sake, we can put a <div> with the id of mydata like so:
<div id="mydata"></div>
Now in your jQuery.ajax function, you could do something like the following:
$("#lnkInfo").click(function() {
var id = $('#txtId').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'displayInfoLabs',
'pId':id},
dataType: 'text/html',
success: function(response){
$('#mydata').html(response);
}
});
});
As you can see in the above, we modified your success function to include
$('#mydata').html(response);
provided all your data is printed and supplied correctly, it should display on the page.
EDIT:
it seems in your PHP query
$query = "SELECT bk.idlab , bk.codigolab , bk.capacidad, bk.carrera, bk.ubicacion FROM labs as bk WHERE bk.idlab = $pId";
You are selecting the columns prefixed with bk.* yet trying to print out the values without the prefix as seen below:
echo '<ul>' .
'<li>Laboratorio # ' . $row['codigolab'] . '</li>' .
'<li>Capacidad: ' . $row['capacidad'] . '</li>' .
'<li>Carrera: ' . $row['carrera'] . '</li>' .
'<li>Ubicación: ' . $row['ubicacion'] . '</li>' .
'</ul>';
Try changing the above to something like:
echo '<ul>' .
'<li>Laboratorio # ' . $row['bk.codigolab'] . '</li>' .
'<li>Capacidad: ' . $row['bk.capacidad'] . '</li>' .
'<li>Carrera: ' . $row['bk.carrera'] . '</li>' .
'<li>Ubicación: ' . $row['bk.ubicacion'] . '</li>' .
'</ul>';
If i understood it correctly.
Edit: ignore above php examples.
Change the success function from:
$('#mydata').html(response);
to
$('#mydata').append(response);
As .html() replaces all content within the specified element with the supplied content.
EDIT #2:
From the comments, you're ajax request is run every time that #LnkInfo is triggered which seems like it happens a lot as it loads the PopUp?
What you want to do is add in some logic, either in your jQuery function that checks if you've already appended the list to the popup and to stop it appending.
That could be done simply by adding a boolean variable somewhere in there.
Alternatively, you could just add a little div on that popup that you append it to.
Example:
This is your popup:
div class="popUp1 hide" id="popUpCorrecto1">
<div class="estiloPopUp">
<span>Información de laboratorio</span>
<span value="Cerrar" id="btnCerrar">x</span>
</div>
<!-- ADDED A NEW DIV HERE FOR LIST CONTENT -->
<div id="mylistcontent"></div>
<input type = "button" value = "Eliminar" id = "btnEliminar" onclick="eliminar()" />
<input type = "button" value = "Modificar" id = "btnModificar" onclick="window.location='modificarLab.html';" />
</div>
As you can see above, I've added the following:
<!-- ADDED A NEW DIV HERE FOR LIST CONTENT -->
<div id="mylistcontent"></div>
Now in your jQuery success function, you could append to that #mylistcontent div instead of the popup div :)

email generator in javascript and php

i have a javascript and php code that makes an email address hard for bots to find. i have it implemented on one site thats very basic and it works perfect, however on this other site with many more elements—something seems to go awry and it wont work.
the javascript adds in the mailto: and # functions
in the php, the elements are called in and the javascript runs to complete the function when you click on it——making it like a regular mailto: function.
is there something i'm missing in terms of perhaps DOM or global elements or something?
i have this script being called in my
header.php:
<script type="text/javascript" src="javascript/scripts.js"></script>
scripts.js:
function blind(name,domain) {
str = "mailto:" + name + "#" + domain;
window.location = str;
}
emailgen.php:
function showContacts()
{
global $debe;
$return ="";
$return .="
<div>";
$contactitems = $debe->runSql("SELECT * FROM contacts ORDER BY imp");
for($i=0; $i<count($contactitems); $i++)
{
$parts = explode('#', substr($contactitems[$i][3], $pos + 0));
$return .="
<p>" . $contactitems[$i][1] . "<br />
" . $parts[0] . "#" . $parts[1] . "<br />
</p>";
}
return $return;
}
when i view the source, it seems to show up okay but for some reason the mailto: isn't calling.
viewsource of emailgen.php:
name#email.com<br />
Add a single quote after $parts[0] . ":
" . $parts[0] . "#" . $parts[1] . "<br />

Categories