Script works on every post but not the last post - javascript

My script removes the http:// and www from urls displayed in a post's content but for some reason it either affects all the posts but the last one or just the first post of the page depending on where I place the script.
For instance if it's in the loop it will affect all the posts but the last but if it's outside the loop it only affects the first post.
I'm looking for a solution so that it takes affect on all urls being displayed on a page. Any help would be much appreciated.
<?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<Script>
$(document).ready(function removeFunction() {
let post_id = '<?php global $post; echo $post->ID; ?>';
var str = document.getElementById("link" + post_id).innerHTML;
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
document.getElementById("link" + post_id).innerHTML = res;
});
</Script>
<p><?php the_content(); ?></p>
<!-- This is where the URL's are EX: <a id="link[return_post_id]" href="http://example.com/">http://example.com/</a> -->
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
?>

1.You tagged jQuery there so put jQuery code outside of loop.
2.It has to iterate over all <p> and do what you are doing.
3.Change <p><?php the_content(); ?></p> to <p data-id="<?php global $post; echo $post->ID; ?>"><?php the_content(); ?></p> (inside while loop)
4.After above steps followed, change jQuery code like below:
<Script>
$(document).ready(function() {
$('p').each(function(){
let post_id = $(this).data('id');
var str = $(this).html();
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
$(this).html(res);
});
});
</Script>

there is a problem and this is on mixture of php and javascript.
Your php code Generate JS Within a Loop, in each loop it will create a function named removeFunction() and your browser interpreter mixed up things. it will replace the last one.
There Are 2 Solution for Your problem:
First is to make These Functions Distinct like This:
$(document).ready(function removeFunction<?php echo $post->ID; ?>() {
this will make function names as removeFunction1() removeFunction2() ...
The Second Sulotion is to Define The function outside The loop and in the php loop just call the function like this:
while (have_posts()) : the_post(); ?>
<script>
removeFunction(<?php global $post; echo $post->ID; ?>);
and your function definition would be like this:
removeFunction(post_id){

Related

Output value in javascript from php loop

I'm not sure how to search this, but I have an array in php numbered 1 to 20. I have a foreach loop to output the values and have the user be able to click on the numbers. After clicking the number, the page would then output the number clicked.
HTML:
<div id="chapters" onclick="getChapter()">
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter">Chapter <?php echo $chapter;?></p>
<?php
}
?>
</div>
Javascript
function getChapter() {
chapter = document.getElementById("currChapter").id;
document.write(chapter);
}
I'm not able to output the number that the user clicks on.
I have tried putting
id=<?php $chapter?>
, but that does not work as well as replacing id with value and name.
I would recommend passing the $chapter as parameter of a function "Onclick" event :
<div id="chapters">
<?php
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
?>
and the Javascript:
function getChapter(chapterNumber) {
alert(chapterNumber);
}
I don't really understand what you want to do, seems you explanation just a example, but may be this will help. You can call function getChapter with parameter ( onClick="getChapter(<?php echo $chapter;?>) ) :
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
function getChapter(chapter) {
document.write(chapter);
}

AJAX - Undefined PHP variable

I have the following problem, the following script sends a keyword a PHP file hosted in another domain (I already added the CROS headers), this PHP returns me some "echos of different variables" (title, thumbnail, url, etc.) And it works but randomly returns me "Undefined variables".
The first thing was to add an if (isset ()) to my variables in PHP and the error does not appear anymore but the results returned by my searches are much smaller (Before adding it averaged 10 to 20 results, Now I get 5 results).
Can this be a problem with my script?
My form.php
<form method="POST" action="" id="form-busqueda">
<input type="text" name="keyword">
<button id="search" name="search">Search</search>
<div id="results"></div>
<script>
jQuery(function($){
var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
$('[id^="form-busqueda"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/script.php',
data : $(this).serialize(),
beforeSend: function(){
$('#results').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
});
});
});
</script>
</form>
My script.php (dlPage is a function that create cURL connection):
<?php
if (isset($_POST['keyword'])) {
$search = $_POST['keyword'];
$html = dlPage("http://example.com/" . $search);
//where I search and get with simple_html_dom example:
$video = $videos->find('div.example2>a', 0);
$title = $video->innertext;
$url = $video->attr['href'];
$id = $video->attr['id'];
$thumbnail = $video->find('div.thumb', 0)->innertext;
echo $title;
echo $url;
echo $id;
echo $thumbnail[0];
}
?>
I've updated my code, I didn't put all the code because I thought that it isn't relevant, my script.php works fine with pure PHP. The problem appear when I use AJAX.
I'm getting the following error:
Notice: Undefined variable: title in C:\xampp\htdocs\webs\ladoserver\script.php on line 13
Notice: Undefined variable: title in C:\xampp\htdocs\webs\ladoserver\script.php on line 13
Notice: Undefined variable: url in C:\xampp\htdocs\webs\ladoserver\script.php on line 14
The undefined variable is coming from your PHP file (/ladoserver/script.php).
What generates the variables being returned? The most common "cause" of this, is by only setting the variables within a block of code that might not be executed (eg within an if block, or in a loop that iterates 0 times)
You could get around the error (assuming you're okay with blank values) by defining each of the variables at the top of your script.
<?php
$title = "";
$thumbnail = "";
$url = "";
$id = "";
?>
Edit: #snip1377 reminded me that you can also just use isset at the end of your script before the output as well.
Here's some sample code for your $thumbnail variable, which you could apply to all your variables being returned
<?php
if (isset($thumbnail))
{
echo $thumbnail;
}
else
{
echo "";
}
?>
Alternativaely, you can use a ternary operator:
<?php
echo (isset($thumbnail)) ? $thumbnail : '';
?>
Edit again: just to illustrate what I mean about how the variables might not get defined within a script, here is an example that could cause that undefined error:
<?php
if ($_POST['value'] == 1)
{
// This will never be reached unless $_POST['value'] is exactly 1
$return_val = 1;
}
echo $return_val;
?>
This will give the undefined warning, if $_POST['value'] is anything other than 1.
Similarly, if $_POST['value'] were 0 in the following code, it would have that undefined warning as well:
<?php
for ($i=0; $i<$_POST['value']; $i++)
{
// This will never be reached if $_POST['value'] is less than 1
$return_val = $i;
}
echo $return_val;
?>
In the examples above, you can simply define $return_val at the top of the script, and you won't get the error anymore.
You send this data as a post method.you shuld echo them with $_post['name'] but you just echo $name
Use this in script.php :
<?php
echo $_POST['title'];
echo $_POST['thumbnail'];
echo $_POST['url'];
?>

phpcoding special characters

When I load a php page, i put within a javascript function, a name. The problem comes when this string has special chars like '.
Here I paste the code of a click event:
showSocialShare(event, '<?php echo $object->slug; ?>', '<?php echo htmlspecialchars($object->title); ?>', '<?php echo $object->image; ?>')
I thought that the function htmlspecialchars code somehow the string but the result is:
showSocialShare(event, '4049269', 'collection-'Noun'', '/img/Original.jpg')
As can be seen, at the second parameter, the name contains characters like ' and arises an error.
How can I avoid this?
Never output text from PHP directly into a Javascript context. As you're finding out, it's VERY easy to generate JS syntax errors.
Always use json_encode: e.g. given this
<?php $foo = 'bar'; ?>
<script>
var badly_broken = <?php echo $foo ?>;
var working_fine = <?php echo json_encode($foo); ?>;
</script>
You'll end up with
<script>
var badly_broken = bar; // oops - undefined variable "bar"
var working_fine = "bar";
</script>
And note that if you're outputting JS into an HTML attribute, you not only have to generate valid Javascript, you have to output valid HTML AS WELL:
<?php $foo = array('bar' => 'baz'); ?>
<a onclick="brokenCall(<?echo json_encode($foo) ?>)">
<a onclick="workinCall(<? echo htmlspecialchars(json_encode($foo)) ?>)">
produces:
<a onclick="brokenCall({"bar":"baz"})">
^--start attribute
^--end attribute - ruhroh
<a onclick="workingCall({"bar":"baz"}")>

How can I pass the name of the field in form_error ()

It's part of my view. Me need transmit input name in on which i click.
Below is a script that will get the name input after click
<div class="form_hint"><?=form_error('this get value from javascript after click')?></div>
<?php echo form_open("onenews/" . $onenews['id'] . "#signup", $form_reg['main_form']); ?>
<?php echo form_input($form_reg['login'], $this->form_validation->set_value('login')) ?>
<?php echo form_input($form_reg['email'], $this->form_validation->set_value('email')) ?>
<?php echo form_input($form_reg['password']) ?>
<?php echo form_input($form_reg['conf_password']) ?>
<?= MY_Controller:: create_captcha(); ?>
<?php echo form_input($form_reg['captcha']) ?>
<?php echo form_input($form_reg['submit']) ?>
<?php echo form_close(); ?>
</div>
</div>
jq
<script type="text/javascript">
$(function(){
var curInput = '';
$('#form_reg').find('input').on('click', function(){
curInput = $(this).attr("name");
});
})
</script>
Or i must use ajax?
Thanks!
Your question is not clear at all, but I assume you want to dynamically change the content of the form_hint div. You can't do that with PHP. Once PHP renders the page, it shuts down and does nothing more. So the only way to make PHP show that message is after the form submit, but then you lose your click data. There is a way to save the clicked element in a session for example, but that would be a really bad solution.
So the best solution would probably be to list all the hints in a JavaScript variable, and call the appropriate one upon the click event, and fill the form_hint div with it.
$('.form_hint').text(yourAppropriateMessageHere);
An example with a hidden div for the login input field with exactly how you described would be:
<div class="form_text_login"><?=form_error('login')?></div>
JS
var loginMessage = $('.form_text_login').text();
// list others here
// then make a tree with switch/case or if/else
if (curInput == 'login') {
$('.form_hint').text(loginMessage);
}
else if (curInput == 'email') {
// do the same with the email message, etc.
}

display a calulated value on all post in a category in wordpress

i am working on wordpress based coupon site. I have to create a amount calculator which would work on all the individual category pages . I would be having a amount slider which would be having $ values.
Once a value is selected and on clicking the submit button, i want the percentage deals (under that respective category) to calculate a amount with respect to the $ amount selected using the slider. and then displaying it on their respective deals.
I hope the idea is clear.
Till now, i have managed to, take all the posts title of the current category page into an array, and then using the preg_match feature, i have managed to extract out the '%' deal amount.
Also i have created a simple slider which the user will need to input their $ amount.
<?php
$array = array();
global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;
$myposts = get_posts(array('numberposts' => 1, 'offset' => 0, 'category__in' => array($category), 'post_status'=>'publish'));
foreach($myposts as $post) :
setup_postdata($post);
$title = get_the_title();
array_push($array,$title);
endforeach; ?>
<?php wp_reset_query(); ?>
<?php
foreach($array as $str) {
if(preg_match('/(\d+)\%/i' ,$str,$m)) {
echo $m[1],"\n"; ?>
<input type="text" name="a" value="<?php echo $m[1]; ?>" size=5>
<?php }
} ?>
the above code is used to fetch all the post under the current category and extracting the % value from the respective post title. The extracted number is in '$m[1]' which i would like to pass against the respective post.
I am not able to define the respective post and passing that '%' amount and in return sending the calculated amount and saving it back to that particular post. that is, on clicking the submit button, i would want that each post having percentage value would get calculated and get displayed against that particular post. Sorry for such a huge explanation. I didnt want any detail to get missed out. Any help would be appreciated.
EDITED CODE - This code is responsible to display a single deal. I have placed the above mentioned in the sidebar file of my theme. I want to display the savings within the respective percentage deal.
<div style="float:left; <?php if($GLOBALS['themename']['display_previewimage'] =="yes"){ ?>width:357px;<?php }else{ ?>width:477px;margin-left:10px;<?php } ?>">
<h2 class="coupontitle">
<a href="<?php echo $link; ?>" title="<?php the_title_attribute(); ?>" <?php if($GLOBALS['premiumpress']['analytics_tracking'] =="yes"){ ?>onclick="pageTracker._trackEvent('COUPON CLICK', 'TITLE CLICK', '<?php the_title(); ?>');"<?php } ?> <?php if(is_single()){ ?> target="_blank"<?php } ?>>
<?php the_title(); ?>
</a>
</h2>
<p><?php echo $post->post_content; ?></p>
<?php if($code != "" && $GLOBALS['themename']['system'] =="link"){ ?>
</div>
Ok I have created a JSFIDDLE that will give you an idea about what to do. http://jsfiddle.net/Q5sAK/1/
For this I used the jquery UI slider but this should work for your own slider you just need to call the $.each() function when you are ready.
So we know that your percentage is in the h2 tag with the class coupontitle of all of you products.
First we are going to start by modifying that h2 to have a span tag at the end that we will use to hold the computed savings:
<h2 class="coupontitle">
<a href="<?php echo $link; ?>" title="<?php the_title_attribute(); ?>" <?php if($GLOBALS['premiumpress']['analytics_tracking'] =="yes"){ ?>onclick="pageTracker._trackEvent('COUPON CLICK', 'TITLE CLICK', '<?php the_title(); ?>');"<?php } ?> <?php if(is_single()){ ?> target="_blank"<?php } ?>>
<?php the_title(); ?>
</a>
<span><span>
</h2>
Then we need to add the javascript that will calculate the savings.
function updateSlider(){
//Get the value of the slider.
var curentSliderAmount = $('#sliderId').val();
//Loop over all of the titles
$.each($('.coupontitle'),function(index,coupObj){
//This will create the variable from the regex search that will have all of the parts for the percent we need
var percent = $(coupObj).text().match(/(\d+)\%/i);
//We will then take the 2nd part which is just the number without the % sign and make it a percent then multiply that by the slider value and then fix it to a 2 decimal value so it can be used a curency.
var savings = ((percent[1]*.01) * curentSliderAmount ).toFixed(2);
//We then set the span html content = to our newly calculated value.
$('span',coupObj).html('Save: $'+savings);
});
}
//Run this when the page starts
$(document).ready(function(){ updateSlider() });
Then you just need to call updateSlider() when ever the slider updates.

Categories