OMDb API not working in javascript - javascript

I am using OMDb API to fetch Title, Year and Runtime of movie. These should appear on the page as soon as it loads.I used j query ajax for this. But it does not work.
As soon as the page loads it shows undefined written there. Where I am making the mistake??
I am new to j query ajax and API's so any help would be appreciated.Thanks in advance :)
<! doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">< </script>
<script type="text/javascript">
window.onload=function()
{
$.ajax({
url: "http://www.omdbapi.com/?t=spiderman&y=&plot=full&r=json",
crossDomain: true,
dataType: "json",
success: fetch
});
}
//For fetching data on success
function fetch(e){
var result="";
$.each(e,function(value){
result+="<p>" +value.Title +"</p>";
result+="<p>" +value.Year +"</p>";
result+="<p>" +value.Runtime +"</p>";
});
$('#movie').html(result); //For storing result in html
}
</script>
</head>
<body>
<p id="movie"></p>
</body>

in order to get all returned values from the object, you need to get each property by key and value,the returned json looks like this:
{"Title":"Spiderman","Year":"1990","Rated":"N/A","Released":"N/A","Runtime":"5 min","Genre":"Short","Director":"Christian Davi","Writer":"N/A","Actors":"N/A","Plot":"N/A","Language":"German","Country":"Switzerland","Awards":"N/A","Poster":"N/A","Metascore":"N/A","imdbRating":"5.7","imdbVotes":"90","imdbID":"tt0100669","Type":"movie","Response":"True"}
so just call e.Title to get title or loop into object using $.each with key and value as arguments.
first argument is the property name(KEY) and second is the value.
$.each(e,function(key,value){
result+="<p>"+ key + " : " + value +"</p>";
});
<! doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">< </script>
<script type="text/javascript">
window.onload=function()
{
$.ajax({
url: "http://www.omdbapi.com/?t=spiderman&y=&plot=full&r=json",
crossDomain: true,
dataType: "json",
success: fetch
});
}
//For fetching data on success
function fetch(e){
var result="";
//where keys are attribute names and values are their values
$.each(e,function(key,value){
result+="<p>"+ key + " : " + value +"</p>";
});
$('#movie').html(result); //For storing result in html
}
</script>
</head>
<body>
<p id="movie"></p>
</body>

Related

not able to pass array from JS to PHP with AJAX

Hello am trying to pass an array from my JS script file to another file called serverSide.php so i can print the array in that file and do something with it , am having no issue sending the data and getting a response using the AJAX/JSON the problem i am getting "Notice: Undefined index: theArray in C:\xampp\htdocs\Ajax test\serverSide.php on line 2" when i try to print_r the array i sent ?
**Here is my JS code **
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body>
<h1>Testing AJAX techniques</h1>
<script>
let myArray = [1,2,3];
console.log(myArray);
let myArray1 = JSON.stringify(myArray);
console.log(myArray1);
$.post({
method: 'POST',
url: 'serverSide.php',
data: {theArray: myArray1},
success: function(res) {
console.log(res);
}
})
</script>
</body>
</html>
And this is the serverSide.php file code where i try to print the array
<?php
$test = json_decode($_POST['theArray']);
print_r($test);
?>
Thank you for any help

how to use ajax to put value from javascript variable into a php variable

I need to get the value of a javascript variable and put it into a mysql database. I am trying to use jquery ajax function in (test.html) to Post the variable to a separate PHP file (external.php). I'm not sure why it's not working, I would appreciate any insight. Here are my two files:
Here is test.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function () {
var longitude = "print a longitude";
$.ajax({
url: "external.php",
method: "POST",
data: { "longitude": longitude }
});
});
</script>
</body>
</html>
And here is external.php:
<?php
$longitude = $_POST['longitude'];
echo json_encode($longitude);
?>
The code below works perfectly fine for me:
The external.php file:
<?php
header('Content-Type: application/json');
$longitude = $_POST['longitude'];
echo json_encode($longitude);
?>
The test.html file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function () {
var longitude = "print a longitude";
$.ajax({
url: "external.php",
method: "POST",
dataType: "json",
data: { "longitude": longitude },
success: function(data){
console.log(data);
}
});
});
</script>
</body>
</html>
Also, make sure you are not running your file as:
file:///C:/Users/XXX/Desktop/XAMPP/htdocs/test.html
If you run it like this you would get this error:
XML Parsing Error: no root element found
Location: file:///C:/Users/XXX/Desktop/XAMPP/htdocs/external.php
Line Number 5, Column 3:
What you need to do is run Apache and then run the file as:
http://localhost/test.html
Below is the screenshot of what I get:

How to send DELETE request to node with button and jquery?

I have a web page that's showing a "ressource" (aka just one entry from a mongodb collection), and on that web page I want to have a button "delete" that will send a "delete" request to the server to the correct route.
The router works (so when I use an external program to send a delete request, the entry is deleted), but I want to the same with a link.
Apparently, after doing some research, I would need to use an ajax function to do that, as in this post. The problem is that I can't make it work (probably because I just started using jquery), it seems nothing happens when I click on the button. But if I try a simple alert(), it works ('#delete').on('click',function(){ alert('clicked')}); .
So
Here's the basic html :
$('#delete').on('click', function() {
alert('click');
//here would be the code to send the DELETE request ?
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Storystrap Template</title>
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- bower:css -->
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css" />
<!--endbower-->
<!-- bower:js -->
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/printplugin.min.js"></script>
<!--inject:js-->
<script src="/js/app.js"></script>
<script src="/js/modernizr-custom-touch.js"></script>
</head>
<body>
<button class="delete" data-target="/" data-method="DELETE" data-disabled="true">Delete Ressource</button>
</body>
</html>
And here is the route code in node.js (this code works if I manually send a DELETE request), the id is supposed to be in the link of the page
ressourcesRouter.route('/ressources/t/:ressourcesId')
// permet d'afficher UNE ressource spécifique
.get(function(req,res){
var returnRessource = req.ressource.toJSON();
res.render('ressourceView', {
title: 'Ressources',
ressource: returnRessource
});
})
.delete(function(req,res){
req.ressource.remove(function(err){
if(err)
res.status(500).send(err);
else{
res.status(204).send('Removed');
console.log('ressource supprimée');
}
});
});
Could you help me out to figure the ajax code needed ? or is there another way ?
Don't hesitate to ask for more code if needed, I'll be as reactive as possible to answer you quickly.
Best regards.
Take a look at the jQuery ajax docs: http://api.jquery.com/jquery.ajax/
$.ajax({
url: '/ressources/t/123',
method: 'DELETE',
data: yourdata
})
.done(function( data ) {
console.log(data);
});
<script type="text/javascript">
$(document).ready(function(){
$('table#delTable td a.delete_link').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: '../scripts/delete_link.php',
data: 'link=' + $(this).attr('data_link') + '&topic_pk=' + $(this).attr('data_topic') + '&topic_introduction=' + $(this).attr('data_introduction'),
cache: false,
success: function()
{
parent.fadeOut('fast', function() {$(this).remove();});
}
});
}
});
});
</script> just look at this. it can solution your problem. Dont Forget your datatable's name

Calling json data from an api

I am trying to retrieve data from an api and use it to populate the div with the ID "output". I get an error that the $ is undefined. Can anyone help determine what I am missing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<meta name="Content-Style-Type" content="text/css">
</head>
<body style="margin: 0px; padding: 0px;">
<div id="fullscreen">
<div id="output">
</div>
</div>
</body>
<script>
$.ajax({
type: 'GET',
url: "https://apiurl.com",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
</script>
</html>
As Sirko already explained in the comments, you are trying to use the javascript library JQuery, but the library is not available because you didn't include it.
You can include it by either downloading JQuery here and including it via
<script src="src_to_local_jquery.js"/>
or by including it externally (described in CDN section of above link)
Also note, that script tags should be put either in the head or the body section. To make sure your custom script is executed after the page is ready, you can use JQuery's document ready method.
The $ sign is not part of the JavaScript language, it is a short hand for a third party library jQuery ($ === jQuery).
You need to add it as a dependency in your html file with a script tag with a src attribute containing the URI for the source file before you can use it.
<html>
<head></head>
<body>
...
...
<script src="//code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(function () {
// Your code here
});
</script>
</body>
</html>
Include jQuery either as a CDN or download add reference locally. Then make sure the DOM is ready before you make the call. You can read more about that here
<script src="local_jquery.js"/>
// OR
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
$(function() {
$.ajax({
type: 'GET',
url: "https://apiurl.com",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});

Grabbing Values from a JSON API Responce, putting them into webpage

Today I have a question that may seem kinda simple the the rest of you. I'm just now learning how to use APIs/JSONs and I'm a little confused. I'm trying to simply grab the temperature from this openweathermap.org API response and displaying it in an html tag.
The javascript from what I know is grabbing the temperature and setting it as a var. I'm confused why I cannot use id="" to set text inside a tag. The code below is what I have so far. I thank you for your time.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
var weather;
var temp;
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather){
var temp = weather.main.temp;
}
});
</script>
</head>
<body>
<p id="temp"></p>
</body>
</html>
#ArunPJohny have already identified the errors: 1) missing }) and 2) use $('#temp') to get the HTML element. Also you don't need to declare weather because it is declared as an argument.
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather) {
$('#temp').text(weather.main.temp);
}
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<p id="temp"></p>

Categories