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?
Related
I am running a Wordpress website, and trying to call PHP methods from my Javascript code.
When a button is tapped, the saverFoo() Javascript method is called, and attempts to call the PHP method save_image_data().
function saverFoo() {
var dataURL = canvas.toDataURL();
<?php echo save_image_data(dataURL); ?>;
}
function loaderFoo() {
var loadedImage = <?php echo loadimagedata(); ?>;
console.log(loadedImage);
}
The PHP method's implementation is in the function.php file, and is simply attempting to save some image data (dataURL) in the user's meta
function save_image_data($imageData) {
global $current_user;
update_user_meta( $current_user->ID, 'user_design', $_POST['$imageData']);
}
function loadimagedata() {
global $current_user;
$old_notes = get_user_meta($current_user->ID, 'user_design', true);
return $old_notes;
}
Inspecting my web-page in Chrome, shows me an empty space where loaderFoo () (javascript) is supposed to be calling loadimagedata() (php) , and loadedImage is an undefined variable, when I try to log it, such as:
function loaderFoo() {
var loadedImage = ;
console.log(loadedImage);
}
Not sure what fundamental mistake I'm making here.
Always remember that PHP runs on the server side, and javascript on the client side. So we have an order here, the server receives the request PHP processes what it should process and render the page, only here Javascript will be executed.
In this example, when the 'saverFoo()' function is executed, this function <? Php echo save_image_data (dataURL); ?>; has already been written on the page. PHP will not be able to get the information contained in the dataURL variable, not on this way. To do this, we must make a request to the server with this desired information, but with an "image" is not trivial to do this, as there is a limit on the size of the post when using a normal String field.
function saverFoo () {
var dataURL = canvas.toDataURL ();
<? php echo save_image_data (dataURL); ?>;
}
PHP doesn't work that way. It is a pre-processor. It is all run and done server side and the resulting text/html/binary data/whatever is sent out to the client. In the case of a content type of text/html the browser will load it, parse it, render it, and run whatever javascript is called.
How you can mix PHP and JavaScript in-line like that would be to use PHP to fill in variables. For example
alert("<?php print($_SERVER['SCRIPT_FILENAME']); ?>");
would work because the client would see
alert("/path/to/foo.php");
and render that for the user.
To really interact with PHP using JavaScript, you'll want to look into using a http based REST type service and perhaps one of the various popular tool sets like Angular, Vue, etc.
Originally I wanted to use node.js, but after an entire day of frustration, I switched to using jquery and mySQL. The logins seem to be working, but something is wrong in the way it is handling variables. All I want to do is update the database with two things: score and name. Here is the code I modded for my project in PHP:
<?php
$db = "myDatabaseNameIsCorrect";//Your database name
$dbu = "soIsMyUsername";//Your database username
$dbp = "AndMyPassword";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['name']) && isset($_GET['this.score'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['this.score']));
$sql = mysql_query("INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
And here is the JS! that runs the PHP:
let gameoverScene = new Phaser.Scene('GameOver');
gameoverScene.create = function(){
this.laughSound=this.sound.add('laughSound')
this.gameW = this.sys.game.config.width;
this.gameH = this.sys.game.config.height;
this.goToTitle=function(){
var name = prompt('Enter your name');
jQuery.ajax({
type: "POST",
url: 'savescores.php?name=' +name +'&score=' + this.score,
dataType: 'text',
data: {functionname: 'add', arguments: [name, this.score]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
this.scene.start('Title')
};
I also tried changing the data type and that didn't work, but I'm not ruling it out yet as a problem.
Here are links to the project and the database:
www.igglepud.com/DeerDefender/Testing
www.igglepud.com/DeerDefender/Testing/getscores.php
This is the error I get:
gameover.js:20 Uncaught TypeError: Cannot use 'in' operator to search for 'error' in
Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.
at Object.success (gameover.js:20)
at fire (jquery.js:3268)
at Object.fireWith [as resolveWith] (jquery.js:3398)
at done (jquery.js:9305)
at XMLHttpRequest.<anonymous> (jquery.js:9548)
So, the error you're getting is because, in the JavaScript, obj (or the parameter in obj's position) is a string, not an array.
You can see some examples here of how you can properly check for and catch errors.
Edit:
So, in regards to your question about the score variable.
It's important to note that there are 2 types of variables at play here.
The first one is PHP GET variables. PHP GET variables are set via the following format:
var=value
You can set these variables by calling a PHP script like this:
script.php?var1=value1&var2=value2&var3=value3 // etc...
You can access them like this:
echo $_GET["var1"];
echo $_GET["var2"];
echo $_GET["var3"];
Which produces the result:
value1
value2
value3
The second variable at play is a JavaScript variable. Those can only be accessed in JavaScript. a JavaScript variable means nothing in PHP.
So, let's examine what you're doing from the JavaScript:
url: 'savescores.php?name=' +name +'&score=' + this.score,
For the purpose of explaining let's say name = Chipster, and this.score = 123.
What this code will do is try to open the following file:
savescores.php?name=Chipster&score=123
Remembering that PHP GET variables are set by the format script.php?var1=value1&var2=value2&var3=value3 // etc... we can see that there are 2 GET variables available from the PHP script called name and score. Thus, to access score from PHP you need to do it like this:
echo $_GET["score"];
This will output 123 in our example.
This may not solve your problem, but one issue I see with your code is calling strip_tags (or another function that alters the string) after it has already been quoted for insertion with mysql_real_escape_string may defeat the purpose of mysql_real_escape_string. It should be the very last function called on data before it's inserted.
Also, if score is an integer string, intval serves just as well as mysql_real_escape_string for sanitizing integers for insertion.
EDIT: You're also checking for GET variables in the PHP when the submission method used in the jQuery is POST. Try looking at $_POST instead of $_GET on the PHP side. You don't need to put variables in a query string if you're putting them in the request body via POST either.
First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.
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 am trying to save a string that is created dynamically based on the user's interaction with the web app that I'm creating. just a string. nothing special. I am using ajax to send the string up to the server, and it seems that it is getting as far as the file_put_contents function I am using, but it seems to go haywire. It makes the txt file, but it does not put anything in it, and it does not send back q, the variable that I have it echo back.
Another weird thing is that when I try to write to said file with this
file_put_contents($putStringHere, $q);
I also tried this one:
file_put_contents($putStringHere, "$q");
The file always says that this happened:
modified: Today, Now (last time I ran the function)
Last Opened: Today, 5 minutes ago... last time I opened the file by hand
This would make sense, except for the fact that the function above contains fopen, fmodify, fclose, or whatever they're called. And the modified set to the last time I ran the function... I am super confused on this one. anyone who can help, I will greatly appreciate it.
ajax that sends string (yes, i made sure it was a string)
//ajax for saving changes
function stylesheetBackup(str){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","stylesheetBackupFile.php",true);
console.log("q="+str);
xmlhttp.send("q="+str);
}
also tried ajax with
xmlhttp.open("POST","stylesheetBackupFile.php",true);
xmlhttp.send();
php that I call with ajax
<?php
//get the q parameter from URL
$q = $_POST["q"];
$putStringHere = "savedStyleSheet.txt";
//output the response
echo $q;
//save to a backup file
file_put_contents($putStringHere, $q);
?>
You have a mis-match:
xmlhttp.open("GET"...
and
$q = $_POST["q"];
Here's two things that might help fix your problem:
In the AJAX request, you specify that it's a GET request. However, in your PHP file, you're trying to get the q value of $_POST. Try $_GET['q'] instead.
I'm not sure you're able to send your GET data using xmlhttp.send. Try adding it to your URL, as in xmlhttp.open("GET", "stylesheetBackupFile.php?q=" + str, true).