Ajax call to iTunes Search API with nodejs javascript and express - javascript

multiple similar questions out there but I cannot figure out this iTunes api call.
here is part of my server.js
app.post('/look', function(req,res){
var encoded = encodeURIComponent(req.body.search);var itunesURL = 'https://itunes.apple.com/search?';
var apiURL = itunesURL + 'term=' + encoded + '&country=US&media=music&limit=5';
console.log("inside it!");
var search_value = req.body.search.body;
$.ajax({
type: 'POST',
url: 'https://itunes.apple.com/search?',
data: { term: search_value },
// kind:'song', trackName: "Upside Down",
dataType:"json", //nodejs knows its trying to send me json
data:JSON.stringify({ // puts into a json obj
"search": $("#search").val(),
}),
success:(function(result){ // result is json from node
console.log("YESASASAS")
$.each(result[5].trackName, function(key,value){
$('#search_results').innerHTML += "<div> Track Name: </div><div> "+ result.trackName + "</div> <div> Artist Name: </div> <div> "+ result.artistName + "</div>"
});
}),
error:function(e)
{
console.log("EROROROROR")
},
});
});
And some of my ejs file where I just have an input box and submit button to call the ajax api call
<form action="/look" id = "doit" method="post">
<!-- search box -->
<input type="text" placeholder="Search.." id="search"><br>
<!-- search button -->
<input type="button" action="/look" onclick="myFunction()" id="search_button" value="search">
<!-- the div that will contain our search results -->
<div id="search_results" style="padding:5px;"> Search Results: </div>
</form>
<p id="demo"></p>
Would love another method to do this other than the button calling the /look endpoint

Related

Returning response from JSON request using Ajax form on Laravel blade template

Ok, so i have a API based on Laravel, i'm trying to return its JSON response in a view with it's own form data.
HTML:
<form id="translate" action="translate" method="GET">
<div class="form-group"><label for="from" name="from">Translate from</label><select class="form-control" id="from"><option value="latin" selected="selected">Latin alphabet</option><option value="deepling">Jekhr</option></select></div>
<div class="form-group"><label for="message" name="message">Message</label><textarea class="form-control" id="message"></textarea></div>
<div class="form-group"><div class="form-row"></div></div>
<button class="btn btn-primary btn-block" type="submit">Translate!</button>
</form>
Base API URL:
http://localhost/translate?text=Hello World&method=Latin&pronunciation
So i'm trying to write a Ajax request to get JSON response with form data and display it on DOM table, like:
Translated Message = $json["translated"]
Pronunciation = $json["pronounce"]
Can anyone help me?
Edit:
Here's a solution that I got based on comment:
$("#translate").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "GET",
url: url,
data: form.serialize(),
success: function(data)
{
$('#translateTable tbody tr').remove();
$('#translateTable tbody').append("<tr><td>Request</td><td>" + data.requested + "</td></tr><tr><td>Translation</td><td>" + data.translated + "</td></tr><tr><td>Pronounce</td><td>" + data.pronounce + "</td></tr>");
$('#translateTable').show();
}
});
});

JavaScript Ajax and Mail/Ticket

I'm working on some project which there is a Bootstrap modal it sending tickets but I want also send email to the same person at the same time. But I'm missing something I guess.
<div class="modal-body">
<form onsubmit="return false" id="new_message_form" autocomplete="off">
<input type="hidden" name="form_type" value="new_message">
<input type="hidden" name="ticket_id" id="ticket_id" value="<?=$id;?>">
<div class="row">
<div class="col-md-12">
<div class="form-group no-margin">
<textarea class="ckeditor" id="message_new" name="message_new"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
Close
<button id="ticket_message_add" class="btn <?=$this->Configs->get_info("theme_buttons");?>">Send</button>
</form>
and it sends it to admin.js
$("#ticket_message_update").click(function (){
CKEDITOR.instances['message_update'].updateElement();
$("#UpdateMessageModal").modal("hide");
$.post(base_admin+"support", $("#update_message_form").serialize() ,function(data){
var data= JSON.parse(data);
if(data.update== 1){
$('#update_message_form')[0].reset();
location.reload();
}
});
});
So here is the thing. I have fully working ajax form with php mail system.(PHPMailer on github) When I click send button it automatically sending email to target mail addresses. But when I try to merge the ticket and email system seems not working but in logic it should be.
I'm adding function on button/input fields
onclick="AjaxFunction();"
<button id="ticket_message_add" onclick="AjaxFunction();" class="btn <?=$this->Configs->get_info("theme_buttons");?>">Send</button>
and adding my script also;
<script>
function AjaxFunction() {
var bilgi = {
userid: $('#user').val(),
ad: $('#ticket_id').val(),
soyad: $('#message_new').val()
}
$.ajax({
type: 'post',
url: 'gonder.php',
data: {query: bilgi},
success: function(result) {
}
});
}
</script>
And it needs to send the variables to "gonder.php" right? But it doesn't. Apparently I'm missing something.
Hi try to send the data like this:
function AjaxFunction() {
var bilgi = [{
userid: $('#user').val(),
ad: $('#ticket_id').val(),
soyad: $('#message_new').val()
}];
$.ajax({
type: 'post',
url: 'gonder.php',
data: {query: JSON.stringify(bilgi)},
success: function(result) {
}
});
}
then on the server side:
<?php
$data = json_decode($_POST["query"]);
// will echo the JSON.stringified - string:
echo $_POST["query"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach($data as $cityObject){
echo "userid: " . $cityObject->userid. ", ad: " . $cityObject->ad. "<br/>";
}
?>
Hope it Helps

How do I open data on a new page?

I am making a weather app and want my weather data to open on new page but it's currently opening underneath the search bar. I want it to redirect to another HTML-page with the weather data from the Javascript code when I push the search-button. How do I do that the easiest way?
This is my Javascript code that gets the weather data:
$(function() {
$("#city-form").on('submit', function(e){
e.preventDefault();
e.returnValue = false;
search($("#city-input").val());
});
function search(city){
$("#city").html("");
$("#description").html("");
$("#temp").html("");
$("#humidity").html("");
$("#wind").html("");
var query = {
'q' : city,
'lang': 'SE',
'units': 'metric',
'APPID' : '31fb7e0aa1f90896809571484a8b13cc'
};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
type: 'get',
async: true,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
dataType: "json",
data: query,
error: function (request, status, error) {
alert(JSON.parse(request.responseText).message);
console.log(request.responseText);
},
success: function (data) {
// Logs server reseponse
console.log(JSON.stringify(data));
// Sends data for presentation
present(city, data);
}
});
}
function present(city, data){
$("#city").html(city);
$.each(data.weather, function(i, weather) {
$("#description").append("<img class='w-icon' src='http://openweathermap.org/img/w/" + weather.icon + ".png' />");
$("#description").append(weather.description + " ");
});
$("#temp").html(data.main.temp + " °C");
$("#humidity").html("Luftfuktighet: "+ data.main.humidity + "%");
$("#wind").html("Vind: "+ data.wind.speed + " m/s");
}
});
And this is my HTML-code with the search bar and weather data:
<form id="city-form">
<input type="text" id="city-input" class="form-control" placeholder="Sök på stad" required>
<button type="submit" id="submit-btn" class="btn btn-primary">Sök</button>
<input type="reset" value="Reset">
</form>
<div id="weather">
<div id="city"></div>
<div id="temp"></div>
<div id="description"></div>
<div id="humidity"></div>
<div id="wind"></div>
</div>
I recomend you create another page that receives the city as a query param.
myPage?city="london"
Code for redirect:
function search(city){
window.location.href = 'myPage?city=' + city
}
If you prefer open in a new tab: Open a URL in a new tab (and not a new window) using JavaScript
On the new page you recover the city from params
How to get the value from the GET parameters?
And do the ajax request the same way you do now, you gonna move the display info to the new page:
<div id="weather">
<div id="city"></div>
<div id="temp"></div>
<div id="description"></div>
<div id="humidity"></div>
<div id="wind"></div>

JSON to javascript variable

I'm creating a login form with html,css and javascript.
I'm doing a POST to an API in order to receive some JSON with the identified username that I just submitted in the form.
If the email and password are correct, I receive the JSON with all the info from my API. The problem is that I don't know how to manipulate the info that I receive... I'd like to save the JSON I'm receiving through the POST to a variable and then be able to access the account type or the other properties of that object.
<form name="login" id="myForm" action="API_URL" method="post" class="form-signin">
<h3 class="form-signin-heading">Por favor inicie sesión</h3>
<label for="inputEmail" class="sr-only">E-mail</label>
<input type="email" name="email" class="form-control" placeholder="E-mail" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" class="form-control" placeholder="Contraseña" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Recordarme
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" id type="submit">Iniciar sesión</button>
</form>
After hitting submit, I receive the JSON like this:
!(https://imgur.com/a/wbUcp)
This is my JQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js%22%3E
$(document).ready(function() {
$('#myform').submit(function() {
$.ajax({
type: "POST",
url: '/form/',
data: {
email: $("#inputEmail").val(),
password: $("#inputPassword").val()
},
success: function(data)
{
if (data === 'Correct') {
var objeto = data.parse();
console.log(objeto);
}
else {
alert(data);
}
}
});
});
});
</script>
Can anyone please point me in the right direction?
If you are using Javascript try like this:
$.ajax({
type: "POST",
url: '/form/',
data: {
email: $("#inputEmail").val(),
password: $("#inputPassword").val()
},
success: function(response){
var data = response;
contactData = JSON.parse(data);
console.log("ID: " + contactData.id);
console.log("ID: " + contactData.user_type_id);
console.log("ID: " + contactData.first_name);
console.log("ID: " + contactData.last_name);
console.log("ID: " + contactData.email);
console.log("ID: " + contactData.password);
},
failure : function(data){
alert('Server Connection failed');
},
error : function(request,error){
alert(error);
}
});
You can get Json in array in php with
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
You are posting data and it will be received in string format.If you are only dealing with JSON then you can use JSON parser like this
let body = JSON.Parse(req.body);
Now body variable will contain an object and you can access properties easily.If you are using nodeJs on server side than body-parser middle ware can be used also.Let me know in comment if there is something contrary.
You need to invoke the call using JavaScript & AJAX.
Add an OnClick event listener to the submit button and call handleLoginClicked().
Collect all variable from the inputs and use ajax to post to the url.
Get back the response and parse the JSON, assign to a javascript variable.
You can use jQuery for example to do so: jQuery.Post

How to pass dynamic content from form using ajax

I need to pass data filled in a form, so it would be sent in a POST request using the Ajax code.
Here is my HTML form:
<!DOCTYPE html>
<html>
<head>
<title>Alteon Cluster Management</title>
<script src="jquery-1.11.2.min.js"></script>
<script src="alteon1.js"></script>
</head>
<body>
<button id="configR1btn">Configure Server 1</button> <button id="configR2btn">Configure Server 2</button>
<form>
<section>
<header>
<h1>R Servers</h1>
</header>
Server 1 IP Address: <input type ="text" name="firstRServerIP"><br><br>
Server 1 Name: <input type ="text" name="firstRServerName"><br><br>
Server 2 IP Address: <input type ="text" name="secondRServerIP"><br><br>
Server 2 Name: <input type ="text" name="secondRServerName"><br><br>
</section>
</form>
</body>
</html>
And here is my Ajax code:
$(document).ready(function(){
$('#configR1btn').click(function (){
var t = $(this);
//var t.closest(".form").find(".firstRServerIP").val();
var firstRServerIP = t.prev(".firstRServerIP").val();
var dataString = '{\n"State":"2"\n"IpAddr":" + firstRServerIP"\n}';
$.ajax({
method: 'POST',
url: 'https://Default_Generated_Alteon_BBI_Cert/config/SlbNewCfgEnhRealServerTable/R1',
//crossDomain: true,
data: dataString,
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
});
});
For example, I fill the data '1.2.3.4' in the "firstRServerIP" part of the HTML form, and click the "Configure" button.
The POST request data should look like this:
{
"State":"2"
"IpAddr":"1.2.3.4"
}
Instead, I get:
{
"State":"2"
"IpAddr": " firstRServerIP"
}
What is wrong with my code?
A help will be appreciated.
Thanks.
You can correct it like that:
var dataString = '{\n"State":"2"\n"IpAddr":"' + firstRServerIP + '"\n}';
But I would suggest you to do that instead:
var dataString = JSON.stringify({
State: '2'
IpAddr: t.prev(".firstRServerIP").val()
})
;
You can also do the following if you want all the values of your form:
var dataString = $('#my-form').serialize();
in this case set the good name attributes in your inputs (ie. State and IpAddr) and use <form id="my-form">
I changed the format of your dataString object so that it's more readable and also used a different jQuery selector to get the value from the proper input field.
$('#configR1btn').click(function () {
var firstRServerIP = $("[name='firstRServerIP']").val();
var dataString = {
"State":"2",
"IpAddr": firstRServerIP
};
console.log(dataString);
This will output:
You can play with this JSFiddle. Open your console to see the result of the click.
Here is what you need. Please bear in mind that you do not have an element with class="firstRServerIP"; therefore $('.firstRServerIP').val() will always return undefined.
$('#configR1btn').click(function (){
var f = $('form').first(),
firstRServerIP = f.find(':text[name=firstRServerIP]').val(),
dataString = JSON.stringify({
State: "2",
IpAddr: firstRServerIP
});
dataString = dataString.replace(/([\{,])/g,'$1\n').replace('}','\n}');
$.ajax(...........
PROOF OF CONCEPT
$('#configR1btn').on('click',function() {
var f = $('form').first(),
firstRServerIP = f.find(':text[name=firstRServerIP]').val(),
dataString = JSON.stringify({
State: "2",
IpAddr: firstRServerIP
});
dataString = dataString.replace(/([\{,])/g,'$1\n').replace('}','\n}');
alert( dataString );
//ajax call here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="configR1btn">Configure Server 1</button> <button id="configR2btn">Configure Server 2</button>
<form>
<section>
<header>
<h1>R Servers</h1>
</header>
Server 1 IP Address: <input type ="text" name="firstRServerIP"><br><br>
Server 1 Name: <input type ="text" name="firstRServerName"><br><br>
Server 2 IP Address: <input type ="text" name="secondRServerIP"><br><br>
Server 2 Name: <input type ="text" name="secondRServerName"><br><br>
</section>
</form>

Categories