My href links not working when contained within ajax call - php

I am having a bizarre problem that I cannot figure out. It is quite possible that I just do not know something fundamental which is the cause. I really have no idea. Anyway; I have a function on a page that uses mysql to look up divisions; then it has buttons for each division; and when you click each button; a team list for each division appears within a div container. the buttons send a "div_id" value to the container. The container then uses ajax to go back to mysql and then look up the teams for that division and output information on them. This is all working. But when I try and have the php file which is called from ajax list a simple href link for each team; the links do not appear. It really seems that I cannot have href links present in the php file that is called by ajax.
I do not think I need to post all of the code for all the buttons and all that, if so please let me know; here is the script that does the ajax call on the php file:
<script>
function MyRadFunction(DivId) {
var answer = DivId;
$.ajax({
cache: false,
type: 'GET',
url: 'http://jba.gtdsites.com/gscript3_links.php',
data: 'answer=' + answer,
dataType: 'html',
success: function(response) {
$('#ajax_content').html(response);
}
});
}
</script>
and here is the php file that is called:
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
$div_id=$answer;
/* Connect to a mysql database using driver invocation */
$dsn = 'mysql:dbname=gtdtables;host=gtdtables.db.1567753.hostedresource.com';
$user = 'username';
$password = 'password';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT * FROM teams WHERE div_id=$div_id";
foreach ($dbh->query($sql) as $resultsg1)
{
$team_id=$resultsg1[team_id];
$team_name=$resultsg1[team_name];
echo "<a href='/team-schedules/?gc_start=2&team_id=<?php echo $team_id; ?>'><?php echo $team_name; ?></a><br/>";
echo $team_name . "<br/>";
echo $team_id . "<br/>";
?>
Teams Page not link
Final Exam 1
<?php echo $team_name; ?><br/>
<?php
}
}
?>
I echoes the team name and team id just fine; and where i just have it print text that works as well; but all of the html hyperlink stuff just does not appear; I tried a few different ways. Can anyone tell me why this is happening?

Your error is kinda funny, but here it is, upon examining the site, on the network tab the markup built from PHP is rendered correctly. But the thing is:
The CSS is the problem:
a { color: #fff; }
Your text color on the links are white. Therefore its not seen, but its there, just change it accordingly.
a { color: #000; } /** or which color you want **/
And in your PHP, properly concatenate the values:
echo "<a href='/team-schedules/?gc_start=2&team_id=".$team_id."'>".$team_name."</a><br/>";
Important note: Don't just directly use variables inside your statements, use prepared statements to produce safer queries. Here is a tutorial for that.

Related

Not able to call the php function using jQuery:ajax

I am new to php and trying to implement a small webpage part of a school project. reportBuffering method in video.js file should call bufferingEventLogger method in server.php using Jquery ajax and store the passed values in Database. I am not able to trigger the bufferingEventLogger function. Here's the code for video.js
var video;
$(document).ready(function(){
var timeBuffered = 0;
var timer;
video = $('#main-video')[0];
video.play();
$(video).on("play",function(){
if(timer!=null)
clearInterval(incrementBufferedTime);
});
$(video).on("waiting",function(){
timer = setInterval(function(){
incrementBufferedTime
},1000);
});
function incrementBufferedTime(){
timeBuffered++;
console.log("Buffered time"+timeBuffered);
if(timeBuffered > 5){
reportBuffering()
}
}
function reportBuffering(){
$.ajax({
method: "POST",
url: "server.php",
data:{functionId:'bufferingEventLogger',val0:1,val1:'2016-04-18 16:37:01',val2:'2016-04-18 16:37:02'},
success:function (response) {
console.log(response)
}
});
}
reportBuffering();
});
Below code is for server.php
$id=$_POST['val0'];
$bufferStartTime=$_POST['val1'];
$bufferEndTime=$_POST['val2'];
//bufferingEventLogger($id,$bufferStartTime,$bufferEndTime);
function bufferingEventLogger($id,$bufferStartTime,$bufferEndTime){
$conn = mysqli_connect("localhost", "root", "", "metrics");
$sql = "INSERT INTO buffer_time(id,buffer_start,buffer_end) VALUES $id,'$bufferStartTime','$bufferEndTime')";
echo 'entered';
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($link);
I have gone through similar questions, but couldn't get it to work. Thanks
The only line that calls bufferingEventLogger is commented out.
Do you want to only call this function? If so, just uncomment the line.
If you want to add more functions, you might need to use something like a switch statement.
#beating_around_abush You are almost there! What you are doing now is passing the function name from the client to the server (as part of the AJAX call). However, on the server side the data is received as a string. What you need to do on the server is take that string value and convert it to a callable definition (in this case a function call). Conversely, in the PHP file just before mysqli_close($link); add a call to bufferingEventLogger() specifically. It does mean you have to refactor the function definition but that is a quick change.

Can't connect to my MySQL database using PHP mysqli_connect()

Background: I am attempting to run some AJAX on keyup in a search box that will go to the database for a lookup, then return the results without refreshing the page.
The Problem: I'm not confident that it's actually connecting to my database. I've tested the connection using THIS METHOD, and it says that it's successful for the credentials I'm using. However, I can change the host from locahost to www.MYDOMAINNAME.com OR the server name from my cPanel, and it still says it's a successful connection. If it's successful, then why isn't it running my SQL?
The Question: Is there something wrong with my code below, and if not, is there a better way for me to test what's happening?
Notes: The output in my console is "Error [object Object]". It's hitting search.php successfully, so I don't think it's a file path issue. I also ran the PHP on page load instead of doing it through AJAX and everything seemed to work just fine. I was able to get some results back when I hard-coded a value for $query.
File Structure:
(ROOT FOLDER)
index.php (where the form is)
(PHP FOLDER)
search.php
(JS FOLDER)
search.js
HTML:
<form action="php/search.php" method="post">
<input type="search" class="main-search" name="query" />
<div class="btn btn-lg btn-primary">Search</div></form>
</form>
jQuery:
$(function() {
$(".main-search").keyup(function() {
search($(this).val());
});
});
function search(query) {
$.ajax({
url:"./php/search.php",
type:"POST",
dataType:"json",
data: { query:query },
success: function(data) {
$(".result").html(data);
},
error: function(data) {
$(".result").html(data);
}
});
}
PHP:
<?php
$query = $_POST["query"];
$link = mysqli_connect('localhost', 'USER', 'PASS') or die ('Error connecting to mysql: ' . mysqli_error($link));
mysqli_select_db($link, 'DB_NAME');
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT actual FROM icons WHERE synonym = '$query'")) {
$row = mysqli_fetch_array($result);
echo $row["actual"];
mysqli_free_result($result);
}
else {
echo "No results found.";
}
mysqli_close($con);
?>
Try changing the AJAX call data paramenter to this
data: { 'query':query }
I think this should work
Just navigate and run the php code directly instead of relying on an AJAX call to test. If there is a connection error then it should be displayed in your echo statement in the browser.
Make sure you have php error reporting running.

Javascript function with PHP throwing a "Illegally Formed XML Syntax" error

I'm trying to learn some javascript and i'm having trouble figuring out why my code is incorrect (i'm sure i'm doing something wrong lol), but anyways I am trying to create a login page so that when the form is submitted javascript will call a function that checks if the login is in a mysql database and then checks the validity of the password for the user if they exist. however I am getting an error (Illegally Formed XML Syntax) i cannot resolve. I'm really confused, mostly because netbeans is saying it is a xml syntax error and i'm not using xml. here is the code in question:
function validateLogin(login){
login.addEventListener("input", function() {
$value = login.value;
if (<?php
//connect to mysql
mysql_connect(host, user, pass) or die(mysql_error());
echo("<script type='text/javascript'>");
echo("alert('MYSQL Connected.');");
echo("</script>");
//select db
mysql_select_db() or die(mysql_error());
echo("<script type='text/javascript'>");
echo("alert('MYSQL Database Selected.');");
echo("</script>");
//query
$result = mysql_query("SELECT * FROM logins") or die(mysql_error());
//check results against given login
while($row = mysql_fetch_array($result)){
if($row[login] == $value){
echo("true");
exit(0);
}
}
echo("false");
exit(0);
?>) {
login.setCustomValidity("Invalid Login. Please Click 'Register' Below.")
} else {
login.setCustomValidity("")
}
});
}
the code is in an external js file and the error throws on the last line. Also from reading i understand best practices is to not mix js and php so how would i got about separating them but maintaining the functionality i need?
thanks!
You can't mix PHP and JavaScript in this way as all of your PHP has already executed on the server before any of your JavaScript executes on the client.
The error is because the client is receiving and failing to execute this as JavaScript:
function validateLogin(login){
login.addEventListener("input", function() {
$value = login.value;
if (<script type='text/javascript'>alert('MYSQL Connected.');</script>...
// etc.
To interact with PHP from the client, you'll have to make another HTTP request -- either by <a> click, <form> submit, or Ajax request (using jQuery.post for brevity; see Using XMLHttpRequest for further details):
function validateLogin(login){
login.addEventListener("input", function() {
$.post('/validateLogin.php', { login: login }, function (result) {
if (result === "true") {
login.setCustomValidity("Invalid Login. Please Click 'Register' Below.")
} else {
login.setCustomValidity("")
}
});
});
}
Adjust the URL, /validateLogin.php, as needed; but create a PHP file for this URL similar to:
<?php
$value = $_POST['login'];
mysql_connect(host, user, pass) or die(mysql_error());
mysql_select_db() or die(mysql_error());
$result = mysql_query("SELECT * FROM logins") or die(mysql_error());
while($row = mysql_fetch_array($result)){
if($row[login] == $value){
echo("true");
exit(0);
}
}
echo("false");
exit(0);
?>
What is wrong? You simply break your JavaScript by inserting <script> parts to your if condition. So you get if (<script type='text/javascript'>alert('MYSQL Connected.');</script>... and so on... Next thing: you're trying to match $value, which is JavaScript variable, with $row[login] in PHP loop - you don't have $value there! These are separated codes. It's all wrong.
Jonathan Lonowski explained it very good how you should do this.

How to add ajax to wordpress theme

I've got a problem that I'm stuck on for days now...
I'm trying to use a simple ajaxPOST function to send data to a MySQL database (not WP database).
This code is located within "single-post.php" in the theme, because it must be checked before every post.
$.ajax({ url: 'library/functions/admin_checkuser.php',
data: {action: userID},
type: 'post',
success: function(output) {
alert(output);
}
});
I'm simply sending a variable to a "admin_checkuser.php" script which in turn calls another script that take actions on the database.
This is the code for "admin_checkuser":
$userid = $_POST['action'];
echo $userid;//for testing
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
echo $bb;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
But I don't think the calls go through to the script.
These scripts where tested outside of WordPress and did work, so it must be something in WordPress that blocking the ajax call.
BTW, I tried placing the "admin_checkuser.php" in many diffrent folders but nothing worked.
Thanks in advance.
You're much better off using the inbuilt Wordpress AJAX request.
So in your themes functions.php file, add your function to be called, for example:
function checkUser() {
$userid = $_POST['user']; //validation also :)
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
echo $bb;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
} else {
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
}
After that, you add your hook with connects to the inbuilt AJAX System
add_action('wp_ajax_check_user', 'checkUser');
add_action('wp_ajax_nopriv_check_user', 'checkUser');
wp_ajax_nopriv_%s allows it to be called from the front end.
And then, in your javascript file, you just fire off your ajax request.
$.post(ajaxurl, { action: 'check_user', user: userId }, function(output) {
alert(output);
});
If ajaxurl is undefined, you will need to create it in your template file, something like this should work, but there are other ways.
add_action('wp_head','ajaxurl');
function ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
Backend of wordpress does the rest.
It takes the action passed in the AJAX request, looks for the corresponding `wp_ajax(_nopriv)_%s hook and then calls the function that is assigned to the hook.
It will also pass in either the $_POST or $_GET depending on the type of AJAX request.
You can read a little more about using AJAX inside of Wordpress.
You should check your url for your ajax call.
Maybe use the full url instead of the relative one.
It could be because of the location of your theme makes the url incorrect. I'm assuming your ajax code is in your theme folder.
There are some wordpress functions that get the theme directory.
For example if you at this page http://yourwebpage/test/ then the ajax call will go here http://yourwebpage/test/library/functions/admin_checkuser.php. This I assume would be the incorrect location.
This is why you need to add the absolute url to your script. And if it is in your theme, you can use this method get_template_directory_uri() to get the template directory.
See here: http://codex.wordpress.org/Function_Reference/get_template_directory_uri

Query string parameters from Javascript do not make it to processing PHP script

I want to populate a jQWidgets listbox control on my webpage(when page finished loading and rendering) with values from an actual MySQL database table.
PARTIAL SOLUTION: Here
NEW PROBLEM:
I've updated the source code and if I hardcode the SQL string - the listbox gets populated. But I want to make a small JS function - popList(field, table) - which can be called when you want to generate a jQWidgets listbox with values from a MySQL database on a page.
Problem is - for some reason the $field and $table are empty when the PHP script is being executed, and I receive You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM' at line 1 error. What gives?
The page:
<div id="ListBox">
<script type="text/javascript">
popList("name", "categories");
</script>
</div>
popList(field, value):
function popList(field, table) {
$.ajax({
type: "GET",
url: 'getListOfValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: 'json',
success: function(response) {
var source = $.parseJSON(response);
$("#ListBox").jqxListBox({ source: source, checkboxes: true, width: '400px', height: '150px', theme: 'summer'});
},
error: function() {
alert('sources unavailable');
}
});
}
getListOfValues.php:
<?php
require "dbinfo.php";
// Opens a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$field = $_GET["field"];
$table = $_GET["table"];
$field = mysql_real_escape_string($field);
$table = mysql_real_escape_string($table);
$qryString = "SELECT " . $field . " FROM " . $table;
$qryResult = mysql_query($qryString) or die(mysql_error());
$source = array();
while ($row = mysql_fetch_array($qryResult)){
array_push($source, $row[$field]);
}
mysql_close($connection);
echo json_encode($source);
?>
Ok, you have a few things here. First off you need a callback function when you do the ajaxRequest. (I'll explain why in a bit.) So add the following line BEFORE your ajaxReqest.send(null);
ajaxRequest.onreadystatechange = processAjaxResponse;
Then you need to add the processAjaxResponse function which will be called.
function processAjaxResponse() {
if (ajaxRequest.readySTate == 4) {
var response = ajaxRequest.responseText;
//do something with the response
//if you want to decode the JSON returned from PHP use this line
var arr = eval(response);
}
}
Ok, now the problem on your PHP side is you are using the return method. Instead you want PHP to print or echo output. Think about it this way. Each ajax call you do is like an invisible browser. Your PHP script needs to print something to the screen for the invisible browser to grab and work with.
In this specific case you are trying to pass an array from PHP back to JS so json_encode is your friend. Change your return line to the following:
print json_encode($listOfReturnedValues);
Let me know if you have any questions or need any help beyond this point. As an aside, I would really recommend using something like jQuery to do the ajax call and parse the response. Not only will it make sure the ajax call is compliant in every browser, it can automatically parse the JSON response into an array/object/whatever for you. Here's what your popList function would look like in jQuery (NOTE: you wouldn't need the processAjaxResponse function above)
function popList(field,table) {
$.ajax({
type: "GET",
url: 'getListofValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: "json",
success: function(response) {
//the response variable here would have your array automatically decoded
}
});
}
It's just a lot cleaner and easier to maintain. I had to go back to some old code to remember how I did it before ;)
Good luck!

Categories