<?PHP
$result = mysql_query($query);
$finalval=0;
while($row = mysql_fetch_array($result))
{
$finalval=$finalval."<a onClick='showContent("please display")'
href='#' >". $row['Title'] ."</a> <br>" ;
}
echo $finalval;
?>
<script language="javascript" type="text/javascript" >
function showContent(value)
{
alert value;
}
</script>
Guys please help me out and please please tell me in a php code on clicking link how to call javascript/ajax function..Thank you so much
try alert(value) instead of alert value
Try this one ,opening double quotes within double quotes you need to escape them \
$finalval=$finalval."<a onClick='showContent(\"please display\")'
href='#' >". $row['Title'] ."</a> <br>" ;
}
<?PHP
$result = mysql_query($query);
$finalval = 0;
while ($row = mysql_fetch_array($result)) {
$finalval = $finalval."<a class='show-content' data-value='please display' href='#' >". $row['Title'] ."</a> <br>" ;
}
echo $finalval;
?>
With javascript querySelectorAll get all a links with class selector then handle them
<script language="javascript" type="text/javascript" >
var element = document.querySelectorAll(".show-content");
for (var link in element) {
element[link].onclick = function() {
showContent(this.getAttribute('data-value'));
};
}
function showContent(value){
alert(value);
}
</script>
with jQuery it is pretty stright forward,
<script language="javascript" type="text/javascript" >
$(document).ready(function(){
$("a.content").on('click', function(){
alert($(this).data('value'));
// or make a specific function call
});
});
</script>
Hope this will help you, and do not forget to escape the special charactors as mentioned by M Khalid Junaid
Related
I have
function delImage(posteId,imagebinId) {
$.get("<?php echo base_url('/Home/deletePostimage/') ?>");
return false;
}
i want to be like /Home/deletePostimage/posteId/imagebinId
i tried
$.get("<?php echo base_url('/Home/deletePostimage/')+posteId+"/"+imagebinId ?>");
but it divide the two numbers
like posteId=5 imagebinId =2
the results will be
/Home/deletePostimage/2,5
the params from
<a class="postimgsd" onClick="if(confirm('Are you sure you want to delete this image ?')){delImage(<?php echo $value['id'],$get_images[0]['binId']; ?>); rmItem(<?php echo $i; ?>);}else{} ; " >
With ES6, you can do this with string interpolation:
$.get(`<?php echo base_url('/Home/deletePostimage/${postId}/${imagebinId}') ?>`);
Without ES6, there is another answer that answers it, or use this:
var url = '/Home/deletePostimage/' + postId + '/' + imagebinId;
$.get("<?php echo base_url('" + url + "') ?>");
Furthermore, the code that calls this function should actually be:
<a class="postimgsd" onClick="checkDeletion()" />
<script type='text/javascript'>
function checkDeletion() {
if(confirm('Are you sure you want to delete this image ?')) {
var postId = <?php echo $value['id']; ?>;
var imagebinId = <?php echo $get_images[0]['binId']; ?>;
delImage(postId, imagebinId);
rmItem(<?php echo $i; ?>);
}
}
</script>
You need to keep in mind that PHP is processed on back-end before send the html to your user browser. That said, everything between php tags (<?php ... ?>) is rendered/processed before javascript even exists.
So if you put any JavaScript code inside your PHP code it won't work.
To make it work and be clean, do something like this:
function delImage(posteId,imagebinId) {
let url = "<?php echo base_url('/Home/deletePostimage/') ?>";
$.get(url + posteId + "," + imagebinId);
return false;
}
i have this code, now i want to send this $_SESSION['roll_id'] variable to another page menu.php where ajax function is written. how i send this variable to another ajax page for set data.
this is login.php page.
if($row["Login_Id"]==$username and $row["Login_Pass"]==$password)
{
echo "<h2 align='center'>" ."Login Sucessfull welcome" ." " .$row["Login_Id"]
."</h2>" ;
$_SESSION['roll_id']=$row['Roll_Id'];
//echo "ID" .$_SESSION['roll_id']; (give roll id)
header("Location: menu.php");
}
else
{
echo "<h2 align='center'>" ."Login Failed" ."</h2>";
}
this is menu.php page where whole functionality is written. i want to send rollid from this page to submenu.php where i can use this roll id in sql query.
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = '<?php json_encode($session); ?>';
$.ajax
({
type:'post',
url:'submenu.php',
data:{"roll_id":rollid},
success:function(response)
{
//console.log(response);
var menuArray= JSON.parse(response);
var html ="";
$.each( menuArray, function( key, value )
{
html += "<li><a href=''>" + value.Menu_Name + "</a>";
if(value.subMenu.length > 0)
{
console.log(JSON.stringify(value.subMenu));
html += "<ul>";
$.each( value.subMenu, function( key, subValue )
{
html += "<li><a href=''>" + subValue.text + "</a></li>";
});
html += "</ul>";
}
html += "</li>";
});
console.log(html);
if(response!="")
{
$("#main_menu").html(html);
}
}
});
});
this is submenu.php page
<?php
session_start();
include('config.php');
$roll_id = $_POST['roll_id'];
$q="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,b.Menu_Level,
b.MainMenu_ID, b.Menu_Order, b.Account_id,b.is_deleted from roll_menu AS a
join menu AS b on a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id;
$menu = mysqli_query($conn, $q);
$mainMenu = array();
foreach($menu as $x=>$value)
{
if($value['MainMenu_ID']==0)
$mainMenu[]=$value;
}
$menuData= array();
foreach($mainMenu as $y=>$value1)
{
$subMenu= array();
$m=$mainMenu[$y]['Menu_Id'];
$q1="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,
b.Menu_Level, b.MainMenu_ID, b.Menu_Order, b.Account_id,
b.is_deleted from roll_menu AS a join menu AS b on
a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id."and b.MainMenu_ID=$m";
$menu1 = mysqli_query($conn, $q1);
while($row=mysqli_fetch_array($menu1))
{
if($row["MainMenu_ID"]==$m)
{
$subMenu[]=array("text"=>$row["Menu_Name"]);
}
}
$value1["subMenu"] = $subMenu;
$menuData[] = $value1;
}
$menuDataJSON = json_encode($menuData);
echo $menuDataJSON;
now i attach the full code of submenu.php page.
Try like this may its helpful for you
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = "<?php echo $session; ?>"; //change here
alert(rollid)
$.ajax
({
type:'post',
url:'submenu.php',
data:{roll_id:rollid}, // change alse here
/*success: function (data) {
alert(data);
}*/
You echoed the <h2 ... on successful login and then used the header function to redirect. This will cause a warning `Warning: Cannot modify header information - headers already sent by” and redirection might not work.
As for AJAX, you need to echo the roll_id like this:
var rollid = '<?php echo json_encode($session); ?>';
I woudl also like to point out that since rollid is a single value, you dont really need to json_encode it.
1st : You missed to echo the variable .
2nd : if it's not a array no need json_encode
3rd : Before header function you will not echo any browser out put like html or echoing something will cause Warning: Cannot modify header information - headers already sent so take care about that .
4th : Try to put exit(); function after header function
header(....);
exit();
Js :
var rollid = '<?php echo $session; ?>';
just start_session() at top of page and try like this
var rollid = "<?php echo $_SESSION['roll_id']; ?>";
Hello every one i want to get text from this code
$content = '<span class="version_host">
<script type="text/javascript">
document.writeln('streamin.to');
</script>
</span>';
I want to get the text between ('streamin.to') streamin.to
I am using strip_tags() function of php
$test = strip_tags($content);
echo $test;
output:
document.writeln('streamin.to');
please help me i want the text streamin.to only.
One way is to Use str_replace
<?php
$content = "<span class='version_host'>
<script type='text/javascript'>
document.writeln('streamin.to');
</script></span>";
$test = strip_tags($content);
$test1 = str_replace("');","",str_replace("document.writeln('","",$test));
echo $test1;
?>
OR USING preg_match
<?php
$content = "<span class='version_host'>
<script type='text/javascript'>
document.writeln('streamin.to');
</script></span>";
$test = strip_tags($content);
$data = preg_match("/\'([^\']*?)\'/", $test, $matches);
echo $matches[1];
Or Using explode as stated by #Rene Pot
<?php
$content = "<span class='version_host'>
<script type='text/javascript'>
document.writeln('streamin.to');
</script></span>";
$test = strip_tags($content);
$array = explode("'",$test);
$string = $array[1];
echo $string;
?>
Hope this helps you
The following should provide what you need.
$content = "<span class='version_host'>
<script type='text/javascript'>
document.writeln('streamin.to');
</script>
</span>";
$test = strip_tags($content);
$array = explode("'", $test);
echo $array[1];
With explode you split the string "document.writeln('streamin.to')" by ' delimiter, and get an array of 3 elements.
What strip_tags() does is getting rid of any <> tags in a String, so document.writeln('streamin.to'); remains.
Now, you only want to get the part between the single quotes, so best would be to use regular expressions (learn more on regExOne.com)
output = "document.writeln('streamin.to');".match(/'([^']+)'/);
Then output[1] will contain what you're looking for.
edit:
If you want to achieve the same using php, try
preg_match("/'([^']+)'/", "document.writeln('streamin.to');", $output);
In that case $output[1] will contain what you're looking for
I am trying to populate a dynamic dropdown list based on the value user has inserted in the previous textbox(auto-complete). So, when user insert an actor/actress name in the auto-complete textbox, a dropdown will be populated by list of movies in which that actor has played.
Problem:
Could someone kindly let me know what is the problem with this code and why it populate an empty dropdown?
Here is the html/js code:
<html>
<?php
print_r($_POST);
?>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
</head>
<body>
Source:
<input type="textbox" name= "tag" id="tags">
<select id="movieImdbId" name="movieImdbId[]" multiple="multiple" width="200px" size="10px" style=display:none;>
</select>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
$("#tags").change(function () {
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#movieImdbId").html(response).show();
});
});
}
});
});
</script>
</body>
</html>
and this is actions.php code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['q']) && !empty($_POST['q'])){
$q = $_POST['q'];
$html = "";
try{
$conn = new PDO('mysql:host=localhost;dbname=imdb;charset=utf8mb4','user','pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = $conn->prepare("SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q");
$sql->execute(array(':q' => $_POST['q']));
while($rows = $sql->fetch(PDO::FETCH_OBJ)){
$option = '<option value="' . $rows['movieImdbId'] . '">' . $rows['movieImdbId'] . '</option>';
}
$html .= $option;
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
I really appreciate if someone can help me fix it.
Thanks.
You call via POST
$.post("actions.php")
but check for GET Variables
if(isset($_GET['q']) && !empty($_GET['q']))
So i guess your php script delivers an empty string.
Print the response to console and see if you get a result.
I am trying to alert the text of a div which is in a for loop when it is clicked. There are many divs with same id, i want to get 3 if i click the 3rd or 2 when 2nd is clicked. How can i make it with the following code or what must i add to it? Thank you.
<? for($i=0; $i<5; $i++) { ?>
<div id="abc"><? echo $i ?></div>
<? } ?>
<script>
$(function() {
$("#abc").click(function() {
var thevar= $("#abc").text();
alert (thevar);
}
</script>
Just try to use a class instead of using id inside that loop,
<? for($i=0; $i<5; $i++) { ?>
<div class="abc"><? echo $i ?></div>
<? } ?>
<script>
$(function() {
$(".abc").click(function()
{
var thevar= $(this).text();
alert (thevar);
});
});
</script>
You should have unique ids on page. due to this $("#abc").text() always returns value for first element in matched selector. Rather use abc as class. and to refer element in current context, use $(this):
var thevar=$(this).text();
You have syntax error in your code. Missing }); . Id should be unique .
<? for($i = 0;$i<5;$i++) { ?>
<div class="abc"><? echo $i ?></div> //change
<? } ?>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(function() {
$(".abc").click(function()
{
var thevar= $(this).text(); //change
alert (thevar);
});//was missing
});//was missing
</script>