Putting a JavaScript variable in PHP array - javascript

I was making an image gallery with up and down buttons ,the array $imageids contains all image ids. I want to access these values with
JavaScript as follows,
PHP :
require"./connect.php";
$imgquery = mysql_query("SELECT * FROM press INNER JOIN subscriptions ON press.userid=subscriptions.to_u WHERE subscriptions.from_u='30' ORDER BY press.id DESC ");
$countrow = mysql_num_rows($imgquery);
$imageids = array();
while($fimgq = mysql_fetch_assoc($imgq)) {
$imgid = $fimgq['id'];
array_push($imageids,$imgid);
}
JavaScript:
$(document).ready(function() {
var i = -1;
var cr = <?php echo $countrow ?>;
$('#down').click(function() {
if (i < cr-1) {
i = i + 1;
var ard = <?php echo $imageids[i]?>;
alert(ard);
}
});
$('#up').click(function() {
if(i>0) {
i = i - 1;
var aru = <?php echo $imageids[i]?>;
alert(aru);
}
});
});
I want to get $imageids elements by putting a javascript variable i inside $imageids[] array , like
var ard = <?php echo $imageids[i]?>;
alert(ard); // Which doesn't work

As #chris85 and #Khalos pointed out in comments, the PHP variables are all dead once the JavaScript runs, so you need to output all the ID:s into an JavaScript array. It would looke something like this:
$(document).ready(function(){
var i=-1;
var cr= <?php echo $countrow ?>;
//Save all the ID:s to a JS variable so they can be used later.
var imageids = [<?php echo implode(',', $imageids); ?>];
$('#down').click(function(){
if(i<cr-1) {
i=i+1;
alert(imageids[i]); //This uses the JS variable imageids, not the dead PHP one.
}
});
$('#up').click(function(){
if(i>0) {
i=i-1;
alert(imageids[i]); //Same as above.
}
});
});

Related

How to make script tag work inside a div?

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();
}
});

How to insert multiple values to single key in javascript

I have an object array var codropsEvents={[date1]:['event1'],[date2]:['event2'};
I want to insert multiple values to event1 i.e {[date1]:['event1','event2'],..}
I use the following code
<?php
$da=[];
$qry="select * from events";
$ex=mysqli_query($con,$qry);
while($row=mysqli_fetch_assoc($ex))
{
$timestamp = strtotime($row['date']);
$date= date('m-d-Y', $timestamp);
$event=$row['event'];
$da[]=$date;
$eve[]=$event;
}
?>
<script type="text/javascript">
var a=<?php echo(json_encode($da)); ?>;
var ev= <?php echo(json_encode($eve)); ?>;
var codropsEvents ={};
for(var i=0;i<a.length;i++)
{
codropsEvents[a[i]] = '<span>'+[ev[i]]+'</span>';
}
</script>
But using this code I got something like this,
var codropsEvents={[date1]:[event1],[date1]:[event2]}
But I need all events with same date in a single key is {[date1]:['event1','event2',..],[date2]:[''event3','event4'..],..};
Please anyone can help me
You need to check whether the key exists in the object, if not initialize it with empty array. Then push elements into the array.
<script type="text/javascript">
var a=<?php echo(json_encode($da)); ?>;
var ev= <?php echo(json_encode($eve)); ?>;
var codropsEvents ={};
for(var i=0;i<a.length;i++)
{
if (!codropsEvents[a[i]]) {
codropsEvents[a[i]] = [];
}
codropsEvents[a[i]].push('<span>'+[ev[i]]+'</span>');
}
</script>

PHP MySQL value pass to JavaScript

hei,
$i=0;
while($row = $result->fetch_assoc()) {
echo "
<tr><td>".$row["Number"]."</td><td>".$row["MusikName"]." ".$row["MusikURL"]."</td></tr>";
this part works...it give me -> 1 test1 url1.de 2 test2 url2.de ...
So what I want is to pass the URL to a JavaScript Array...by doing in phpscript
$urlarray[]=$row["MusikURL"];
echo $urlarray[$i]; // gives me url1.de url2.de url3.de
i++; // to fill $urlarray[1] [2] [...] with urls
How do I pass the urls to a JavaScript Array so that I can access to those by
javascriptarrayurl[1] javascriptarrayurl[2] (result should be a clear url) ... I got troubles with JSON :c
thanks in advance !!
You can use jQuery and have something like
<?php
$returnArray = array();
while ($row = $result->fetch_assoc()) {
array_push($returnArray, $row);
}
$jsonArray = json_encode($returnArray);
?>
<script>
$(document).ready(function () {
var objArray = $.parseJSON("<?php echo $jsonArray; ?>");
for (var i = 0; i < objArray.length; i++) {
var row = objArray[i];
console.log(row);
// Now here you have access to row.Number row.MusikURL
}
});
You can use json_encode() to convert a PHP variable to its Javascript literal notation.
<script>
var urlarray = <?php echo json_encode($urlarray); ?>;
</script>

Check inArray from a php array

PHP:
$ports = $Db->query('SELECT port FROM servers');
Javascript:
$("#port").on('keyup', function(){
var port = $("#port").val();
var portlist = <?php print(json_encode($ports)); ?>;
if(jQuery.inArray(port, portlist[port])!==-1)
{
$("#result").removeClass("label-success");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-danger");
$("#result").html("Port belegt!");
}
else
{
$("#result").removeClass("label-danger");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-success");
$("#result").html("Port Frei!");
}
})
Why is this not working?
The array contains 1234 and 7777.
So if I type 7777 into the html input field (#port) it should do the first action (if true)
But it always goes into the else action.
you need to cast integers in array to string by quoting and remove [port]
here is a working example of your code
http://jsfiddle.net/4X68y/
var portlist = ["1234","777"];
if(jQuery.inArray(port, portlist)!==-1)
jQuery inArray accepts array as second parameter - not specific key.
Try this:
$("#port").on('keyup', function(){
var port = $(this).val();
var portlist = <?php print(json_encode($ports)); ?>;
if(jQuery.inArray(port, portlist)!==-1)
{
$("#result").removeClass("label-success");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-danger");
$("#result").html("Port belegt!");
}
else
{
$("#result").removeClass("label-danger");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-success");
$("#result").html("Port Frei!");
}
})
--EDIT--
The following works for me (if the portlist is array not json object. If it isnt maybe it's a good idea to just loop the results and create the array old fashioned way like below)
PHP:
<?php
$q = $db->query("SELECT port FROM ports");
$ports = array();
while($$row = $result->fetch_assoc()){
$ports[] = $row['port'];
}
?>
JS CODE:
$("#port").on('keyup', function(){
var port = parseInt($(this).val());
var portlist = <?php print(json_encode($ports)); ?>;
if(jQuery.inArray(port, portlist)===-1)
{
$("#result").removeClass("label-success");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-danger");
$("#result").html("Port belegt!");
}
else
{
$("#result").removeClass("label-danger");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-success");
$("#result").html("Port Frei!");
}
})

adding php array values to javascript array

I have a php array and I want to add its value to a javascript array. For example I am doing it something like this.
$k_data = json_encode($k)
Thus
k_data = [2,3,4,8,9]
Now in javascript I am doing like the following
var s4 = [[]];
for(var i = 0; i<5; i++)
{
s4.push([i,$k_data[i]]);
}
plot5.series[0].data = s4;
where plot5 is jqplot graph. But this is not working, I am getting blank graph while the following thing is working
for(var i = 0; i<5; i++)
{
s4.push([i,Math.sin(i)]);
}
Where I am making mistake?
If you want to deal with the php array only, you can do this-
First, implode the array to make a comma-separated string, say $str. Just like-
<?php
$str = implode(",", $array);
?>
Then, use split to convert the php string to the javascript array. Just like-
<script>
var str = <?php echo $str; ?>;
var array = str.split(',');
</script>
OR, json_encode() can help you directly-
<script>
<?php
$js_array = json_encode($php_array);
echo "var js_array = ". $js_array . ";\n";
?>
</script>
Well you can do a for loop and echo the Javascript commands to fill the Javascript Array
<script>
var s4 = [[]];
<?php
$k_data = json_encode($k)
$i = 0;
foreach($k_data as $v) {
echo 's4.push([' , $i , ',Math.sin(' , $v , ')]);';
++$i;
}
?>
plot5.series[0].data = s4;
</script>
It seems that you are refering to a php variable in you javascript. Keep in mind that PHP is executed serverside, whereas javascript is executed by the browser. Therefore, you need to pass the PHP variable to your javascript. Assuming that your javascript and PHP are in one .php file, replacing above javascript with the following should work:
<?php $k_data_js = implode("','", $k_data); ?>
var k_data = <?php echo "['" . $k_data_js . "']"; ?>;
var s4 = [[]];
for(var i = 0; i<k_data.length; i++)
{
s4.push([i,k_data[i]]);
}
plot5.series[0].data = s4;
The variable is passed to javascript in the second line. From then on you can refer to k_data in your script.

Categories

Resources