Display openweathermap (API) data on website using AJAX and PHP - javascript

when i want enter a city here, nothing happens, no error in my console, i don't know why
this is my code :
ajax.js
$(document).ready(function(){
$('#submitLocation').click(function(){
//get value from input field
var city = $("#city").val();
$.post('PHP/controller.php', {variable: city});
//check not empty
if (city != ''){
$.ajax({
url: "PHP/router.php",
// url :"http://api.openweathermap.org/data/2.5/weather?q=" + city +"&lang=fr"+"&units=metric" + "&APPID=697edce53ba912538458a39d776ca24e",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
console.log(data.weather[0].description);
console.log(data.main);
console.log(data.main.temp);
var information = show(data);
$("#show").html(information);
}
});
}else{
$('#error').html('Field cannot be empty');
}
});
})
function show(data){
return "<h3>Témpérature: "+ data.main.temp +"°C"+"</h3>" + "<h3>"+ data.weather[0].description +"</h3>";
}
this is my router.php, my js call the router
<?php
require('../PHP/controller.php');
if (isset($_GET['city'])) {
return getWeatherCity($_GET['city']);
}
else {
echo'Error';
}
?>
i know that i can do this only with js or only with php but i want use both of them.

Do you have any request happening in the "Requests" tab of your DevTool?
You should see a request towards PHP/router.php and the associated status code. Given that you might collect clues to debug what's going on.

Related

Is there a way to display a message when no valid input is displayed?

Still pretty new at all this, but i was wondering if there is a way to display an error message if no valid input (404 message) is displayed.
The error message works if nothing is entered into the input box, but if the user doesn't spell for example 'London' correctly, the console displays a 404 message and i don't know how to display an error message for that, any help would be appreciated, Thanks.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
$('#submitweather').click(function(){
var city = $("#city").val();//declares variable name "city"
if(city !== ''){ //if the input box is not empty
$.ajax({
//first part, web address. second part, global variable. third part, UK uses metric. fourth part, API key.
url: 'http://api.openweathermap.org/data/2.5/weather?q='+city+"&units=metric"+"&APPID=???",
type: "GET",
datatype: "JSONP", //JSON with padding
success: function(data){
//console.log(data); test worked
var widget = show (data);
$("#show").html(widget);
$("#city").val('');} // empties input box when finished
});
}
else if(city == ''){
$("#error").html('Cannot Be Empty').fadeOut(10000);
}
else (){
}
});
});
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Use $.ajax error handler which will catch not found or unauthorized and such, like this:
$('#submitweather').click(function(){
var city = $("#city").val(); //declares variable name "city"
if(city !== ''){ //if the input box is not empty
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q='+city+"&units=metric"+"&APPID=???",
type: "GET",
datatype: "JSONP", //JSON with padding
success: function(data){
// You could check the API response as well
if (data.cod == 200){ // API specifies "cod" for the response code.
$("#show").html(data);
$("#city").val('');
}else{
$("#error").html(data.cod+" "+data.message).fadeOut(10000);
}
},
error: function(jqXHR, textStatus, errorThrown){
$("#error").html(textStatus+" "+errorThrown).fadeOut(10000);
}
});
}
else if(city == ''){
$("#error").html('Cannot Be Empty').fadeOut(10000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" id="city" value="Londron" />
<button id="submitweather">Check weather</button>
</div>
<h2>Result</h2>
<div id="show"></div>
<h2>Error</h2>
<div id="error"></div>

Codeigniter & Ajax - Condition statement in javascript

Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.

AJAX is not working in macOS WebView

I have created a WebView for macOS app and it contains one AJAX call. The same WebView is working fine when the app calls my local URL, but when it calls the live URL, the AJAX call is not working.
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: 'http://mywebsite.com/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
My local PHP version is 7.1.8 and my live server PHP version is 5.4.
Change your function to onclick of checkbox directly,put this code in your checkbox onclick="MyFuncion",why I'm telling this is for web view we need to give exact command in exact position it's not a browser
And your AJAX call will be like below,
function myFunction()
{
var pripolcheck = $("#pripolcheck").val();
var app = $("#app").val();
var user_id = $("#user_id").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1='+ pripolcheck + '&app1='+ app + '&user_id1='+ user_id;
if(pripolcheck=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxformsubmit.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$("input.pripolcheck").attr("disabled", true);
}
});
}
return false;
}
"My local PHP version is 7.1.8 and my live server PHP version is 5.4."
I think this explains everything.
However, try setting an absolute URL in your call:
url: 'ajaxformsubmit.php',
to
url: '/ajaxformsubmit.php',
Or whatever the actual path would be. Just a single slash will give you
http://wherever.com/ajaxformsubmit.php
if u use same site url plz use relative path not absolute path then its ok.
if use defrant site url plz comment me so give me new solution
PLZ try
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: '/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});

javascript missing a url parameter during redirection

my website has an option of country like for different country the website layout is different. it is running on the basis of sessions if session is not set the user will be redirected to index to select a country then will be redirected from the page where he originally came from. here's the code
my session_check_client.php file that is included in every file except index
<?php
session_start();
if(!isset($_SESSION['country']))
{
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
header("location:index.php?return_uri=$actual_link");
}
?>
now what happens is when i go back to home page i wanna check whether this requested has some return parameter or just user has visited he website for the first time. there are two button for two countries of which i am showing the code.
function canada(){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=canada',
success: function (data) {
var $_GET = <?php echo json_encode($_GET);?>;
if($_GET){
//window.location.href=$_GET['return_uri'];
alert($_GET['return_uri']);
}
else {
window.location.href = "home.php";
}
}
});
}
function us(){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=us',
success: function (data) {
var $_GET = <?php echo json_encode($_GET);?>;
if($_GET){
//window.location.href=$_GET['return_uri'];
alert($_GET['return_uri']);
}
else {
window.location.href = "home.php";
}
}
});
}
now the problem is when i am alerting the value of $_GET['return_uri'] it is giving me a false value
e.g my return_uri value is http://localhost/interfold/products2.php?category=Aprons&id=57725599688 it actually shows the whole value in return_uri in index page like http://localhost/interfold/products2.php?category=Aprons&id=57725599688 but when is get the url value using javascript it is onlye giving me the value http://localhost/interfold/products2.php?category=Aprons it is missing the $ and afterwards parts!!! any recommendations?
Since you are only using super global variables, you can directly print a JS variable above the function you are describing:
var actual_link = "<?php echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>";
function postCountry( country ){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=' + country,
success: function (data) {
if(actual_link){
//window.location.href=actual_link;
alert(actual_link);
}
else {
window.location.href = "home.php";
}
}
});
}
postCountry('us');
postCountry('canada');

Make page refresh if successful login with ajax/jquery

Ajax code
$("#login_btn").click(function() {
var url = "core/login.php";
$.ajax({
type: "POST",
url: url,
data: $("#sr").serialize(),
success: function(data) {
var responseData = jQuery.parseJSON(data);
$('.oops').html('<div class="error">'+responseData.oops+'</div>');
alert(responseData.good);
if(responseData.good === 1) {
alert(good)
location.reload();
}
}
});
});
Php code if everything passes
else {
$_SESSION['id'] = $login;
$good = 1;
exit();
}
How come it's not freshing the page with location.reload? Should I be using .done .try?
Dont refresh, the whole idea of using ajax is that you dont need to.
You can set your sessions in the ajax php script and pull new content based on the change in session.
That being said, you are missing a ';' at
alert(good);

Categories