How to run an SQL query from JavaScript [duplicate] - javascript

This question already has answers here:
ReferenceError: $ is not defined
(7 answers)
Closed 3 years ago.
This question is pretty much what I am trying to do, but I cannot understand how to use it in my context.
I have tried the marked answer and the answer submitted by xdazz. Both of these answers seem to send the variables from the client-side to the php script through POST. When I attempt this, it simply does not hit my alerts, which leads me to believe that the php script receiving the POST variables is never being executed.
Here is the function which runs when I click a button on my js canvas
function updateLeaderboard()
{
alert("before");
$.post("process.php", { postantNum: antNum, postantRate: antRate },
function(data)
{
alert(data);
} );
alert("after");
}
Here is the process.php file
<?php
$antNum = $_POST['antNum'];
$antRate = $_POST['antRate'];
echo $antNum;
echo $antRate;
$con=mysqli_connect("localhost","root","pass","login");
mysqli_query($con,"UPDATE userdata SET `words`='$antNum' WHERE `player`='$antRate'");
?>
HTML running the javascript:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>p5.js example</title>
<style> body {padding: 0; margin: 0;} </style>
<script src="../p5.min.js"></script>
<script src="../addons/p5.dom.js"></script>
<script src="../addons/p5.dom.min.js"></script>
<script src="../addons/p5.sound.min.js"></script>
<script src="antclicker.js"></script>
</head>
<body>
</body>
</html>
I wish to be able to send in antNum and antRate from the client-side js game I have created to the database for storage.
There are no error messages, I just know it never gets to the echos in the process.php and never hits the after alert, only the before alert is triggered.
EDIT:
Now since I have dipped my feet into chromes tools, I have discovered that on the line $.post("process.php", { postantNum: antNum, postantRate: antRate },
(yes I have changed the code a little bit) I get the error : ReferenceError: $ is not defined, how can it be singling out the "$". I'm guessing this probably means that there are some syntax errors nearby.

First off in the HTML I did not know I needed to include
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
as I did not know I was using ajax, this is why the $ was undefined.
the updateLeaderboard function should look like this.
function updateLeaderboard()
{
alert("before");
$.post("process.php", { antNum, antRate },
function(data)
{
alert(data);
} );
alert("after");
}
antNum and antRate are just vars which are previously defined.
and the process.php should look like
<?php
$antNum = $_POST['antNum'];
$antRate = $_POST['antRate'];
$con=mysqli_connect("localhost","root","pass","login");
mysqli_query($con,"UPDATE userdata SET `antNum`='$antNum' , `antRate`='$antRate' WHERE `player`='bob'");
?>
just swap bob out for the user in question.
PS. This was also a factor in helping me find the answer, by first allowing me to notice the $ was undefined.

Related

How can the client-side listen for anything outside the web page without the server-side?

What I want to do is use JavaScript (or some other client-side way) to listen for events occurring outside the web page without server-side help. It might look like this:
// tester.js
cses = new ClientSideEventSource("JSEventSource.js");
cses.onmessage = function(event){
// do something
}
// JSEventSource.js
CSES_return("CSES has been run!");
// note how this is client-side
The problem here is that this is all imaginary because those functions (sadly) don't exist. AJAX calls to JS files don't work. Here is an example of it's usage:
function getNotifications()
{
var cses = new ClientSideEventSource("JSEventSource.js");
cses.onmessage = function(event){alert(event.data)}
}
function sendNotification()
{
CSES_return("You have got a notification!");
// this does not give an error even if this is not used in CSES mode
// which is started with: new ClientSideEventSource("jsfile.js");
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Test</title>
<meta charset="UTF-8"/>
</head>
<body>
<button onclick="getNotifications()">Get Notifications</button>
<button onclick="sendNotification()">Send Notification</button>
</body>
</html>
<!-- You will get errors because ClientSideEventSource and CSES_return do not exist -->
That is basically a messaging system (with a certain message) that doesn't use any Server-Side code. Is there anything to replicate this?

Refresh currentsong shoutcast

I know there are a lot of these questions about this one, but unfortunately i cant find the right answer so i try it again.
I simply want to display the current song from "http://178.19.116.253/currentsong?sid=1" on my site that must refresh every x seconds.
I rather not use php cause it will make a background process for all users, so i've seen a lot of little scripts like this..
<div id="sc_stats"><?php include_once 'sc_stats.php'; ?></div>
var refreshId = setInterval(function() {
$.get("sc_stats.php", function(data) {
$("#sc_stats").html(data);
});
}, 10000);
But i cant get mine to work without php.
Someone can help me with this?
You don't need to use php, the following snippet which only uses jQuery will display the current song and refresh it every second.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="nowplaying"></div>
<script src="https://cdn.jsdelivr.net/jquery/3.2.0/jquery.min.js"></script>
<script>
setInterval(function() {
$.ajax({
url: "http://178.19.116.253/currentsong?sid=1",
dataType: "html",
success: function(data) {
$('.nowplaying').text(data);
console.log(data);
}
});
}, 1000);
</script>
</body>
</html>
Note: In order to get this to work, either:
This piece of code must run on the same domain/server as your stream
Or CORS must be enabled on your server. More about CORS can be found here
You can test CORS with the following Chrome plugin: Allow-Control-Allow-Origin:

Script only works in console [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I recently started to learn jQuery so I had some exercices to do. This one is about displaying messages by clicking on page element. Here is the code :
var $caption = $('caption');
$caption.on('click', function(event) {
    $(' <td>Wp it worked</td>').insertAfter('tr');
});
<!DOCTYPE html>
    <html>
        <head>
            <title>Happy Birthday !</title>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
            <script type="text/javascript" src="js/script.js"></script>
            <link rel="stylesheet" type="text/css" href="css/style.css">
            <meta charset="utf-8">
        </head>
        <body>
                <table>
                    <caption>Click here</caption>
                        <tr>
 
                        </tr>
                </table>
        </body>
    </html>
So the problem is that it doesn't work. When I write the script in the console it works perfectly, but with the js file it basicly doesn't. So I know it's not a problem of folder because when I put something like alert('test'); in the js file it works. Someone knows why ?
it is working in the snippet , however you may try this.
$(document).ready(function () {
var $caption = $('caption');
$caption.on('click', function (event) {
$(' <td>Wp it worked</td>').insertAfter('tr');
});
});

jQuery ajax plugin get entered value

I am using jQuery autocomplete plugin to get values from database using this plugin. As per demo I made my code like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="js/jquery.autocomplete.js"></script>
<link rel="stylesheet" href="styles.css">
<script>
jQuery(document).ready(function() {
jQuery('#autocomplete').autocomplete({
serviceUrl: 'ajax.php',
});
});
</script>
</head>
<body>
<input type="text" id="autocomplete">
</body>
</html>
Now when I am doing any search. Then in console tab I can see the ajax request like this
XHR finished loading: GET "http://localhost/ajax.php?query=united
additionally it is showing one error in console tab like
Uncaught SyntaxError: Unexpected token < in jquery-2.1.0-min.js:4
Now to get the value of query string in ajax.php I did like this
$value = $_POST['query];
echo $value;
But it is not showing any value. So can someone tell me how to get the input entered values in the ajax.php file? Any help and suggestions will be really appreciable. Thanks
You are using Google Chrome, aren't you?
It would be helpful to see what data is actually transfered...
Try to hit F12, open the "Network" tab, click on the item that shows up when the AJAX request is made, and check the output in the "Response" sub tab.
My assumption: You're facing some syntax error in your PHP file that outputs HTML tags as part of an error message.
BTW: Your PHP code contains a syntax error, the ' after index "query" on line 1 is missing...

How to display variables from external JavaScript in HTML. Internet Explorer 7

I realize this is a horribly newbie question, but Ive been trying to fix it for days trying different methods so I just wanted to ask what would you do.
I am attempting to create a web program to use at work, and I have this setup:
Windows 7
IE 7 - Cannot Upgrade.
The "website" is not a webhost, basicly I have a folder on my desktop with html/css/js files and I use IE to run the scripts, no host.
I want to keep a set of vars, mostly strings, in an external JS file and pull the JS into different HTML pages. I want it to write on load of the document.. not on ready. It does not have to be user dynamtic.
Also, When I make the js file, does it have to have a header.. like HTML has doctypes?
I really appreciate your help as I am trying to learn and will cont on my own from here. My setup is much different than most, and im not sure which part was causing my problem so I finally broke down and posted.
When you write your JavaScript file it doesn't have to have any header or doctype. For example you can have a variables.js file that looks just like this:
var x = "abc";
var y = "def";
and have many HTML files that include variables.js like this:
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>title</title>
</head>
<body>
<!-- page content -->
<script src="variables.js"></script>
<script>
alert(x);
</script>
</body>
</html>
and your variables should be available there. Any script that is included after the reference to your variables.js should have access to everything that was included before without the need to listen to any events.
If you need to listen to the events then I suggest to use jQuery or some other JavaScript framework. An example for jQuery would be:
$(window).load(function() {
alert(x);
});
A more advanced example of changing the DOM elements:
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>title</title>
</head>
<body>
<p>Select variable:</p>
<p>
Show x
Show y
</p>
<p>Value:</p>
<p id="value"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="variables.js"></script>
<script>
$('#show-x').click(function (e) {
e.preventDefault();
$('#value').html(x);
});
$('#show-y').click(function (e) {
e.preventDefault();
$('#value').html(y);
});
</script>
</body>
</html>
If it's not a global variable, you can't display/print/access or whatever you call it because it has a local scope, defined in a function.
You can probably only use a debugger simply to debug it

Categories

Resources