Song didn't play when the url isn't empy - javascript

I'm really confused and got stuck building a music game using Phaser js framework.
I need the path audio which saved in localhost. To get that path I'm using AJAX. Here's my AJAX code in phaser :
function preload()
{
game.load.audio('song', pathsong);
}
function getSong()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
pathsong = xmlhttp.responseText;
alert("succes");
alert(pathsong);
}
else
{
alert(xmlhttp.readyState);
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", "getsong.php" , true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
And here's my getsong.php
<?php
$path = "asset/audio/music/1.mp3";
echo ($path);
?>
The xmlhttp.readyState and xmlhttp.status return 4 and 200 in a while and give success alert. But the song still didn't play, here's the screenshot of it.
The stop text is an alert that the song didn't play.
I can't understand why it didn't play even that var pathsong is not null.
I'm newbie at phaser and still learning about programming.
Please don't blame me, and sorry if my english is bad. I'm really trying hard to explain. ^^v

Probably you should run the preload() method right after redefining the pathsong variable when AJAX response has been successfully received.
Try to add preload(); after the line pathsong = xmlhttp.responseText;

Related

Ajax fails to find PHP file location

I have a simple code in a Javascript file that calls a PHP file using Ajax. At the moment it's a simple call and I don't need to pass any variables.
I'm using IIS and the folders structure is the following:
ROOT > sendMail.php
ROOT > JS > chat.js
The call starts from chat.js and it's the following:
function sendEmail(params){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("POST", "sendMail.php?q=" + params, true);
xmlhttp.send();
}
But I receive "404 Not Found". Someone can help me?
Thanks in advance!

Single Ajax Function That Able To Call Different PHP page

I have button below on my index.html:
<button value="about_us.php" onClick="fNt(value)">About Us</button>
<button value="faq.php" onClick="fNt(value)">FAQ</button>
<button value="contact_us.php" onClick="fNt(value)">Contact Us</button>
which I want to use AJAX to get info from php page as of value. I know I can create 3 AJAX function to target 3 php page, but if I have more buttons later it will consume much space.
So, I wonder is it possible to write something like this?
<script>
function fNt(value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","variable of clicked value",true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200{
document.getElementById("ajax").innerHTML = xmlhttp.responseText;}}}
</script>
I know the script above won't work, it is just to show you what I try to achieve, any idea how to do it? Pls help.
Try this, It will help you...
function fNt(url) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("ajax").innerHTML = xmlhttp.responseText;
}
}
}
<button onClick="fNt('about_us.php')">About Us</button>
<button onClick="fNt('faq.php')">FAQ</button>
<button onClick="fNt('contact_us.php')">ContactUs</button>
Happy Coding
Regardless, you will have to create a separate callback for each button (unless you want the action of clicking each button to do the exact same thing). Why not put the uniform ajax code in a function and pass to that function a url and a separate callback function. If you want to check the request object status, just pass it directly to the callback:
function doGet(route, callback){
var xhr = new XMLHttpRequest(),
method = "GET",
url = route; //If you need to massage the route or anything
xhr.open(method, url, true);
xhr.onreadystatechange = callback(xhr);
xhr.send();
}
Then to call it:
var route = "routedesired.com";
var callback = function(xhrObj){
if (xhrObj.readyState == 4 && xhrObj.status == 200{
console.log("HELLO WORLD")
}
}
Another Approach
I don't understand what exactly you are trying to do, but if you want to do something different for each link, you can just add the route to the callback function as well inside the doGet function I created:
function doGet(route){
var xhr = new XMLHttpRequest(),
method = "GET",
url = route; //if you need to massage the route or anything
var callback = function(routeParam){
if (xhr.readyState == 4 && xhr.status == 200{
switch(routeParam){
case "faq.php":{
//do some action if route is "faq.php"
}
break;
//continue with the same logic for other URL's
}
}
}
xhr.open(method, url, true);
xhr.onreadystatechange = callback(route);
xhr.send();
}
Then to call it:
<button onClick="doGet('about_us.php')">About Us</button>
<button onClick="doGet('faq.php')">FAQ</button>
<button onClick="doGet('contact_us.php')">Contact Us</button>
Ultimately, there are different ways to structure it to automate the process and reduce the amount of code that you need. A part of how you approach it is dependent on what you plan on doing after the request succeeds.

Using AJAX to execute a PHP script through a JavaScript function

I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)

Making a Javascript Loop request in rails view

I need to download a file from a link I am given. In order to do this I must make a get request to that link. It can have 3 states:
1. Code 200 and the download will begin once the request landed
2. Code 202 which means I must repeat the request because the file is being uploaded
3. Error code and I must create a dom element that shows that.
How it works:
I make a request to this rails action:
def by_month
export_form = Commissions::ByMonthForm.new(current_user)
if export_form.submit(params)
#export = export_form.export
else
show_errors export_form.errors
end
end
This in turn starts the file upload. Which I don't know when it's ready(depending on how big the file it is). Now I must create a javascript get request to a link that follows the indications I have given at the beginning of the post. And integrate it in the by_month.html.erb view from rails . The javascript I managed to write is:
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
httpGetAsync(theUrl);
}
else {
make_error_css();
}
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
However I don't think it works. Any ideas of how I can do this?(redirect_to_main and make_error_css are functions that I will implement myself later).
Update As per the comments below
Can you try this,
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
setTimeout(
makeRequest(theUrl),
3000);
}
else {
make_error_css();
}
}
}
//makeRequest(xmlHttp, theUrl);
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
function makeRequest(theUrl){
httpGetAsync(theUrl);
}
makeRequest() is where the request is made again if the status is 202.

Failing to get results using XMLHttpRequest

I'm trying to retrieve a file using XMLHttpRequest with Javascript. I'm having some problems getting the data of the sample file.
Here is the simple code:
<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
alert(xmlHttp.responseText);
}
xmlHttp.open("GET", "http://humanstxt.org/humans.txt", true);
xmlHttp.send(null);
</script>
With the above code I don't get any alerts. If I remove && xmlHttp.status == 200 then I get an empty alert, (I don't know why the server isn't giving the 200 status code). I tried different URLs but they all give out the same results.
Any thoughts on this?

Categories