Can anyone help advise why this setTimeout() function is not working? I have tried many version over the net and it is still not working.
<script type="text/javascript">
function makeSlection(frm, proj, tenure, address, postal, cat, parent, estate, latlng, district, state) {
alert(proj);
alert('hello im inside makeselection function');
opener.projectn.value = proj;
opener.tenure.value = tenure;
opener.address.value = address;
opener.postcode.value = postal;
opener.category.value = parent;
opener.category.onchange();
opener.state.value = state;
opener.region.value = estate;
opener.add.value = latlng;
opener.latlngse.click();
//setTimeout(function(){alert('hi');},3000);
setTimeout(function(){ pelay(cat); },5000);
}
function pelay(cate){
alert(cate);
opener.category_id.value = cate;
this.close;
}
</script>
<body>
Please select project name.
<form id="fsrm" name="fsrm" action="#">
<table width="100%">
<?php
for($i=0;$i<count($prolists);$i++){
$row = $prolists[$i];
?>
<tr>
<td>
<button type="submit" name="nselect<?php echo $row->id ?>" id="nselect<?php echo $row->id ?>" value="<?php echo $row->project_name ?>" onclick="JavaScript:makeSlection(this.form, document.getElementById('nselect<?php echo $row->id ?>').value, '<?php echo $row->tenure ?>', '<?php echo $row->address ?>', '<?php echo $row->postal_code ?>', '<?php echo $row->cat ?>', '<?php echo $row->parent_id ?>', '<?php echo $row->estate ?>', '<?php echo $row->lat ?>,<?php echo $row->lng ?>', '<?php echo $row->district ?>', '<?php echo $row->state ?>');">Select</button>
</td>
<td>
<?php echo $row->project_name ?>
</td>
</tr>
<?php } ?>
</table>
</form>
</body>
Even when I try this:
setTimeout(function(){alert('hi');},3000);
It's also not working.
Just added the body codes to call the javascript.
Short Answer
It does work. Something else must be going wrong for you.
Long answer
First of all, mixing HTML/Javascript/PHP like that makes it a lot harder for anyone to understand what the hell your code is trying to achive.
Secondly, your question stands a better chance of getting an answer that will help you progress to a solution if you make it Short, Self Contained, Correct, and add an Example.
Preferably one we can view online which demonstrates the simplest version you could create that is working (or in this case broken).
Such a version would look something like this:
<script>
function makeSlection(cat) {
alert('hello im inside makeselection function');
setTimeout(function(){ pelay(cat); },1500);
}
function pelay(cate){
alert(cate);
}
</script>
<button onclick="JavaScript:makeSlection('foo');">Select</button>
I took the liberty of creating an example on JsFiddle from the code you provided us with.
Which leads me to the third point: the simplified version of the code you gave us in your question works. Both alerts get triggered.
So I'm guessing we are not getting the full picture here.
Your setTimeout is inside the makeSelection function so it will only set the timeout once the makeSelection function is executed.
Related
I need to echo multiple line error in JS alert and I am using below code
Working code
$str = "This is a error1\\n";
$alert = $str."This is error2";
if(!empty($alert)){
?>
<script type="text/javascript">
alert('<?php echo $alert;?>');
</script>
<?php
}
but I need to work on an old written code so this has addslashes function before echo alert like below:
$str = "This is a error1\\n";
$alert = $str."This is error2";
$alert = addslashes($alert);
if(!empty($alert)){
?>
<script type="text/javascript">
alert('<?php echo $alert;?>');
</script>
<?php
}
Output : This is a error1\nThis is error2
I need this to print in two lines I have also tried with only \n but it is not working then.
I'd make javascript do the hard work.
<script type="text/javascript">
var alertArr = ["<?php echo $string1; ?>", "<?php echo $string2; ?>"];
alert(alertArr.join("\n"));
</script>
https://jsfiddle.net/0uwmmm3n/
(Magnificent random url by the way)
EDIT: less messy version, maybe more legitimate
<?php $alertArr = [$string1, $string2]; ?>
<script type="text/javascript">
var alertArr = <?php echo json_encode($alertArr); ?>;
alert(alertArr.join("\n"));
</script>
RE-EDIT: nah, too much work for a job so simple, two conversions is way too much
$str = "This is a error1\\n";
$alert = $str."This is error2";
$alert = addslashes($alert);
if(!empty($alert)){
?>
<script type="text/javascript">
alert('<?php echo $alert;?>');
</script>
<?php
}
I have used this code and it working fine according to your need
if still issue continues then clear your cache
I have this line of code
<script type="text/javascript">
document.title = "<?php include('pot1.php');?>"
</script>
My pot1.php gives me an echo with one random number, but that code does not seem to work and I don't know why the echo doesn't appear in my title. Is anything wrong with the code?
pot1.php code:
<?php
#include_once('link1.php');
$cg = fetchinfo("value","info","name","current_game");
$cb = fetchinfo("cost","games","id",$cg);
$cb=round($cb,2);
echo '$'.$cb;
?>
This echo is working and is giving me values because I can see them in one div.
You should just do it like this:
<?php include('pot1.php');?>
Now we know that there is a variable set. Echo that into the title tag.
<script type="text/javascript">
document.title = "<? echo $cb ?>"
</script>
The way you're doing it now... I don't think you can include an entire PHP page and expect to behave like a simple string, even if that's all it returns.
Put the value you want inside a variable in the pot1.php file and use it on the title
<?php include('pot1.php');?>
<script type="text/javascript">
document.title = "<?php echo $yourVar;?>"
</script>
I'm trying to upgrade my like-system to something more practical.
Currently I have it like Like then in the PHP have something like: if $_GET['like'] is set, then grab the user's ID and the post ID and call a function called like_status($post_id,$user_id);
However, I've been working on something like this:
The main part that shows on the statuses:
<script src="https://mysite/stuff/jquery.min.js"></script>
<script src="https://mysite/stuff/js/global.js"></script>
<input type="hidden" id="postid" value="<? echo $postid; ?>">
<input type="hidden" id="userid" value="<? echo $session_user_id; ?>">
<span id="like-button" style="color:red;">Like</span>
The Javascript/jQuery:
$('span#like-button').on('click', function(){
var postid = $('input#postid').val();
var userid = $('input#userid').val();
if (postid != ''){
$.post('https://mysite/stuff/ajax/like.php', {postid: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = data;
});
}
});
and finally,
My like.php script:
<?php
if(isset($_POST['postid']) === true && empty($_POST['userid']) === false){
include $_SERVER['DOCUMENT_ROOT'].'/stuff/init.php';
if(is_liked($_POST['postid'],$_POST['userid']) === true){
unlike_status($_POST['postid'],$_POST['userid']);
echo 'Like';
} else {
like_status($_POST['postid'],$_POST['userid']);
echo 'Unlike';
}
}
?>
My unlike/like functions work fine. I have a working like system now, but it makes the user refresh and everything every time, and it's very inconvenient. I'd like to use this method to automatically update the like button without having to refresh the page or anything. This way, users can like multiple things on the page, and not have to refresh the page every time. I also think it's more secure since the $_GET['like'] can be changed to any id, even if user's aren't friends with other users, or the status doesn't exist.
My issue:
Okay, so whenever I click the like button, nothing happens. I tried this in a separate page as well (changing the type from hidden to text, and manually inputting the data) and it didn't work either. It seems the javascript doesn't execute. I've opened up console in google chrome, and when I click the button, nothing happens. The like doesn't get posted to the database, and the button doesn't get updated.
Can anyone explain what I'm doing wrong? Possibly point me in the right direction to fixing this?
UPDATE
I tried combining the Javascript/HTML in one page to have dynamic variables.
This is what shows up for each status:
<script src="https://mysite/stuff/jquery.min.js"></script>
<script type="Javascript">
$(document.body).on('click','#like-button', function(
var postid<? echo $status_id; ?> = $('input#postid<? echo $status_id; ?>').val();
var userid<? echo $status_id; ?> = $('input#userid<? echo $status_id; ?>').val();
$.post('https://mysite/stuff/ajax/like.php', {postid: postid<? echo $status_id; ?>, userid: userid<? echo $status_id; ?>}, function(data){
document.getElementById('like-button').innerHTML = data;
});
));
</script>
<input type="hidden" id="postid<? echo $status_id; ?>" value="<? echo $status_id; ?>">
<input type="hidden" id="userid<? echo $status_id; ?>" value="<? echo $session_user_id; ?>">
<span id="like-button" style="color:red;"><? if(isliked($status_id,$session_user_id) === true){ ?>Unlike<? } else { ?>Like<?}?></span>
I still can't get it to execute the script.
You can always just use $('#fomrm_id').serialize(), to get all the form fields at once in POST data. It refreshes page because you have to add return false; to the end of jQuery.click event.
If those elements are being created dynamically (or as in your case script is being executed before they are created), you need to set proper .on event, this one is not good, as it binds to the element that may not be there.
Should be rather:
$(document.body).on('click','#like-button', function(){..}); - that will bind it to document body, that is always there, but will check for selector in second argument if it matches.
It's not exactly what I wanted to do, but it's good enough. I managed to get the like button to work/update without refreshing and such. Thanks to everyone for the help if it wasn't for your suggestions I would've never found this out.
<input type="hidden" id="postid" value="<? echo $status_id; ?>"><br>
<input type="hidden" id="userid" value="<? echo $session_user_id; ?>"><br>
<span id="like-button" style="color:red;"><? if(isliked($status_id,$session_user_id) === true){ ?>Unlike<? } else { ?>Like<? } ?></span>
<script>
$('span#like-button').on('click', function(){
var postid = $('input#postid').val();
var userid = $('input#userid').val();
<? if(isliked($status_id,$session_user_id) === true){ ?>
$.get('https://mysite/dash', {unlike: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = 'Like';
});
<? } else { ?>
$.get('https://mysite/dash', {like: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = 'Unike';
});
<? } ?>
});
</script>
I realize this has been asked numerous times here, but I just can't figure it out. I'm certain it is simple, but I've been banging my head a little. I have search results that are php arrays, displayed in a jquery window. I need to eventually get them back to the server, but first need to pass them to jquery variables. This is where I am stuck.
You will see I have made an attempt to via $book_title, trying to pass that to a jquery variable "title"
<script>
$(function() {
$( "#dialog" ).dialog({
height: 550, width: 450});
$( ".btn" ).click(function(){
//assign values to each variable
//var title = $("#returnvalues").val();
var title = <?php echo json_encode($book_title);?>;
var author = $("#returnvalues").val();
var published = $("#returnvalues").val();
var description = $("#returnvalues").val();
var pages = $("#returnvalues").val();
var publisher = $("#returnvalues").val();
var ISBN = $("#returnvalues").val();
//book_title = $item['volumeInfo']['title'];
$.ajax({
type: "POST",
url: 'book-meta.php',
dataType: 'json',
//assign values to the variables to be passed to the server via data
data: { title : title, author : author, published : published,
description : description, pages : pages, publisher : publisher, ISBN : ISBN},
success: function(data)
{
//alert(data);
//identify the variables for unique handing on the server side
$("input[name='bbp_topic_title']").val(data.title);
$("input[name='bbp_extra_field1']").val(data.author);
$("input[name='bbp_extra_field2']").val(data.published);
$("input[name='bbp_extra_field3']").val(data.description);
$("input[name='bbp_extra_field4']").val(data.pages);
$("input[name='bbp_extra_field5']").val(data.publisher);
$("input[name='bbp_extra_field6']").val(data.ISBN);
//$("#displayResults").html(data);
},
error: function(errorThrown){
alert('error');
}
});
$( "#dialog" ).dialog( "close" );
});
});
</script>
<strong><p style="font-size: 16px; text-align: center";>Top 10 Results for "<?php echo #$_POST['q']; ?>"</p></strong>
<strong><p style="font-size: 14px; text-align: center";>choose a book to select as your topic</p></strong>
<table style="width:400px">
<col width="325">
<col width="75">
<?php $i=0; foreach ($data['items'] as $item) { $i++; ?>
<tr>
<td>
<strong><u><div style="font-size: 14px";><?php printf($item['volumeInfo']['title'])?></u></div></strong>
<strong>Author: </strong><?php printf( $item['volumeInfo']['authors'][0])?><br />
<strong>Published: </strong><?php printf( $item['volumeInfo']['publishedDate']); ?><br />
<strong>Page(s): </strong><?php printf( $item['volumeInfo']['pageCount']); ?><br />
<strong>Publisher: </strong><?php printf( $item['volumeInfo']['publisher']); ?><br />
<strong>Category: </strong><?php printf( strtolower($item['volumeInfo']['printType']).', '.strtolower($item['volumeInfo']['categories'][0])); ?>
<strong>ISBN: </strong><?php printf( $item['volumeInfo']['industryIdentifiers'][0]['identifier']); ?></td>
<td><p><input type="submit" method="post" name="selectbook" value="Select" class="btn" id="returnvalues" /></p>
<img src="<?php printf( rawurldecode($item['volumeInfo']['imageLinks']['smallThumbnail'])); ?>" />
</td>
<tr><td style="width:420px"><p><strong>Description: </strong><?php printf( $item['volumeInfo']['description']); ?><br /></p></td>
<?php $book_title=$item['volumeInfo']['title'];
//$book_meta=array($item['volumeInfo']['title']=>"$book_title",$item['volumeInfo']['authors'][0]=>"$book_author");
//print(json_encode($book_meta));
Any help is appreciated. If this gets marked as a duplicate question, please also give this newbie some specific direction. Thanks.
I figured this out! Thanks to XQDev and Uttara for the help! I had to create a separate script, within the loop where my php results are displayed. In this separate script I declare my javascript variables only.
<script>
var title = <?php echo json_encode($book_title); ?>;
</script>
Issue is resolved! Hopefully this thread will help someone in the future with a similar issue.
var title = "<?php echo $book_title; ?>" could cause your wanted result.
The result can be checked by using alert(title) after the assignment.
Your variable are no "jQuery Variables", by the way. They are ordinary Javascript variables. But you pass and access them by using jQuery methods.
But: Your way, in case $book_title contains a string, should be fine, too.. What exactly isn't working?
If you are trying to assign php array to javascript variable then do this
var title = <?php echo json_encode($book_title); ?>;
considering that your $book_title is an array
Eg: <?php
$book_title = array('one', 'two');
?>
javascript: title = ['one', 'two']
I looked around but couldnt find what i looked for so i thought i should try and ask.
Also i should mention i am quite new to most codes.
I am trying to get multiple variables from my database into my function.
From here i need the image link and the id. (As you can see i tried to link them in the onclick=)
<div id="HeadItems" >
<?php
$sqlhead = "SELECT * FROM items
WHERE part = 'head'";
$headquery = mysqli_query($con, $sqlhead) or die (mysqli_error($con));
while($headf = mysqli_fetch_assoc($headquery))
{
?>
<img class="headArmor" src="<?php echo $headf['image']; ?>" onclick="headHide('<?php echo $headf['image']; ?>", "<?php echo $headf['id']; ?>')"/>
<?php
}
?>
</div>
They go into my function:
function headHide(src, chosenid) {
var head = document.getElementById("head");
var HeadItems = document.getElementById('HeadItems');
HeadItems.style.display = 'none';
head.innerHTML = "<img src='" +src+ "' width=80; height=80;>";
var chosenhead = chosenid;
}
(when i click on the image the image is then inserted into the head.innerHTML)
Problem is that after i put in the second variable in the function (chosenid and the $headf['id'] in the while loop) it stopped working.
I probably made it hard to understand now (I'm dutch) so a small summary:
I want my onclick function to give me the $headf['head'] and $headf['id'].
so i can make the $headf['id'] into a var
You seem to have some single quotes missing here:
onclick="headHide('<?php echo $headf['image']; ?>', '<?php echo $headf['id']; ?>')"
^ ^
The problem is with the quotes in the definition of onclick.
This should work.
onclick="headHide(<?php echo '\''.$headf['image'].'\',\''.$headf['id'].'\''; ?>)"
//This will be onclick="headHide('image','id')"