I have a page in wordpress, that uses an jquery and ajax to get information from an external api. The form sends the array generated in javascript back to the same page with another variable that the php in the page uses to determine which page to display. Outside of wordpress, the code works fine. Inside Wordpress the first portion runs, but then instead of loading the same page again it goes to a search page and says nothing found.
The url on the output is:
http://kltools.net/?s=&post_type%5B%5D=portfolio&post_type%5B%5D=post&post_type%5B%5D=page
Which seems odd considering I'm using post not get.
The javascript that generates the array and submits the form:
function submitchans(){
for (var i=0;i<chans.length;i++)
{ var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'chans[]';
newHidInp.value = chans[i];
form.appendChild(newHidInp);
}
}
function livearray(input){
if (input != null) {
chans.push(input);
}
if (Y === cSize){
submitchans();
document.forms[0].submit();
}
}
Previously the array was outArray[] instead of chans[], I changed it thinking that may be triggering the result, but no luck.
This is the PHP portion of the code:
<?php
$page_to_load = $_POST[view];
switch($page_to_load) {
case '':
echo "<script src=\"../scripts/jquery-3.2.0.min.js\"></script>";
echo "<script type=\"application/javascript\" src=\"../scripts/raid.js\"></script>";
echo "<font size=\"+3\" color=\"#FFFFFF\">Who should I host?<br>Please wait while channel is selected<br></font>";
echo "<font size=\"+2\">";
echo "<br><br>";
echo "<img src=\"../_images/ajax_loader_blue_350.gif\">";
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$chanarray[] = null;
$offline = 0;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `TwitchNames` FROM TK_Members WHERE Validated='1' AND RaidMe='1'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($chanarray, $row['TwitchNames']);
}
} else {
echo "0 results";
}
array_splice($chanarray, 0, 1);
$conn->close();
echo "<script type=\"application/javascript\">";
echo "var channels = ". json_encode($chanarray);
echo "</script>";
echo "</font>";
echo "<form id=\"form\" method=\"post\">";
echo "<input type=\"hidden\" name=\"view\" value=\"page2\">";
echo "</form>";
break;
case 'page2':
echo "<font size=\"+3\" color=\"#FFFFFF\">Who should I host?<br>";
echo "Your channel to host is:<br></font>";
echo "<font size=\"+2\">";
echo "<br><br>";
$chans[] = null;
$test = $_POST['chans'];
foreach ($test as $chan) {
$temparray = array(rand(),$chan);
array_push($chans, $temparray);
}
array_splice($chans,0,1);
sort($chans);
echo "".$chans[0][1]."";
echo "<br><br><br>";
echo "See All Live Channels";
echo "</font>";
break;
}
?>
After working with what blokeish has suggested I've modified the javascript file working out where the problem is.
The new javascript file is:
// JavaScript Document
var chans = ["test1","test2","test3"];
function submitchans(){
for (var i=0;i<chans.length;i++)
{ var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'chans[]';
newHidInp.value = chans[i];
document.getElementById('chansform').appendChild(newHidInp);
}
}
jQuery(function ($) {
submitchans();
document.getElementById('chansform').submit();
});
Using only the javascript clicking submit, it passes to the next page. When adding in the array pass is when it fails. This is the page log that is returning during the execution. !!--CORRECTION--!! there was a typo in the code, after correcting ID to Id the code is working as intended.
document.forms[0].submit() is likely submitting the wp search form as that could be the first form in the DOM. I see "http://kltools.net/?s=" in the URL where "s" is the search term.
Using document.getElementById('idOfForm').submit() should get you around that problem if there are multiple forms in a page and you cant be sure of its index.
Related
I am calling a php file, into my HTML document using AJAX, and it is working too. The problem is that, there are few script tags in that PHP files, which works just fine if the PHP files is viewed individually. But when I call it using AJAX, those scripts are not functioning.
I am attaching my PHP code, and the screenshots below.
trial.php
<script>
document.getElementById("response1").onload = function() {
document.body.style.backgroundColor = "#ffa31a";
}
</script>
<h1 class="restitle"> Responses</h1>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portfolio";
$conn = mysqli_connect( $servername, $username, $password, $dbname );
if ( !$conn ) {
die( "Connection failed: " . mysqli_connect_error() );
}
$sql = "SELECT NAME, EMAIL, MESSAGE, TIME FROM Feedback ORDER BY TIME";
$result=$conn->query( $sql );
if ( $result == TRUE ) {
$i=0;
?>
<script>
var n = 1;
</script>
<?php
while ($row = $result -> fetch_row()) {
$i = $i+1;
echo "<div class='response' id='response$i'><h1 class='responsetitle' id='responsetitle$i'><i class='fa fa-user' aria-hidden='true'></i> " . $row[0]. " <span class='responseemail' id='responseemail$i'> (". $row[1] .")</h1><hr class='responseline'><p class='responsetxt' id='responsetxt$i'>\"" . $row[2] . "\"</p><br /><div class='responsetimecontain'><span class='responsetime'>- " . $row[3] . "</span></div></div>";
echo "<div id='valuepipe$i' style='display:none;'>" . $i . "</div>";
?>
<script>
var i = document.getElementById("valuepipe" + n).textContent;
if (i % 2 == 0) {
document.getElementById("response" + n).style.backgroundColor = "#ffa31a";
document.getElementById("responseemail" + n).style.color = "#f2f2f2";
document.getElementById("responseemail" + n).style.opacity = "0.6";
document.getElementById("responsetitle" + n).childNodes[0].style.color = "#f2f2f2";
document.getElementById("responsetxt" + n).style.color = "#f2f2f2";
}
n++;
</script>
<?php
}
$result -> free_result();
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close( $conn );
?>
When this file is viewed individually:
But when I call it using AJAX:
<script>
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("main2").innerHTML = this.responseText;
}
xhttp.open("GET", "trial.php");
xhttp.send();
</script>
I get the following view :
Somehow all the script tags are being ignored or something. Need a solution. Any help would be appreciated.
Note: The other styles are implemented in my CSS file, so they are visible. Only the Scripts are not working
From the MDN reference
HTML5 specifies that a <script> tag inserted with innerHTML should not execute.
You'll need to separate the scripts from the HTML content and either include them as part of the code that loads the content, or place them in their own script file that is loaded separately.
I new in programming. Currently, I develop a system that registration part. The registration part is successfully saved to the database. What I want to know is how to popup an alert dialog with one button e.g "Ok" after registration was successful and redirect to another page, such as home page. Now I only echo "successfully saved"
Below is my current code
<?php
require "DbConnect.php";
$name = $_POST['name'];
$badgeid = $_POST['badgeid'];
$position = $_POST['position'];
$department = $_POST['department'];
$factory = $_POST['factory'];
$reviewer = $_POST['reviewer'];
$title = $_POST['title'];
$year = $_POST['year'];
$month = $_POST['month'];
$suggestionwill = $_POST['suggestionwill'];
$present = $_POST['present'];
$details = $_POST['details'];
$benefit = $_POST['benefit'];
$sql_query = "INSERT INTO topsuggest (name,badgeid,position,department,factory,
reviewer,title,year,month,suggestionwill,present,details,benefit) VALUES('$name','$badgeid','$position','$department','$factory','$reviewer','$title','$year','$month','$suggestionwill','$present','$details','$benefit')";
if(mysqli_query($conn,$sql_query))
{
echo "<p id='msg'></p>";
}
else
{
echo "Error!! Not Saved".mysqli_error($con);
}
?>
Just use php header and use javascript to alert a message .
if(mysqli_query($conn,$sql_query))
{
echo "<script>alert('Successfuly Saved');</script>";
header('Location: PATH TO BE REDIRECTED');
}
For a example
if(mysqli_query($conn,$sql_query))
{
echo "<script>alert('Successfuly Saved');</script>";
header('Location: ../Insert/Index.php');
}
Please note that space between Location: is compulsory
After inserting data you can simply redirect to your interested page with a success message like:
header("location:page_of_interest.php?msg=Record Inserted");
and on page_of_interest.php you can simply check for msg and show if it is set like:
if(isset($_GET['msg'])){
echo $_GET['msg'];
}
Recently I have been assigned a group project for a college class and I will need to query a customers name from a database and then print out the rest of the row in form fields. I have the select menu working correctly and it will print to the form field. However, the problem occurring is the query results will only show the last row in the MYSQL table I selected. Any help here would be greatly appreciated. I have been spinning my wheels for a few days on this issue. I am only a beginner coder, so it might be a little messy.
Thanks,
Connection.PHP File
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "medley";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
My Query Page
<?php
require 'connection.php';
$conn = Connect();
$sql = "SELECT * FROM cust_info";
$result = $conn->query($sql);
echo "<select id='firstName' name='firstname' onchange=populatesecondbox()>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['F_Name'] . "', '" . $row['L_Name'] . "'> " . $row['F_Name'] . " " . $row['L_Name'] . "</option>";
$pphone = $row['P_Phone'];
}
echo "</select>";
?>
<input id="secondinputbox" type="text" />
<script type="text/javascript">
function populatesecondbox(val) {
var dropdown = document.getElementById("firstName");
var pphone = document.getElementById("secondinputbox");
var secondfname = document.getElementById("thirdinputbox");
var str = "<?php echo $pphone ?>";
var sfname = "<?php echo $sfname ?>";
pphone.value = str;
secondfname.value = sfname;
}
</script>
Instead of using
$row = mysqli_fetch_array($result)
on line 10, use
$row = $result->fetch_assoc()
or
$row = $result->fetch_array()
The difference between fetch_assoc and fetch_array is that fetch_array contains both numeric indices and named indices. For example echo $row[0] will output as same as echo $row['id']. Whereas, fetch_assoc only contains named indices.
Based on the provided loop statement
$pphone = $row['P_Phone'];
$pphone is getting assigned to the last row on termination of the loop because each iteration is overriding $pphone with the current row until at which point in the loop $pphone gets the last value.
Instead of using
$pphone = $row['P_Phone'];
Try the following in the loop.
$pphone[] = $row['P_Phone'];
Your concatenated phones should be provided after the loop.
$pphones = "['".join("','" , $pphone)."']";
In your js script tag just get $pphones as a string;
var pphones = <?php echo $pphones; ?>;
ddl = document.getElementById('firstname');
pphone.value = pphones[ddl.selectedIndex];
So I have a user page in which I include several tables, one of which uses a pagination script that is handled by javascript (so that I dont have to refresh the page when looking through the pages) now I'm trying to include this on my user.php page but it doesnt seem to work, any help appreciated
User.php page
<?php require 'session.php';
require 'header.php';
require 'includes/database.php';
$userid = $_GET['id'];
$con = mysql_connect($servername, $username, $password);
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname);
//CLIENT INFO TABLE
include 'user/clientinfo.php';
echo "<br>";
// XLRSTATS TABLE
include 'user/xlrstatsinfo.php';
echo "<br>";
//ALIAS TABLE
include 'user/aliases.php';
//IP TABLE
include 'user/ipaliases.php';
//PENALTY TABLE
include 'user/penalties.php';
//PENALTY TABLE
include 'user/userchatlog.php';
?>
userchatlog.php page
<?php
require '../session.php';
?>
<div id='retrieved-data'>
<!--
this is where data will be shown
-->
<img src="../images/ajax-loader.gif" />
</div>
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<script type = "text/javascript" src = "../includes/js/jquery-1.7.1.min.js"></script>
<script type = "text/javascript">
$(function() {
//call the function onload
getdata( 1 );
});
function getdata( pageno ){
var targetURL = '../includes/pagination/userchatlog/search_results.php?page=' + pageno;
$('#retrieved-data').html('<p><img src="../images/ajax-loader.gif" /></p>');
$('#retrieved-data').load( targetURL ).hide().fadeIn('slow');
}
</script>
and my search_results.php
<!-- include style -->
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<?php
//open database
include '../../database.php';
//include our awesome pagination
//class (library)
include 'ps_pagination.php';
//connect to mysql server
$mysqli = new mysqli($servername, $username, $password, $dbname);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
function _ago($tm,$rcs = 0) {
$cur_tm = time(); $dif = $cur_tm-$tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
$no = floor($no); if($no <> 1) $pds[$v] .='s ago'; $x=sprintf("%d %s ",$no,$pds[$v]);
if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
return $x;
}
//query all data anyway you want
$sql = "SELECT * FROM chatlog WHERE msg NOT LIKE '%RADIO%' ORDER BY id DESC";
//now, where gonna use our pagination class
//this is a significant part of our pagination
//i will explain the PS_Pagination parameters
//$conn is a variable from our config_open_db.php
//$sql is our sql statement above
//3 is the number of records retrieved per page
//4 is the number of page numbers rendered below
//null - i used null since in dont have any other
//parameters to pass (i.e. param1=valu1¶m2=value2)
//you can use this if you're gonna use this class for search
//results since you will have to pass search keywords
$pager = new PS_Pagination( $mysqli, $sql, 45, 4, null );
//our pagination class will render new
//recordset (search results now are limited
//for pagination)
$rs = $pager->paginate();
//get retrieved rows to check if
//there are retrieved data
$num = $rs->num_rows;
if($num >= 1 ){
//creating our table header
echo "<table id='my-tbl'>";
echo "<tr>";
echo "<th>Time</th>";
echo "<th>Name</th>";
echo "<th>Message</th>";
echo "</tr>";
//looping through the records retrieved
while( $row = $rs->fetch_assoc() ){
$msg=$row['msg'];
$team=$row['client_team'];
$team = str_replace("42","<img src=images/green.png>",$team);
$team = str_replace("3","<img src=images/red.png>",$team);
$team = str_replace("2","<img src=images/blue.png>",$team);
$team = str_replace("1","<img src=images/grey.png>",$team);
$msg = str_replace("^0","</font><font color=black>",$msg);
$msg = str_replace("^1","</font><font color=red>",$msg);
$msg = str_replace("^2","</font><font color=lime>",$msg);
$msg = str_replace("^3","</font><font color=yellow>",$msg);
$msg = str_replace("^4","</font><font color=blue>",$msg);
$msg = str_replace("^5","</font><font color=aqua>",$msg);
$msg = str_replace("^6","</font><font color=#FF00FF>",$msg);
$msg = str_replace("^7","</font><font color=white>",$msg);
$msg = str_replace("^8","</font><font color=white>",$msg);
$msg = str_replace("^9","</font><font color=gray>",$msg);
$name=$row['client_name'];
$name=htmlentities($name);
$time=$row['msg_time'];
echo "<tr class='data-tr' align='center'>";
echo "<td align=center>";
echo _ago($time);
echo "</td>";
echo "<td align=center>";
echo $team;
echo "<a href='http://144.76.158.173/ech/user.php?id=".$row["client_id"]."' > $name </a></td>";
echo "<td align=left> $msg </td>";
echo "</tr>";
}
echo "</table>";
}else{
//if no records found
echo "No records found!";
}
//page-nav class to control
//the appearance of our page
//number navigation
echo "<div class='page-nav' align='center'>";
//display our page number navigation
echo $pager->renderFullNav();
echo "</div>";
?>
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