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
});
Related
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();
}
Okay so, I'm a bit stuck... Here's my problem. So, what I'm trying to achieve is I have a JS calendar and what I want it to do is when I click on a date, it fetches the times available for that day and displays it and then changes depending on what day you click on WITHOUT refreshing the page. Now, looking around, the only way I can seem to do this is with AJAX (suggestions welcome) although I have never touched AJAX before so have no idea what I'm doing here.
So I've currently got my .HTACCESS files setup on my webserver to use dynamic subdomains.
It's sort of like a multi-step form, and I'm collecting data in the SESSION as I go. Now what I'm guessing the way to do is here, to send a AJAX query with a JS variable with the date and then that runs an SQL query and gets the times and displays them. Here's what I have so far.
Update Session
<div class="output"><?PHP echo $_SESSION["outputTimes"]; ?></div>
<script>
$("#clickme").click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'data.php',
data: { date: '2020-07-04'},
success:function(response){
alert(response);
}
});
});
</script>
data.php
<?php
//Start Session
session_start();
//Include Database Config
include ("config.php");
//POST
$requestDate = $_POST["date"];
//Define SQL Query
$app_get_sql = "SELECT * FROM cc_av WHERE date=$requestDate";
//Run Query
if($result = mysqli_query($db_connect, $app_get_sql)){
while($row = mysqli_fetch_assoc($result)){
$_SESSION["outputTimes"] = '<li>'.$row["time"].'</li>';
}
}
?>
Currently, when I run this, I get the response in the alert() as the current code of the page I'm on. Hence why I noted about my HTACCESS although I can include() it just fine using the same root. Also, from the results of the data.php, how would I output the code sort of update what would be there at the moment.
Here's what I'm trying to create...
https://drive.google.com/file/d/1bgxSUxN6j2IOZcQBuAOo-PeCsuRgdmZ-/view?usp=sharing
Thanks in advance.
So, I've managed to work out what was going wrong. Because my HTACCESS file is creating SubDomains, it was also redirecting the Paths so in the AJAX code I used a URL to the code instead and then added a header to my PHP code on the file that needed to be requested.
header("Access-Control-Allow-Origin: (URL NEEDING TO BE REQUESTED)");
Final AJAX Code
var scriptString = 'THISISMYSTRING';
$('#clickMe').click(function(){
$.ajax({
method: 'get',
url: '(URL)/data.php',
data: {
'myString': scriptString,
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
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>
I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data
I'm writing a script to retrieve the scores from an osu! beatmap. The script uses the osu! API, which can be found here. I've obtained a valid API key, and got the info from the website. My project can be found here: failosu!.
This script is called by AJAX, and the variable s is passed via POST.
My problem is with the returned array.
In the following snippet (not really, it's pretty much my entire script), I make a request for the beatmap information first. In doing this, I am passing a variable, s (beatmap set ID), to the server, and trying to get the variable b (beatmap ID).
However, whenever I call $d1['beatmap_id'], it doesn't return anything to the main page. Instead, my AJAX script runs the error function rather than the success function. Does anyone know what my problem is?
if($_POST['id']) {
$s = $_POST['id'];
$k = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$u0 = "https://osu.ppy.sh/api/get_beatmaps?k=".$k."&s=".$s;
$d0 = json_decode(file_get_contents($u0));
$d1 = get_object_vars($d0[0]);
$b = $d1["beatmap_id"];
// THE CODE STOPS WORKING HERE FOR SOME REASON ????
$u = "https://osu.ppy.sh/api/get_scores?k=".$k."&b=".$b."&m=0";
echo $u;
$d = json_decode(file_get_contents($u));
for($i=0;$i<count($d);$i++) {
echo "<li>".$i." ".$d[$i]['username']."</li>";
}
}
Does anyone know what's wrong? Do you need me to tell you more information about my code?