AJAX/JQuery function undefined - javascript

I'm working on a project that allows users to invite other users. When a user gets an invite, a pop-up should, well...pop up...asking them to accept or decline. For this, I'm using an AJAX call to check if they have any invites. This will eventually be an automatically called function, but for now I'm just testing it with a simple button and onclick function.
What happens is, the AJAX request goes to checkInvitations.php, which checks a database table full of users. In plain English, checkInvitations.php checks whether the "user" AJAX sent over has an invitation. If they do, checkInvitations passes information back to the AJAX request with (name of person who invited the user) and (confirmation of an invite).
For whatever reason, though, my function keeps coming up as undefined, even though I've imported the JQuery library. I've no idea why this is the case.
Here's the function with the AJAX request.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript">
function checkForInvitations()
{
var invitedPlayer = '<?php echo $_SESSION["goodUser"]; ?>' //invitedPlayer = the logged-in user
console.log("invitedPlayer is: "+invitedPlayer); //variable debug check
$.ajax({
type: "post",
url: "checkInvitations.php",
data: {invitedPlayer: invitedPlayer},
success: function(data)
{
// parse json string to javascript object
var invitations = JSON.parse(data);
console.log(invitations); //variable debug check
// check the invitations to/from
var invitingPlayer = invitations.invitationFrom;
var invitationStatus = invitations.invitationStatus;
//if player has received an invite, pop up a screen asking them to confirm/accept the invite
if(invitationStatus != 'false')
{
clearInterval(checkInvitationIntervalId);
confirm_yes = confirm(invitingPlayer+" invited you to a game. Accept ?");
}
}
})
}
And here's the PHP page it requests to
<?php
session_start();
// Create connection
$conn = new mysqli('localhost', 'root', '', 'warzone');
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$invitations = array();
//look for rows in database where user=the invited user and the invitestatus has been set to true (after invite was sent)
$request = "SELECT * FROM warzone.logged_in_users WHERE USER='".$_POST["invitedPlayer"]."' AND INVITESTATUS='TRUE'";
$res = $conn->query($request);
if($row = $res->fetch_assoc())
{
$invitations["invitationFrom"]=$row["INVITING_PLAYER"];
$invitations["invitationStatus"]='true';
}
else
{
$invitations["invitationFrom"]='none';
$invitations["invitationStatus"]='false';
}
echo json_encode($invitations);
?>
Keep in mind when I use the $_SESSION["goodUser"] in place of $_POST["invitedPlayer"] in the above PHP file, I get the exact output I'm looking for. I know that works. I just can't get it to work with $_POST, obviously, because the AJAX request isn't being made/is broken/is undefined.
Any help is appreciated!

From the Mozzila Developer API on script tags.
If a script element has a src attribute specified, it should
not have a script embedded inside its tags.
Therefor you want to seperate your inclusion of jquery into a seperate tag.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript">
</script>
<!-- end script before you start the one with your code in it -->
<script type="text/javascrpt">
// Your code that involves $ here...
</script>

Related

Change PHP session variable from AJAX call

I am building a website for a school-project. I have been programming in PHP for about a year now, and javascript shouldn't be that much of a problem either.
However, I ran into a problem a couple of days ago. I have a "warning/notification" bar under my navbar. There is two buttons, one where you close the notification and one where you get redirected to read more about it.
If you click the close button, I want to make an AJAX call to the same file, where I have PHP code that will detect the call and then change a SESSION variable, so the notification doesn't show up again regardless of which file you are on.
This however, does not seem to work no matter how many approaches I have tried. I've had enough of this struggle and would greatly appreciate any help from this wonderful community.
This by the way is all in the same file.
Here's the AJAX code:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
type:"POST",
url:"navbar.php",
data: info
});
});
And here's the PHP code (that prints out the HTML):
<?php
require "includes/database.php";
$sql = "SELECT * FROM posts WHERE (post_sort = 'homepage' OR post_sort = 'everywhere') AND post_type = 'warning'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($_SESSION["closed_notification"] == 'no') {
if($resultCheck >= 1) {
while($row = mysqli_fetch_assoc($result)) {
$post_header = $row["header"];
$post_content = $row["post_content"];
$post_index = $row["post_index"];
echo '<div class="nav_bottom_holder_warning">
<div class="navbar_lower_container">
<p>'.$post_header.'</p>
<button class="btn" id="close_warning">Stäng</button>
<button class="btn" id="show_warning">Visa inlägg</button>
</div>
</div>';
}
}
}
?>
Last but not least, the code that is responsible for changing the actual SESSION:
<?php
$_SESSION["closed_notification"] = "no";
if(isset($_POST["info"])) {
$_SESSION["closed_notification"] = "yes";
}
?>
I have tried numerous approaches to this problem, this is just one of them. At this point I am just clueless of how to solve it, thank you.
EDIT: I have already included this file in another file that contains a "session_start()" command. So using that in this file would be no help.
First of all there is no session_start(); on the first line so it will give you an error for the Session Variable.
Secondly update your ajax code to this:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
url: 'navbar.php',
type: 'post',
data: {info:info}
});
});
It basically means that data:{name1:variable2}
Here you are giving the data from js variable(variable2) 'info' to php as info(name ==> that we generally set the input attribute) so in php you can access it as $_POST['info'];.
And lastly you gave the js variable value 'close' and you just checked whether the variable is set while changing the session variable.
Change it to actually checking the value which is better and clear when others read your code.
Summary:
Change data: info to data:{info:info}
Just use Javascript local storage or session storage. I guess it is not important for the server to know if a user has closed the notification yet or not.
$("#close_warning").click(function(){
// close the notification
$("#notification").hide();
// set 'closed' flag in local storage
storage.setItem('closed', 1);
});
Have javascript hide the notification, if the 'closed' flag is set.
if (storage.getItem('closed')) {
$("#notification").hide();
}

Unable to get data from database using AJAX & PHP

Update: The first part of this question has been solved and has been updated below with the working code.
~
I’m working on a Javascript application and I’m having difficultly getting an AJAX call to work.
I’m able to successfully insert data into my database using AJAX POST & PHP but I can’t seem to pull data from the database.
I have a Javascript application which uses an image, currently it gets this image from a location in the root folder like this:
img.src = 'picture1.jpg';
Instead of doing this, I want to select a random image from a table in the database every time the Javascript application loads.
I’ve created a table with a single column, and populated this with the addresses/locations of images contained in a folder in my root directory.
For example:
/images/00001.jpg
/images/00002.jpg
/images/00003.jpg
This is the PHP file (located at /scripts/imagerandomizer.php) I’m using to call a random image address:
<?php
session_start();
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabase";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlrandomize = mysqli_query($conn,"SELECT images FROM `images` ORDER BY RAND( ) LIMIT 0 , 1");
$row = mysqli_fetch_row($sqlrandomize);
header('Content-Type: application/json');
echo json_encode($row);
mysqli_close($conn);
?>
And the AJAX which initiates the PHP & listens for the echo:
function getRandomImage() {
$.ajax({
url: 'scripts/imagerandomizer.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
I’m trying to use alert(data); to have the randomly chosen image location/address appear in an alert box (just to see if it’s working). But it’s not working for me, I’m pretty sure I've made a mistake somewhere, and I’m not sure if json is the right data type to use here?
I would like to have the returned address replace the current img.src = 'image.jpg'; , so that when the Javascript application starts, it will receive a random image from the img.src = section of code.
Thanks for any help on this!
UPDATE:
The Javascript can now correctly display a random address (using either “alert” or “console.log”) every time it’s loaded. The last part of my question concerns how to have a .js file read this string, and use it as the location of an image that it then fetches.
This is how my game is set up:
I have a file named “game.js”, it contains the code needed for the game to operate, right now, part of that code is this: img.src = 'images/image00001.jpg'; Right now that image is permanently defined and doesn’t change. I’m trying to replace this static definition with the randomized one. Basically I’m trying to get the randomized address to appear after img.src = whenever game.js loads.
I also need to make sure that this event happens before the rest of the game.js code initiates, as I need the randomly chosen image file to be in place before the rest of the game loads.
I’ve tried defining img.src by including img.src=(response) in the AJAX call at the top of the game.js file but it’s failing to load any image into the game. I’m thinking that maybe this is the wrong way to do this?
2nd UPDATE
Hi #PHPGlue
I’ve been trying to get this to work for days now but I’m still missing something.
This is my function to grab the randomized image, and I’ve tried to place the code to run the game in the success function if (img.src) {//code to run the game here}:
Function getRandomImage() {
$.ajax({
url: 'scripts/imagerandomizer.php',
data: "",
dataType: 'json',
success: function(response){
$('#imageId').attr('src', data.image);
img.src = $('#imageId');
if (img.src) {
//code to run the game here
}
}});
};
I’m definitely missing something here, I think I’m not understanding what you mean correctly. I’d really appreciate any advice on this and thank you again for taking the time to look at my question!
3rd Update
Hi, my current code is:
function getRandomImg(gameFunc){
$.post('scripts/imagerandomizer.php', {randImg:1}, function(data){
var im = $('#imageId');
im.attr('src', data.image);
im.load(function(){
gameFunc(img.src=im);
}
}, 'json');
}
getRandomImg(function(){
javascriptgame();
});
function javascriptgame(){
//in this area I’ve placed all the code to make the game work
}
When you said /* pass args to gameFunc here */ I entered img.src=im. (I’m not sure I understand you correctly but I think I’m supposed to define the img.src= for the game to call in this line?
When you said // game code here - could also pass function name instead of Anonymous function, I created a new function called javascriptgame, inside which I placed the game’s code, and then called this function at this line. I’m not sure if that’s what you meant for me to do?
Unfortunately right now there’s still no image loading into the game, I want to thank you again for taking the time to help me with this and if you could offer any more advice that would be awesome! Thanks so much.
The problem is with your mysqli_query()
It should be like
mysqli_query(connection,query,resultmode)
Where connection and query are required and resultmode is optional.
Example:
mysqli_query($conn,"SELECT images FROM images ORDER BY RAND( ) LIMIT 0 , 1");
For more details please check out
mysqli_query
First you should make a separate secure PHP connection page
// connection.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
You're problem is that you don't actually get any results by just making a query. You still have to get the query results and use them in your code:
<?php
include 'connection.php'; $db = db(); $r = array();
if(isset($_POST['randImg'])){
if(+$_POST['randImg'] === 1){
if($iq = $db->query('SELECT images image FROM images ORDER BY RAND() LIMIT 1')){
if($iq->num_rows > 0){
$fi = $iq->fetch_object(); $r['image'] = $fi->image;
}
else{
// no results were found
}
$iq->free();
}
else{
// connection failure
}
}
else{
// randImg hack
}
}
echo json_encode($r);
$db->close();
?>
Get that in JavaScript as data.image inside your success function.
function getRandomImg(gameFunc){
$.post('scripts/imagerandomizer.php', {randImg:1}, function(data){
var im = $('#imageId');
im.attr('src', data.image);
im.load(function(){
gameFunc(/* pass args to gameFunc here */);
}
}, 'json');
}
getRandomImg(function(){
// game code here - could also pass function name instead of Anonymous function
});

AJAX Request from Table Rows to Details

This is my first time on here so I'm sorry if I'm not quite up to snuff with all of you.
In the process of learning AJAX so I'm brand new, but need to get a page done for our staff website.
I have a page (php) which builds a list through a mysql query of all patients. I have absolutely no problem with this. However, I'm stuck on this part.
When a user clicks a specific row (aka Patient Name), I want it to pull up the details of that patient associated with it in our mysql database on the right-hand side so the page doesn't have to refresh and they aren't directed to any other pages.
I have seen examples like this when it came to customers, like you click the name and a div appears to the right containing email, phone, etc. etc.
Does anyone have any good starting points? I have searched as far as I can, and I'm beginning to think I'm not using the right language when searching for my answer.
Thanks ahead of time... Matt
Use jQuery.
First you need to make a web service on your server. The web service will accept a, let's say, POST parameter which will be either patient name or the patient ID. Based on this id/name you will query your MySQL database, fetch all the details and return as json.
On the front end, you can use jQuery.post(). You will need to pass the appropriate URL and the data. In return, you will get JSON data. In the success callback method of jQuery.post/$.post you can create a div on the right and display those data.
If you are going to return the data in json format, you can also just use $.postJSON()
Please make sure to set the appropriate headers in your PHP webservice. These two are probably the most important
Content-Type: application/json // if you are gonna return the data in JSON format
Access-Control-Allow-Origin: * // to let the browser pass the data to the DOM model. This is to allow CORS (Cross Origin Resouce Sharing)
SAMPLE:
example.php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['patientID'])) {
$patientID = $_POST['patientID'];
$data = array();
// Enter the appropriate details below
$mysqli = new mysqli("host", "username", "password", "db_name");
/* check connection */
if ($mysqli->connect_errno > 0) {
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
$statement = $mysqli->prepare("SELECT * FROM `patients` WHERE `patientID` = ? LIMIT 1");
$statement->bind_param('i', $patientID);
$statement->execute();
// You need to write a variable for each field that you are fetching from the select statement in the correct order
// For eg., if your select statement was like this:
// SELECT name, COUNT(*) as count, id, email FROM patients
// Your bind_result would look like this:
// $statement->bind_result($name, $count, $id, $email);
// PS: The variable name doesn't have to be the same as the column name
$statement->bind_result($id, $name, $email, $phone);
while ($statement->fetch()) {
$data["id"] = $id;
$data["name"] = $name;
$data["email"] = $email;
$data["phone"] = $phone;
}
$statement->free_result();
echo json_encode($data);
}
example.html
Patient #123
example.js
function getPatientData(element) {
var patientID = $(element).attr("id");
$.post("example.php", {"patientID": patientID}, function (data) {
// display the data in appropriate div
}, 'json');
return false;
}
You should do an jquery ajax call on element click
$('.patientClass').on('click', function() {
var patientid = $(this).attr('id');
// attr('id') should be the patients id
$.ajax({
url: "getPatientDetailsURL.php",
type: "post",
data: {
id: patientid
},
success: function(response) {
// create div with response details or append parsed json to existing div
}
});
)}
And on the backend get the patiend id with (int)$_POST['id']
Also you on the backend you can set the page to respond only to ajax calls like this:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//code here
} else {
// not ajax call
}

How do I auto-refresh my php chat-script?

I am having trouble getting my php chat script to auto refresh when mysql data is changed. I have done a good bit of research and it seems a lot of other people's solutions are more complicated then what I need (I'm going for something very basic).
I do not know any javascript so detailed comments would be appreciated if js is involved.
Here is the php script that I have created. It is functioning (at least for me).
include 'connect2.php';
echo "
Enter a Message:
<form method=post action='' name=chat>
<input type=text name=message>
<input type=submit name=chat value=Submit>
</form>
";
if (isset($_POST['chat'])) {
$message = $_POST['message'];
mysql_query("INSERT INTO chat set message='$message',user='$_SESSION[username]'");
}
$sql = "select * from chat order by id desc limit 15";
$result = mysql_query($sql) or die ("An error has occured with in the database.");
while ($data = mysql_fetch_assoc($result)) {
$db_message = $data['message'];
$db_user = $data['user'];
echo "$db_user : $db_message <br>";
}
?>
Any help would be appreciated, thanks! :)
You can use setInterval and jQuery library ajax functions to check for it.
For example, it's very simple to do with jQuery:
$(document).ready(function() {
// check once in five seconds
setInterval(function() {
$.get('/script.php', {do: 'new_messages'}, function(response) {
if(response == 1) {
window.location.reload();
}
});
}, 5000);
});
And somewhere on server:
if(isset($_GET['do']) && $_GET['do'] == 'new_messages') {
// some your code that detects if there's any new messages, and sets
// $there_are_new_messages to true, if there's any
...
if($there_are_new_messages) {
echo 1;
exit; // avoid further output
}
}
Please remember, that for this to work you need to ensure that there's no output before ajax block, as you can get into unexpected results.
Also consider that using output is not a good practice at all to show your script everything is ok. Better way is to set HTTP header with corresponding response code.
The best way to do this in your case would probably be using Ajax (and jQuery) and refreshing every X seconds.
Ready Handler- http://api.jquery.com/ready/
Javascript Timer- http://www.w3schools.com/js/js_timing.asp
Ajax Request- http://api.jquery.com/jQuery.post/
PHP json_encode- http://php.net/manual/en/function.json-encode.php
$( document ).ready(function() { //set up refresh timer on page load
var refreshTimer = setInterval(function(){refreshMessages()},5000); //creates timer to request every 5 seconds
});
function refreshMessages(){
$.post( "getMessages.php", function( data ) { //fire ajax post request
alert("Got messages: " + data); // this just alerts the data when the request is done, you'll probably want to format/print
});
}
On the getMessages.php side of things, you'll want to pull your messages from the database how you normally would. In this case, json encoding your php messages array would be an easy way for you to iterate the returned object.
<?php
$messages = // get messages array from database
echo json_encode($messages);
?>

Connecting to a MySQL database using PhoneGap, AJAX, and JQuery Mobile

I'm in a team developing an Android application that will rely greatly on the use of a remote database. We are using PhoneGap and Jquery Mobile and have been attempting to connect to our MySQL database using AJAX and JSON calls. Currently, we are having trouble in our testing phase, which is to verify we even have a connection at all by pulling a hard-coded user of "Ted" from mySQL / input via MySQL Workbench.
From what we have gathered, the process of data transmission works as this:
On our html file, we have a
<script type="text/javascript" src="Connect.js"></script>
^ Which should run the Connect.js script, correct? So from there, Connect.js is ran?
Connect.js runs, connecting it to our ServerFile.php that is hosted on an external web service, allowing it to run PHP to connect to the MySQL database and pull information.
//run the following code whenever a new pseudo-page is created
$('#PAGENAME').live('pageshow', function(event)) {
// cache this page for later use (inside the AJAX function)
var $this = $(this);
// make an AJAX call to your PHP script
$.getJSON('http://www.WEBSITENAME.com/ServerFile.php', function (response) {
// create a variable to hold the parsed output from the server
var output = [];
// if the PHP script returned a success
if (response.status == 'success') {
// iterate through the response rows
for (var key in response.items) {
// add each response row to the output variable
output.push('<li>' + response.items[key] + '</li>');
}
// if the PHP script returned an error
} else {
// output an error message
output.push('<li>No Data Found</li>');
}
// append the output to the `data-role="content"` div on this page as a
// listview and trigger the `create` event on its parent to style the
// listview
$this.children('[data-role="content"]').append('<ul data-role="listview">' + output.join('') + '</ul>').trigger('create');
});
});
Here is ServerFile.php. This should connect to the MySQL Database, make the Select statement, and then send the output to the browser encoded in the JSON format.
<?php
//session_start();
$connection = mysql_connect("csmadison.dhcp.bsu.edu", "clbavender", "changeme");
$db = mysql_select_db("cs397_clbavender", $connection);
//include your database connection code
// include_once('database-connection.php');
//query your MySQL server for whatever information you want
$query = mysql_query("SELECT * FROM Users WHERE Username ='Ted'", $db) or trigger_error(mysql_error());
//create an output array
$output = array();
//if the MySQL query returned any results
if (mysql_affected_rows() > 0) {
//iterate through the results of your query
while ($row = mysql_fetch_assoc($query)) {
//add the results of your query to the output variable
$output[] = $row;
}
//send your output to the browser encoded in the JSON format
echo json_encode(array('status' => 'success', 'items' => $output));
} else {
//if no records were found in the database then output an error message encoded in the JSON format
echo json_encode(array('status' => 'error', 'items' => $output));
}
?>
Yet nothing is showing here. What do we do from here?
First thing first. Try to determine where is the problem come from, server side or client side.
Print out your database query and encoded json can be useful. If you are creating a simple API service, you should be able to enter http://www.WEBSITENAME.com/ServerFile.php using your browser and look how the output is.
Use echo to print things with php.
If all looks ok, time to print out the response you receive from the server in the javascript and see what is off.
Use console.log to print thing with javascript. The logs should appear in the logcat section of eclipse (since you are developing android app)

Categories