Is it possible to make script tag in to the database print area? I need to add some JavaScript in to table. How can I add this?
Here is the sample of script
$results = $mysqli->query($query);
if($results) {
print ' here the Script '
<script>
$(document).ready(function() {
$('#b1').click(function(){
var data = $('#f1').serialize();
$.post( "post.php", data,function(return_data,status){
$("#display").html(return_data.msg);
setTimeout(function() { $("#display").fadeOut('slow'); }, 4000);
},"json");
})
});
</script>
<?php
$html = ' <script>
$(document).ready(function() {
$("#b1").click(function(){
var data = $("#f1").serialize();
$.post( "post.php", data,function(return_data,status){
$("#display").html(return_data.msg);
setTimeout(function() { $("#display").fadeOut("slow"); }, 4000);
},"json");
})
});
</script>';
echo $html;
?>
Related
I am building an edit feature of a post on a website, so i am using jquery ajax and php as the script file that makes the edit inside a database. The problem is in the return script, i have a script tag which contains some jquery and then i place the returned data inside a div, but the script tag is being printed as if it was a text. Can someone help me please to let the script tag act as an actual script and not being printed as text ?
here is my html div :
<div class="board_post_span" id="<?php echo $board_id."-".$board_user_id;?>-spanBoardEdit"><?php echo $board_post;?></div>
and here is my php script :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
require_once '../includes/create_thumbnail.php';
// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
exit;
}
if(isset($_POST['board_id'], $_POST['board_textarea'])) {
$board_id = (int)$_POST['board_id'];
$board_textarea = mysql_prep($_POST['board_textarea']);
// UPDATE table
$query = "UPDATE board_table ";
$query .= "SET board_post = '$board_textarea' ";
$query .= "WHERE board_id = $board_id";
$result = mysqli_query($connection, $query);
// now we select the updated board post
$query2 = "SELECT * FROM board_table ";
$query2 .= "WHERE board_id = $board_id ";
$result2 = mysqli_query($connection, $query2);
confirm_query($result2);
$result_array = mysqli_fetch_assoc($result2);
}
?>
<?php
echo $result_array['board_post'];
?>
<script>
// This takes care of the board Continue Reading feature ---------------------------------------------------------
$(".board_post_span").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('Continue Reading');
} else {
$(this).text(boardPostText);
}
});
</script>
and here is my jquery and ajax :
$.ajax({
url: url_edit_board,
method: "POST",
data: {
board_id: saveBoardButtonId,
board_textarea: editBoardTextareaVal
},
beforeSend: function() {
CustomSending("Sending...");
},
success: function(data){
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
// this makes the scroll feature comes back
$("body").css("overflow", "scroll");
console.log(data);
$("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").html(data);
$("#"+saveBoardButtonId+"-formBoardEdit").hide();
$("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").show();
}
});
The reason is that you're setting boardPostText to the text of the entire DIV, which includes the <script> tag inside the DIV. You should put the text that you want to abbreviate inside another span, and process just that.
So change:
echo $result_array["board_post"];
to:
echo "<span class='board_post_text'>" . $result_array["board_post"] . "</span>";
Then in the JavaScript you're returning you can do:
$(".board_post_text").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('Continue Reading');
} else {
$(this).text(boardPostText);
}
});
First of all, it seems you don't need else part:
else {
$(this).text(boardPostText);
}
Then, before do anything, make sure that your return data from PHP file, the text has not become encrypted in some way. if < becomes < then the text never consider as JS code.
You can create a script tag then place your JS script into it as a function then call it yourself right after injecting.
replace your script in PHP file with this:
<script>
var scriptText = `function editPost() {
$(".board_post_span").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if (boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('<a href="board_comment.php?
user_id='+boardPostUserId+'&board_id='+boardPostId+'" class="board_continue_reading" target="_blank" id="'+boardPostId+'-continueReading">Continue Reading</a>');
}
});
}`
</script>
then change your js file to:
$.ajax({
// ...
success: function(data) {
// ...
var container = $("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit")
container.html(data)
var scriptEl = $('<script></script>').html(scriptText).appendTo(container)
// now call the editPost function
editPost()
$("#"+saveBoardButtonId+"-formBoardEdit").hide();
container.show();
}
});
I want to add a javascript value to my php query. The code goes like this
<script>
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
<?php
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = '?' ");
?>
})
</script>
I want to put the value of categoryName to the query which I made in php. How will I do it.
Just spend a few hours trying to figure this out myself today. You can use ajax, and send the information using the data tag in an ajax query.
$.ajax({ url: 'file goes here',
data: {action: '0'},
type: 'post',
success: function(output) { //action }
});
The data tag gives you the information.
In your php:
$data = $_POST["action"];
you should use ajax to get the attribute from your clicked div and send it to a php page where you receive the "javascript variable" and use it as a php variable with $_POST like this:
<script type="text/javascript">
$(function() {
$(document).on('click', '.dropdown-menu li a', function() {
{
var categoryname = $(this).attr("id");
var dataString = 'categoryname'+ categoryname ;
$.ajax({
type: "POST",
url: "yourphppage.php",
data: dataString,
cache: false,
success: function(html)
{
$(".result").html(html);
}
});
return false;
});
});
Now in your php page:
$categoryname=$_POST['categoryname'];
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = $categoryname
");
It doesn't go this way, unless you make AJAX calls (see http://api.jquery.com/jquery.get/ and other answers).
The simplest solution (if you do not have too many categories, say a few hundreds tops) would be to cache the categories client-side in a Javascript variable, as in:
<script type="text/javascript">
var categoriesCache = <?php
$cache = array();
$result = mysqli_query($con, "SELECT id, category_name FROM tb_category");
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$cache[$row["category_name"]] = $row["id"];
}
echo json_encode($cache);
?>;
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
var categoryId = categoriesCache[categoryName];
});
</script>
<script>
$(document).on('click', '.dropdown-menu li a', function(e) {
e.preventDefault();
var categoryName = $(this).text();
// !! be careful here !! send web safe category name, `$(this).text();` or even better a numeric value.
$.get('runquery.php', {'category': encodeURIComponent(categoryName)}).done(function (data) {
// on success do something if needed
});
})
</script>
Put your PHP/SQL script in runquery.php
You can do this with Ajax
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
Php-script in a separate File like:
First you JavaScript file:
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
$.post("php-file.php",{cat_Name: categoryName});
});
then you php-file.php looks like:
<?php
$categoryname = $_POST['cat_Name'];
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = '?' ");
?>
if you want to use them again:
add to your PHP on the end:
$return = new array();
$return[0] = ;//your results in this array
echo json_encode($return);
then in your JavaScript should look like:
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
$.post("php-file.php",{cat_Name: categoryName}, function(data){
sccess_function(data);}, "json");
});
then add a function:
function succsess_function(data){
//do thing here
}
In my display page I have a script that updates a div from another php page.
How do I re-write the below script to:
Be a function I can call with updateadiv(divid,content) in my display page (in php) where content is a php variable. (the script will then not call the php page but take the input variable).
<!DOCTYPE html>
<html>
<body>
function updatediv(divId, content)
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
(function($)
{
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#content').hide();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
$('#content').show();
},
success: function() {
$('#loading').hide();
$('#content').show();
}
});
var $container = $("#content");
$container.load("http://192.168.1.90/json_output.php");
var refreshId = setInterval(function()
{
$container.load('http://192.168.1.90/json_output.php');
}, 9000);
});
})(jQuery);
</script>
<?php
function createarray() {
global $reindexed_devices_a ;
$feed_url = "http://192.168.1.90/JSON?request=getstatus&ref=all&location1=all&location2=all";
//$feed_url = "demoxml.xml";
$json = file_get_contents($feed_url);
$devices_a = json_decode($json, true);
//echo $devices_a[Devices][2][name] ;
//echo "<BR> ReIndexed:";
$reindexed_devices_a = array(Devices => array());
foreach ($devices_a[Devices] as $value) {
$reindexed_devices_a[Devices][$value[ref]] = $value;
}
//echo $reindexed_devices_a[Devices][59][name] ;
//need to do some conditional formatting before updating to DIV's
if ($reindexed_devices_a[Devices][59][name] == 'Coffee maker') {
$reindexed_devices_a[Devices][59][name] = "overwritten";
}
echo time();
//echo $reindexed_devices_a[Devices][59][name] ;
}
createarray();
$name59=$reindexed_devices_a[Devices][59][name];
//check if $name59 has changed - if yes update div
updatediv('59');
echo "This is a test <div id = 'name59'>.....</div>";
?>
</body>
</html>
function updateadiv(DivID , Url){
$('#loading').hide();
$('#' + DivID ).html('');
$.ajax({
url:url,
success:function(rData){
$('#' + DivID ).html(rData);
}
});
}
I am trying to send an array from javascript to PHP script using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function() {
var parms = [];
parms.push($(this).text());
});
</script>
<script>
function loadXMLDoc()
{
$.ajax({
type: "POST",
url: "update.php",
data: { value : $(parms).serializeArray() },
success: function(data)
{
console.log (data);
}
});
}
$("button").on('click',function(){ loadXMLDoc(); });
</script>
In my $.output function, I am using the parms [] array to store all the UI slider values which I am trying to pass on to the next PHP script page on a button click event as defined in loadXMLDoc() function. In my PHP page, I am accessing them as below.
<?php
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
// Do whatever you want with the $uid
?>
However, I am not able to view the data in my update.php script. Can someone please let me know what am doing wrong?
This is the link to my work so far.
serializeArray returns the json object ,maybe you could try json_decode in your php script,simply like:
$uid_arr = json_decode($uid,true);
print_r($uid_arr);
Just Use
data: $(parms).serializeArray()
I am passing an array from javascript to PHP using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<head>
<script>
var parms = [];
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function () {
parms.push($(this).text());
});
function loadXMLDoc(parms) {
$.ajax({
type: "POST",
url: "update.php",
data: {
value: $(parms).serializeArray()
},
success: function (data) {
alert(data);
}
});
}
$("button").on('click', function () {
loadXMLDoc(parms);
});
alert(parms);
</script>
</head>
On click of button, I am trying to call the PHP script to edit the display of my web page. However, the ajax call to the below PHP statement alerts only the "Am I printed" line.
<?php
$uid = $_POST['value'];
echo "Am I printed";
echo $uid;
// Do whatever you want with the $uid
?>
Why is the $uid value not returned to my javascript? Is there something am doing wrong?