javascript load php on div doesn't work with Firefox - javascript

I have several php pages that create dynamically links with javascript scripts which load different content in the same div. The function that creates the links is the following:
$variablephp = $_GET['id'];
$result = mysql_query( "SELECT `BASIC` FROM `roleflow_training` WHERE `ROLE_ID`=".$variablephp.""); //Once the text has been saved in the BBDD:
$result = mysql_result ($result, 0, "BASIC");
$result = preg_replace("/\n+/", "\n",$result);
$lineas = explode("\n", $result);
echo "<ul>\n";
foreach ($lineas as $bullet)
{
$test = preg_replace("/\n+/", "", $bullet);
$prueba = chop($test, "\n");
$prueba = chop($prueba, "\b");
$prueba = chop($prueba, "\br");
$prueba = "'".$prueba."'";
$link = mysql_query("SELECT * FROM `cursos_training` WHERE `COURSE_NAME`=".$prueba."");
$existe = mysql_num_rows($link);
if ($existe < 1)
{
echo "<li>".$test."</li>\n";
}
else
{
$fila = mysql_fetch_array($link);
$enlace = $fila['IDLINK'];
$direccion = "<a href=\"javascript:$('#floatFlowCursos').css('display','none');$('#contentFlow').load('curso1_info.php?id=".$enlace."')\">";
echo "<li>".$direccion.$bullet."</a>"."</li>\n";
}
}
echo "</ul>";
This sentence works perfectly with Chrome but not with Firefox or I Explorer, do you have any idea?
Thank you so much for your support!! Cheers!!

Related

How to display values in JS from a PHP array that was posted from jQuery

I have a button called rename that when pushed, executes in jQuery a rename.php file. Inside that php file the program selects data from a mysql, creates an array with that data, and processes an array in to json_encode($array);. How can I then get that json encoded array and echo it out into javascript?
I'm trying to echo the array out so that javascript displays my images src's.
This is my second line of ajax so I just wrote the javascript out as if it were php because I'm not sure of the commands or structure in js.
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
/*alert(result);*/
document.getElementById("images_to_rename").innerHTML = foreach(jArray as array_values)
{
"<img src=\""array_values['original_path']"/"array_values['media']"/>";
}
}
}
);
and my jQuery php file:
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if(empty($_GET['image_name']))
{
echo '<div class="refto" id="refto">image_name is empty</div>';
}
else
{
echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach($_GET['image_name'] as $rowid_rename)
{
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE ".$username." SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arri[] = $row;
}
foreach($arri as $rows) //put them into workable variables
{
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
?>
<script type="text/javascript">
var jArray= <?php echo json_encode($arri); ?>;
</script>
<?php
}
echo "something2";
?>
My PHP file is a jQuery url:"test4.php", type: "GET", and is not the main file. The main file is called main.php and the test4.php is something that's called in jQuery when the user clicks on rename.
Somebody suggested console log so here's what chrome says:
<div class="refto" id="refto">image_name is not empty</div>[{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}] <script type="text/javascript">
var jArray= [{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}];
</script>
something2
Your ajax php file isn't render in browser, then the variable jArray is undefined. With your case, let return php file to json and you can get it as variable in result.
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if (empty($_GET['image_name'])) {
//echo '<div class="refto" id="refto">image_name is empty</div>';
} else {
//echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach ($_GET['image_name'] as $rowid_rename) {
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE " . $username . " SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$arri[] = $row;
}
foreach ($arri as $rows) { //put them into workable variables
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
//stop render here
die();
}
?>
php file need return only json string. Then we'll get result as json variable in javascript.
And Js:
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
var jArray = JSON.parse(result);
/*alert(result);*/
var txt = "";
jArray.forEach(function(array_values){
txt += `<img src=\""array_values.original_path."/"array_values.media"/>`;
})
document.getElementById("images_to_rename").innerHTML = txt;
}
}
);

With one button I want to call a php function as well as a javascript function?

I have a file, where i use a button, called MP4 Quality, When i click on that button, it opens a pop-up and ask for another button to press, to download the video, There is javascript with first button, and when it clicks, open the pop-up and give the second button, from where PHP is used, now i want it to download on single click,
Following is the code for first button...
<button id="videoDownloadButton" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" onClick="downloadVideo();">MP4 Quality</button>
and when it click, the following javascript code will run
function downloadVideo() {
var videoID = player.getVideoData()['video_id']
document.getElementById("downloadFormatList").innerHTML="Please wait. Processing...";
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp3 = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("downloadFormatList").innerHTML=xmlhttp3.responseText;
}
}
//keyword = keyword.replace(/ /g, '%2B');
xmlhttp3.open("GET","TMB/download.php?videoid="+videoID,true);
xmlhttp3.send();
}
and after that PHP code will run, PHP code is this...
if(isset($_REQUEST['videoid'])) {
$my_id = $_REQUEST['videoid'];
if(strpos($my_id,"https://youtu.be/") !== false)
{
$my_id = str_replace("https://youtu.be/","",$my_id);
}
}
<?php
//$my_video_info = 'http://www.youtube.com/get_video_info?&video_id='. $my_id;
$my_video_info = 'http://www.youtube.com/get_video_info?&video_id=' . $my_id . '&asv=3&el=detailpage&hl=en_US'; //video details fix *1
$my_video_info = curlGet($my_video_info);
/* TODO: Check return from curl for status code */
$thumbnail_url = $title = $url_encoded_fmt_stream_map = $type = $url = '';
parse_str($my_video_info);
?>
<?php
$my_title = $title;
$cleanedtitle = clean($title);
if (isset($url_encoded_fmt_stream_map)) {
/* Now get the url_encoded_fmt_stream_map, and explode on comma */
$my_formats_array = explode(',', $url_encoded_fmt_stream_map);
if ($debug) {
echo '<pre>';
print_r($my_formats_array);
echo '</pre>';
}
} else {
echo '<p>No encoded format stream found.</p>';
echo '<p>Here is what we got from YouTube:</p>';
echo $my_video_info;
}
if (count($my_formats_array) == 0) {
echo '<p>No format stream map found - was the video id correct?</p>';
exit;
}
/* create an array of available download formats */
$avail_formats[] = '';
$i = 0;
$ipbits = $ip = $itag = $sig = $quality = '';
$expire = time();
foreach ($my_formats_array as $format) {
parse_str($format);
$avail_formats[$i]['itag'] = $itag;
$avail_formats[$i]['quality'] = $quality;
$type = explode(';', $type);
$avail_formats[$i]['type'] = $type[0];
$avail_formats[$i]['url'] = urldecode($url) . '&signature=' . $sig;
parse_str(urldecode($url));
$avail_formats[$i]['expires'] = date("G:i:s T", $expire);
$avail_formats[$i]['ipbits'] = $ipbits;
$avail_formats[$i]['ip'] = $ip;
$i++;
}
echo '<div class="format_list">';
echo '<br>';
echo '<table>';
/* now that we have the array, print the options */
for ($i = 0; $i < 1; $i++) {
if ($config['VideoLinkMode'] == 'direct' || $config['VideoLinkMode'] == 'both')
?> <tr><td><?php
echo $avail_formats[$i]['type'];
?></td>
<td><small>(<?php
echo $avail_formats[$i]['quality'];
?>)</small> </td>
<td><small><span class="size"><?php
echo formatBytes(get_size($avail_formats[$i]['url']));
?></span></small>
</td>
<td><a href="<?php
echo $avail_formats[$i]['url'];
?> '&title='<?php
echo $cleanedtitle;
?>'" class="downloadButton">Record Video</a></td>
</tr>
<?php
}
?>
after the click on first button, this button will appear,
Record Video
Now i want it on single click, how can i do...??
Try adding this in the bottom of your pop-up page:
<script>
window.location = '<?php echo $avail_formats[$i]['url']; ?>';
</script>
According to your php code, the "second button" term is not correct.
You might have a count of second buttons which have different quality.
This is why the php code and second click exist.
If you want to download your video immediately, replace your foreach loop in php code
foreach ($my_formats_array as $format) {
parse_str($format);
$avail_formats[$i]['itag'] = $itag;
$avail_formats[$i]['quality'] = $quality;
$type = explode(';', $type);
$avail_formats[$i]['type'] = $type[0];
$avail_formats[$i]['url'] = urldecode($url) . '&signature=' . $sig;
parse_str(urldecode($url));
$avail_formats[$i]['expires'] = date("G:i:s T", $expire);
$avail_formats[$i]['ipbits'] = $ipbits;
$avail_formats[$i]['ip'] = $ip;
$i++;
}
on the
if (isset($my_formats_array[0])) {
parse_str($my_formats_array[0]);
header("Location: " . urldecode($url) . '&signature=' . $sig);
die();
}
And get rid of other unnecessary things

Change the value of external Javascript with PHP in foreach loop

How can I change the value of a js variable in a PHP foreach loop?
The js needs to be external.
This is a piece of the index.php here I want to get the output $prozent in the javascript, I don't know how to get a PHP variable to execute a js every time in a loop, the js is a chart. I get the chart in the loop in the echo'<div class="chart-wrapper"> with a this chart js.
<?php
$sql = //SQL query
$res = mysql_query($sql);
$i = 0;
$survey = array();
while ($row = mysql_fetch_assoc($res)) {
$survey[$i]['label'] = $row['Label'];
$i++;
}
foreach ($survey as $survey) {
echo '<div class="col-md-4">';
echo '<div class="front face">';
echo "<h3> ".$survey['label']."<br>";
$sql = //SQL Query
$res = mysql_query($sql) ;
$sql = //SQL Query
$resSum = mysql_query($sql) ;
while ($row = mysql_fetch_array($resSum)) {
$survey['ausgabe'] = $row['sum(a.answer)'];
}
$anzahlreihen = mysql_num_rows($res);
if ($anzahlreihen > 0) {
$prozent = $anzahlreihen * $survey['ausgabe'];
//bunch of ifelse statements
//This is the variable i want to get in the js
echo (round( $prozent, 2));
echo '</font>';
}
}
echo '</div>';
echo '<div class="back face center">';
echo'<div class="chart-wrapper">
}
There are two ways PHP and Javascript can interact.
Use AJAX to request a PHP script which returns JSON or have PHP output the following example HTML;
<script type="text/javascript">
var variable = value;
</script>

How to properly load one ajax request after another

I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

Reload Script Accessed On Another Website

I'm trying to create a script that runs and updates real time(semi if needed) on another website.
The back bone of this is a php script which accesses a database on my server. From there it outputs some basic variable information.
So we're on the same page. This is the script itself.
Located on www.A.com-->
<?php
include "includes/db_conx.php";
// This block grabs the whole list for viewing
$sql = "SELECT * FROM pages ORDER BY id DESC";
$result = mysqli_query($db_conx,$sql);
$productCount = mysqli_num_rows($result);
if ($productCount > 0) {
$x=0;
while($row = mysqli_fetch_assoc($result)){
$id = $row["id"];
$url = $row["url"];
$status = $row["status"];
$headerCode = $row["headerCode"];
$bodyCode = $row["bodyCode"];
if($status == "Ready") {
$statClass = "greenBox";
}
if($status == "Live") {
$statClass = "yellowBox";
}
if ($status == "Hold")
$statClass = "blueBox";
$lastEdit = strftime("%b %d, %Y", strtotime($row["lastEdit"]));
$x++;
$bgChange = ($x%2 == 0)? '': 'blackRow';
$product_list .= "<div class='row noMargin $bgChange'><div class='boxMini idColDeveloper'>$id</div><div class='boxMini statusColDeveloper $statClass boldDiv twelveFont' style='margin:4px;'>$status</div><div class='boxMini urlColDeveloper'>$url</div><div class='boxMini' id='postDateDeveloper'>$lastEdit</div><div class='boxMini actionColDeveloper'><div style='float:left;'> <a href='bodyCodes_edit.php?pid=$id'>Edit</a></div><div style='float:left;margin-left:12px;'><a href='bodyCodes_creator.php?deleteid=$id'><img src='https://www..com/upload/images/delete-item.png' alt='delete' style='display:block;margin-left:auto;margin-right:auto;'/></a></div></div><div class='clear'></div></div>";
$list = $product_list;
}
}
echo ("document.getElementById('date-holder').innerHTML = '".addslashes($list)."';");
?>
On an entirely different website and server I'm using this code to display the information from my database at www.A.com:
Located on www.B.com-->
<script src="https://www..com/test/test.php"></script>
Is there any way to update this every second or less? So it's something of a real time output.

Categories