How do I open data on a new page? - javascript

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>

Related

Ajax call to iTunes Search API with nodejs javascript and express

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

laravel ajax unexpected end of json input

Hello guys i am desperate i am not getting completly this syntax / concept of Ajax.
I have 2 forms on my page. Based on the value of the hidden field a certain logic in my controller will be executed. Its simple actually -- i thought. I am trying to pass an array from my ajax to my controller and then passing it back to my view. I know it doesnt make much sense. But i am trying to understand how that works. The first logic gets executed but the other one gets me this error:
jqXHR is : [object Object] textStatus is : parsererror errorThrown is : SyntaxError: Unexpected end of JSON input
Why is that ? Can you guys please give me an advice.
Update
I tried not to put the whole code and just reduce it to the main question. But since it caused confusion of the rootcause i will show the whole code of the parts which might be relevant. I edited the question to the below.
BLADE
<center>
<div class="col-md-12">
<h3>xlsx, xls, ods, csv to Text</h3>
<form id="xlsForm" enctype="multipart/form-data">
#csrf
<input type="file" name="excelfile" />
<input name ="loadSubmit" id="loadSubmit" type="submit"/>
<input type ="hidden" name="load" value="0">
</form>
</div>
</center>
<div class ="row">
<div class ="col-md-3">
<div class="container mt-5">
<h2 id="words" class="mb-4">Skills found</h2>
</div>
<form id="xlsFormUpdate" enctype="multipart/form-data">
<input type ="hidden" name="load" value="1">
<div id="inner">
</div>
<input name ="updateSubmit" id="updateSubmit" type="submit"/>
</form>
</div>
<div class ="col-md-9">
#include('layouts.partials.datatable')
</div>
</div>
Controller:
if ($request->input('load') == '0') {
//some code -- this works fine
return response()->json($data); //This data can be send - no problem
} elseif (($request->input('load') == '1')) {
$data = $request->post('checkbox_array');
return response->json($data); // i tried json_encode too .. not working.
}
Jquery code
$(document).ready(function(){
$('#xlsForm').submit(function uploadFile(event){
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function (response) {
$("#inner").empty();
$.each(response,function(index,value){
$("#inner").append
('<div class="row">' +
'<div class="col-xs-2">'+
'<input type="checkbox" class="'+value+'" value="'+value+'" name="checkbox[]" checked > <label style="font-weight: bold" for="skillChoice_'+index+'">'+value+' </label>' +
'</div>'+
'<div class="col-xs-1">'+
'<input class="'+value+'" type="number" name="weight[]" min="1" max="3" value="1"> '+
'</div>'+
'</div>');
});
}
});
});
$('#xlsFormUpdate').submit(function uploadFile(event) {
event.preventDefault();
var checkbox_array = [];
$('input[type=checkbox]').each(function (index,value) {
if (this.checked)
{
checkbox_array.push(1);
}
else {
checkbox_array.push(0);
}
});
let checkbox_s = JSON.stringify(checkbox_array)
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: "POST",
data: {checkbox_array:checkbox_s},
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (response) {
alert('The Response is ' + response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('jqXHR is : ' + jqXHR
+ 'textStatus is : ' + textStatus
+ ' errorThrown is : ' + errorThrown);
},
})
});
});
When using ajax submit event to send data to controller, the data in the field data: {checkbox_array:checkbox_s}, will be send to the controller. Since the input field load was never sent, the elseif (($request->input('load') == '1')) clause was never true and the controller was never going into that section and was never returning the right response. The data had to be changed like this var my_datas JSON.stringify({mydata:checkbox_array, load: "1"}); and then in ajax the data could be send like data:my_datas. In controller the field load can then be processed.

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();
}
});
});

Click function won't update information on page

I want my submit button to pull the value from the input box next to it, change the '#' to a '-' and then pass it on so that I can pull information respective to that user and then populate the field in HTML. But the page just refreshes and a '?' gets added to the url.
$("#usernameBtn").click(function() {
var unTouchedID = $("#userid").val();
var usrID = unTouchedID.replace("#", "-");
$.ajax({
url: "https://owapi.net/api/v3/u/" + usrID + "/stats",
dataType: 'json',
data: "",
success: function (data) {
$('#heroStats_elims').html('<h2>'+ data.us.stats.competitive.average_stats.eliminations_avg + '</h2>');
//var avgElims = //data.us.stats.competitive.average_stats.eliminations_avg
}
}); });
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Battle.net Tag" id="userid">
</div>
<button type="submit" class="btn btn-default" id="usernameBtn">Submit</button>
You need to use event.preventDefault(); as #Andrew mentioned to prevent the default behavior of submitting the page.
$("#usernameBtn").click(function(e) {
e.preventDefault();
var unTouchedID = $("#userid").val();
var usrID = unTouchedID.replace("#", "-");
$.ajax({
url: "https://owapi.net/api/v3/u/" + usrID + "/stats",
dataType: 'json',
data: "",
success: function (data) {
$('#heroStats_elims').html('<h2>'+ data.us.stats.competitive.average_stats.eliminations_avg + '</h2>');
//var avgElims = //data.us.stats.competitive.average_stats.eliminations_avg
}
});
});
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Battle.net Tag" id="userid">
</div>
<button type="submit" class="btn btn-default" id="usernameBtn">Submit</button>

Knockout Json Mapping Issue

Hi I have a View Which Contains a ADDBasicDetailsForm (This JSP view is rendered using spring MVC)
BasicDetailView.jsp
<div data-bind="if: profileDto.basicDetailsDTO">
<div class="basicDetails">
Contact No :
<b data-bind="value: profileDto.basicDetailsDTO.contactNo"> </b>
contactMailId :
<b data-bind="value: profileDto.basicDetailsDTO.contactMailId"> </b>
</div>
</div>
<form id="BasicDetailsform" method="POST">
<fieldset class="contactMailId">
<input id="contactMailId"
type="text" placeholder="Mail Id" maxlength="32"
name="contactMailId"></input>
</fieldset>
<fieldset class="contactNo name">
<input id="contactNo"
type="text" placeholder="contactNo" maxlength="32" name="contactNo"></input>
</fieldset>
<fieldset class="buttons">
<button class="saveactionbutton" type="submit">SAVE</button>
</fieldset>
</form>
</div>
Inially contact no and conatct mail ID is not shown in UI. It should be shown when i submit the form and i am using knockout for automatic UI referesh.But It is not working
BasicDetails.js
function BasicViewModel() {
var self = this;
}
var viewModel = new BasicViewModel();
$(document).ready(function(){
$("#BasicDetailsform").submit(function(e)
{
var form = $(this);
e.preventDefault(); //STOP default action
var input = '{';
input += '"contactMailId":"'+$('#contactMailId').val()+'",';
input += '"contactNo":"'+$('#contactNo').val()+'"';
input += '}';
alert(input);
$.ajax({
type: "POST",
dataType: "json",
url : "addBasicDetails",
contentType: "application/json; charset=utf-8",
data: input,
dataFilter: function (response) {
return response;
},
async:false,
success: (function(data, textStatus, jqXHR) {
alert("ajax Success");
form.hide();
data = ko.toJSON(data);
alert("JSON Data in Alert"+data );
ko.mapping.fromJSON(data, {}, self);
ko.applyBindings(viewModel);
}),
error : function(data,textStatus,error){
alert("ajax failure");
}
});
});
});
My JSON response from server
{
"basicDetailDTO":{
"contactNo":"86878",
"contactMailId":
"rahuljain#gmail.com"
}
}
After the Form submission details are not getting reflected in my jsp view .
Please let me know where is the issue in my code.

Categories