PHP backend in Spotify App not working - javascript

I'm trying to make a spotify app that takes in user information and sends it to an SQL database. However, I don't want this to be done using ajax since I want the submission of the information to move the user to a new page while the information is posted to the database in the background.
Here's my code so far:
function complete2() {
var name = document.getElementById("inputname").value;
var form = '<form action="http://site.net/dbconnect.php" method="post" style="display:none">' + '<input type="text" name="name" value="' + name + '">' + '</form>';
$('body').append(form);
$(form).submit();
}
</script>
</head>
<body>
<form id = "submitform" name = "submitform" action = "index.html" method = "POST" onsubmit = "complete2();" >
Name: <input type = "text" id = "inputname"> <br>
<input type = "submit" value = "Create">
</form>
</body>
</html>

So i know you dont want to use AJAX but if you want to load a differnt html file in your local app and Spotify doesnt respect a location header to an internal resource then youre stuck with ajax. However you can make it simialr to what would happen with a standard post something like:
$(function(){
$('#submitform').submit(function(e){
e.preventDefault();
$.post(
$(this).attr('action'),
{'inputname': $(this).find('#inputname').val()},
function(){ window.location.href = 'sp://yourapp/nextpage.html'; }
);
});
});

Here is a sample to get data
$.getJSON("http://www.exx.com/getjsondata.php", function (data) {
parsetheresponse(data) ;
}
Here is a sample to post data (still in JSON)
$.post("http://www.exx.com/postdataspotify.php", { albumname: "test", username: "test2" });
Hope it will help.
Don't forget to put http://www.exx.com in manifest file.

Related

Send JavaScript File() by email onclick

I have a script making a file from data (from a form or not). I have access to the URL to download the file in any browser, using window.URL.createObjectURL. But I would like to add a button to send the file by email. (I have a server and PHP).
Here is my code:
First creating File from 'test':
function makeFile(text) {
var test =
"Here is my " + text;
var data = new File([test], { type: "text/plain" });
if (myFile !== null) {
window.URL.revokeObjectURL(myFile);
}
myFile = window.URL.createObjectURL(data);
return myFile;
}
Now my unsuccessful attempt:
<form action="emailthijob.php" method="post">
<a class="download hide" id="sendbyemail" onclick="myFile.submit()";>⇧ Email</a>
</form>
So I would appreciate help with 1/button to click and send mail, 2/ PHP code to actually get the result.
Thank you very much for your help,
Best,
--Fred

JavaScript searching for a user based on their username?

I've created a function that uses getJSON to retrieve a data set found on an API website of registered Github Users
<!DOCTYPE html>
<!---->
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function(){
var user = $('#search').val();
$.getJSON("https://api.github.com/users/" + user)
.done(function(data) {
var br = "<br>";
var p = $("<p id='users'></p>");
var name = "Username: "+ user.login + br;
var pic = "Avatar Picture:" + br + "<img src='"+user.avatar_url+"'/>" +br;
var homeURl = "Homepage URL: "+"<a href='"+user.html_url+"'>"+user.html_url+"</a>" +br;
var location = "Location: "+"Null" +br;
var admin = "Admin: "+user.site_admin;
p.append("<p>"+ name + pic + homeURl + location + admin +"</p>");
$("#results").empty().append(p);
})
.fail(function(jqXHR) {
console.log("Error: " + jqXHR.status);
})
.always(function() {
console.log("Random Users Request finished");
});
});
</script>
</head>
<body>
<input id="search" type = "text">
<button>Search</button>
<div id="results"></div>
</body>
</html>
As you can tell I have began to modify it so that instead of displaying all users it only displayers the user that has been searched
var user = $('#search').val();
$.getJSON("https://api.github.com/users/" + user)
This snippet of code grabes the username entered in the text area and passes it to the getJSON method in the Url. An example URL is "https://api.github.com/users/mojombo", thus if the user enters "mojombo" then their profile would appear
This function is accessed via a button
<input id="search" type = "text">
<button>Search</button>
However when you search for the example user, in fact any user no data is displayed and a blank screen remains
You have not connected your function to the button.
As it stands, it runs before the user has typed anything into the search field (thus requesting "https://api.github.com/users/" because user at that time is an empty string) , and won't react at all to a button click.
Instead of just
$(function(){
/* code */
});
do
$(function(){
$('button').on('click', function(){
/* code that runs when button is clicked */
})
});

how to acess form with external js files? how to hide sensitive content of js from client?

I'm using emailjs to send email through my free subdomain website.There are two problems with it
1). My emailjs account-id, service-id and template-id is getting public so anybody can access it and send email through it.
2). to solve it I used following code but it steel appears in browser "inspect Element"(Developer tool).
<?php echo "
<script>
(function(){
emailjs.init(my user id);
})();
</script>" ; ?>
<?php
echo "<script src='js/formfilled.js'></script>";
?>
now my form submiting button is like this
<button onclick="email();">
Send
</button>
now my formfill file is like this
var myform = $("form#myform");
function email(){
var service_id = "default_service";
var template_id = "xxxxxxxxx";
myform.find("button").text("Sending...");
emailjs.sendForm(service_id,template_id,"myform")
.then(function(){
alert("Sent!");
myform.find("button").text("Send");
}, function(err) {
alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
myform.find("button").text("Send");
});
}
problem is that when I click the button rather than sending an email it reload the page .
Sorry if it is too silly i am totally beginner and Thanks in advance.
UPDATE
it is working if i put the code in the same file(not using external js)
code:--
<head>
<script type="text/javascript">
(function(){
emailjs.init("xxxxxxxxxxxxxxxxxxxxx");
})(); </head>
</script>
<body>
<!-- form is here-->
<script>
var myform = $("form#myform");
myform.submit(function(event){
event.preventDefault();
// Change to your service ID, or keep using the default service
var service_id = "default_service";
var template_id = "xxxxxxxxxxxxxxxxxxx";
myform.find("button").text("Sending...");
emailjs.sendForm(service_id,template_id,"myform")
.then(function(){
alert("Sent!");
myform.find("button").text("Send");
}, function(err) {
alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
myform.find("button").text("Send");
});
return false;
});
</script>
</body>
but if i put this code in formfilled.js it is not working.
what would be the reason behind it?
Answer:
to use
event.preventDefault();
and loading the file before the button is loaded.

Executing php script on button click and returning value by ob_start

I have button which in enclosed by <a> tag. When clicked, it executes redirect.php script.
login.php - contains
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
redirect.php contains twitter authentication code. If authenticated successfully then gives id and name. I want to fetch these both value in index.php
Using ob_start(); I can receive values from php script to JS function via json.
But I am confused about how to manage the code in index.php to execute script on button click and receiving these two value also.
redirect.php
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$notweets = 5;
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
$id = $content->{'id'};
$name = $content->{'name'};
?>
Please let me know if you need further explaination.
Bottomline:
Rather executing redirect.php script on link click, I want it to execute via function on button click event.
Getting id and name from redirect.php to index.php after redirect script executed
I already have session_start() to manage the twitter session. So dont want to mess up using mutiple session if not necessary ..
UPDATE after david's answer
<body>
<input type="button" value="Run somePHPfile.php" id = "b1" />
<script>
$('#b1').click(function () {
window.location.href = 'redirect.php';
$.get('index.php', function(data) { //If I put this out side click then it gives undefined value for name and id before redirect.php gets executed
// data.id is the id
var id= data.id;
var name = data.name;
alert(name);
});
});
</script>
</body>
Apologize to say:
On button click redirect.php script executed. redirect.php includes other files, which finally reach to index.php. And index.php returns name and id.
So is this enough to manage it : $.get('index.php', function(data) { ... }
To bind to a click event of an HTML button, you would use JavaScript. Since you tagged the question with jQuery, I'll assume its use. The event handler would look something like this:
$('#loginButton2').click(function () {
window.location.href = 'redirect.php';
});
Note: This simulates an anchor click effectively. If you instead want to more closely resemble an HTTP redirect, you might want to use this instead:
window.location.replace('redirect.php');
As for the id and name values, how exactly does this flow return the user to index.php in the first place? Your redirect.php has, well, a redirect (though not all code paths result in that) so it kind of assumes non-AJAX interaction. (I think XHR follows redirects sometimes, but the behavior is different from one browser to another.)
If the redirect isn't terribly important and you just want to make an AJAX call to redirect.php, then you can do that with a simple AJAX request:
$.get('redirect.php');
In order to get those values back to the page, they'll need to be emitted from redirect.php. Something like this:
echo json_encode((object) array('id' => $id, 'name' => $name));
Then in the client-side code you would have those values available in the AJAX callback:
$.get('redirect.php', function(data) {
// data.id is the id
// data.name is the name
// use these values client-side however you need
});
<script>
$("#loginButton2").on('click',function(){
window.location.href="redirect.php";
});
</script>
and in redirect.php file
$_SESSION['id']=$id ;
$_SESSION['name']=$name;
and also
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
to
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>

I am having difficulty reaching a web service. Any ideas what changes are needed on my code?

I have struggled with this task for so long that I am hoping for a reprieve.
We have a web service called Validate on a separate server/domain.
Due to same domain restrictions, I came up with proxy server (code) to work around it.
The code below called Validate.asp, points to the webservice:
Set http = Server.CreateObject("msxml2.ServerXMLHTTP")
http.Open "POST", "http://servername1/folder1/folder2/folder3/Validation/Validate", False
http.setRequestHeader "Content-type","application/x-www-form-urlencoded"
http.Send Request.Form
Response.Write http.ResponseText
Response.End
%>
Then the code markup below invokes Validate.asp.
<!DOCTYPE html>
<html>
<body>
<form>
Enter name: <input id="user" /><br/>
Enter Pass: <input id="pass" /><br/>
<input type="button" value="Get web response via AJAX" onclick="ajaxViaProxy()" />
</form>
<hr/>
Ressponse: <div id="result"></div>
<script type="text/javascript">
function ajaxViaProxy( )
{
var uname = document.getElementById("user").value;
var upass = document.getElementById("pass").value;
var http = new XMLHttpRequest();
http.open("POST", "Validate.asp", true );
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.onreadystatechange=function()
{
if (http.readyState==4 && http.status==200)
{
document.getElementById("result").innerHTML =
"Response from web server was '" + http.responseText + "'";
}
}
http.send("username=" + encodeURIComponent(uname)
+ "&password=" + encodeURIComponent(upass));
}
</script>
</body>
</html>
If everything goes well, we should get response similar to this one below:
{"Value":{"TokenId":35,"LoginName":"validUser","Created":"2013-12-03T09:53:35","Expires":"2013-12-24T09:53:35","LastUsed":"2013-12-03T09:53:35"},"Status":0,"Message":null}
This is the exact response we get when I paste the code below into an address bar and hit the enter key:
http://servername/folder1/folder2/folder3/Validation/Validate?data={"User":"validUserName","Password":"validPassword"}
However, when I use the markup to invoke proxyValidate.asp, rather than get the response with token, I get the following:
{"Value":null,"Status":2,"Message":"Invalid username or password"}
Does anyone know what I need to change in the markup or in proxyValidate.asp so that when I run the code, I get a properly formatted URL string like this below?
http://servername/folder1/folder2/folder3/Validation/Validate?data={"User":"validUserName","Password":"validPassword"}
Thanks alot in advance

Categories

Resources