get Json data (Showing error - 'Request is not excuted') - javascript

get Json data (Showing error - 'Request is not excuted')
How to make a request executed code.
country.js
$("#btn-id").click(function() {
//get data
$.getJSON("https://reqres.in/api/users?page=2",
function(json) {
//Empty div if clicked agian
$("#data-id").html('')
//loop through it
json.data.forEach(function(jd) {
//append data in div
$("#data-id").append(jd.id + "--" + jd.email + '<br>');
})
});
});
HTML FILE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>The jQuery Example</title>
<script src="country.js"></script>
</head>
<body>
<form>
<input type="button" id ="btn-id" value = "Click to Load Data" />
<div id="data-id"></div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="country.js"></script>
</body>
</html>
get Json data (Showing error - 'Request is not excuted')
How to make a request executed code.

Related

How do I get the id present in the link using jQuery?

I am calling data from a movie API using jquery and it has an endpoint where I can call a particular show with an id. The home page displays the movies and clicking them should call another endpoint of the API. Below is my code:
$(function (){
let $movies = $('#showList')
$.ajax({
method:'GET',
url:'http://api.tvmaze.com/shows',
success: function(movies){
$('#show').hide()
$('#showList').removeAttr('hidden');
$.each(movies, function(i,movie){
$movies.append('<li class="list"><a id="ss" href="'+ movie._links.self.href+'">'+ movie.name +'</a></li>')
})
}
})
})
$('body').on('click','.list a',function(event){
event.preventDefault();
$('#showList').hide();
$('#show').empty()
let currentId = event.target.id;
console.log(currentId)
$.ajax({
method:'GET',
url:'http://api.tvmaze.com/shows/'+currentId,
success: function(movies){
$('#show').append('<h1>'+ movies.name +'</h1>')
}
})
$('#show').show();
HTML:
<!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.0">
<title>TV Shows</title>
</head>
<body>
<h1>TV Shows</h1>
<div id="show" hidden></div>
<ul id="showList" hidden></ul>
<form id="searchForm">
<input type="text" id="search_term">
<label for="text">Search</label>
<button>Submit</button>
</form>
<a id="homelink" href="/" hidden>Back to All Shows</a>
<footer>Swayam Shah, 10471353</footer>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="/public/js/index.js"></script>
</body>
</html>
How do I get this id when I click on the movies link? The console.log shows empty.
you haven't mentioned id attribute in your anchor tag.
$movies.append('<li class="list">'+ movie.name +'</li>')
Had to replace URL with only currentID
Using "this" works for me.
$("a").click(function() {
console.log($(this).attr("id"));
});

Print and submit data into Database

I have a form. I would like to print what user intputing in this form and insert data into database. But I 'm facing problem:
If I print data in present window, printing is OK, but don't insert into database. Had a error: Form submission canceled because the form is not connected
If I print data in new window, insert database is ok, but don't print user's data.
I have researched two days, but haven't found any resolve.
I used MVC 1 module and 1 template, and use javascript (jqwery)
Example as below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form name ="form" method="post" action="index.php?controller=index&action=add" onsubmit="return submitData()">
<input type="text" id = "content" name="content">
<button type="submit">Send</button>
</form>
</body>
<script type="text/javascript">
function submitData() {
// print data
content = '<p>The content is: ' + document.getElementById("content").value + '</p>';
document.body.innerHTML = content;
window.print();
// submit data
return true;
}
</script>
</html>

jQuery get function doesn't work as expected

I need to get photos using GIPHY API, I have the following function:
function callApi(input) {
var url1 = `https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=${input.value.toLowerCase()}&limit=1`;
var url2 = "https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1";
var xhr = $.get(url2);
xhr.done(function(jsonObj) {
alert("Success!");
document.getElementById("genImage").src = jsonObj.data.images.original.url;
}).fail(function() {
alert("erro");
}).always(function() {
alert("...");
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form id="query-form">
<label for="query">KEYWORD</label>
<input name="query" type="text">
<input type="submit" id="button" value="GENERATE" onclick="callApi(query)">
</form>
<img id="genImage" src="">
</body>
</html>
So, the problem is that $.get() function doesn't respond at all, even always() callback function does not get executed.
When I try this particular URL in the Postman application, I get the response (json object) and I can access the data.images.origianl.url property it is there.
When I try the following line of code in the console :$.get("https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1"); I get the response with the status code 200, so it should work in the main.js file, but in my case it doesn't.
I have two variables url1 and url2 this is because, in my first tries I did not get anything with the url1, but getting the success with the url2. After some time I didn't get anything using two of them.
What is the problem? How can it be that I can get responses from Postman and from the console using the same URLs, but do not get them with actual code?
Thank you for your patience!
This is a common problem, understanding the difference between type button and type submit.
Submit will submit the form. Whereas button will just process the event handlers assigned.
Change
<input type="submit"
to
<input type="button"
function callApi(input) {
var url1 = `https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=${input.value.toLowerCase()}&limit=1`;
var url2 = "https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1";
var xhr = $.get(url2);
xhr.done(function(jsonObj) {
alert("Success!");
document.getElementById("genImage").src = jsonObj.data.images.original.url;
}).fail(function() {
alert("erro");
}).always(function() {
alert("...");
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form id="query-form">
<label for="query">KEYWORD</label>
<input name="query" type="text">
<input type="button" id="button" value="GENERATE" onclick="callApi(query)">
</form>
<img id="genImage" src="">
</body>
</html>

Checkbox state from HTML (JS) to PHP

I'm new to JS and i want to receive the value from a variable in JS, send it by post (or ajax) to a PHP file, and see the text display. The thing is i've been trying different ways to do it but i always get a undefined index in php.
My code is below
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PRUEBA AJAX JS PHP HTML</title>
</head>
<body>
<H1>prueba</H1>
<input type="checkbox" name="switch" id="switch" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#switch").change(function ()
{
var checked=$("#switch").attr("checked");
if(checked)
{
$("switch").removeAttr("checked");
console.log("estado apagado switch 1");
var estados="1";
$.post("accion.php", {estado: "david"});
}else
{
$("#switch").attr("checked","checked");
console.log("estado encendido switch 1");
var estados="2";
$.post("accion.php", {estado: "david 2"});
}
});
</script>
</body>
</html>
accion.php
<?php
$est = $_POST['estado'];
echo $est;
if ($est=="david") {
echo "no mameees";
}else{
echo "no mameees no se puso ";
}
?>
Someone has any idea ?
$("#switch").change(function () {
var checked=$("#switch").prop("checked");
if(checked)
{
console.log(checked);
}else{
console.log(checked);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Switch <input type="checkbox" name="switch" id="switch" >
Use prop instead of attr to find checkbox is checked or not.
You can let php check if the checkbox was checked or not in a success callback from $.post:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PRUEBA AJAX JS PHP HTML</title>
</head>
<body>
<H1>prueba</H1>
<input type="checkbox" name="switch" id="switch" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#switch").change(function ()
{
var checkbox = $("#switch");
$.post("accion.php", {estado: checkbox.val()}, function(data){
$("h1").html(data);
});
});
</script>
</body>
</html>
accion.php
<?php
$checkbox = isset($_POST['estado']) && $_POST['estado'] == 'on'; // 'on' is the default checkbox value when you don't specify it in html
if ($checkbox) {
echo "it's been checked";
}else{
echo "it wasn't checked";
}
?>
PS: when working with ajax ( check out $.post options) i recommend using dataType: 'json' and your php should respond with a valid JSON, you have json_encode for that.
use
var checked = $('#switch').is(':checked');
instead of
var checked=$("#switch").attr("checked");

How to Send keyboard data to the Server using getJSON

I am using getJSON to send a request to server and fetch response. When I send an string of text like 'firstname=x' to the server, it works fine, but when I use '$('#input').val()' as input data to the server, it returns nothing as response.
Here is the jquery code
<!DOCTYPE html>
<html>
<head>
<title>Request in getJSON</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="jquery-1.8.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function(){
var req=$('#query').val();
var data='firstname=req';
$.getJSON('http://..../server.php?callback=?', data,function(res){
alert('Your name is '+res.fullname);
});//getJSON
}); //onclick
});//on document ready
</script>
</head>
<body>
<h1> Enter Name </h1>
<input type='text' id='query' />
<input type="button" id="button" value="submit" />
<div id="results"></div>
</body>
</html>
Hope you can help me
Thank you
Try with this one:
$(document).ready(function(){
$('#button').click(function(e){
e.preventDefault();
var data={firstname : $('#query').val()}; //<--------try like this
$.getJSON('http://..../server.php?callback=?', data,function(res){
alert('Your name is '+res.fullname);
});//getJSON
}); //onclick
});//on document ready

Categories

Resources