New to API's and trying to figure out how to get a function to be defined from a js file when i click on a button i a php file. The js file is correctly added in the functions.php file.
Right now the jQuery code in my js file looks like this.
jQuery(document).ready(function($) {
function getsource(id){
$.ajax({
url:"https://api.spoonacular.com/recipes/"+id+"/information?apiKey=acc3c7fd3cb74d02b7564eefd51172cd",
success: function(res) {
document.getElementById("sourceLink").innerHTML=res.sourceUrl
document.getElementById("sourceLink").href=res.sourceUrl
}
});
}
function getrecipe(q){
$.ajax({
url:"https://api.spoonacular.com/recipes/search?apiKey=acc3c7fd3cb74d02b7564eefd51172cd&number=3&query="+q,
success: function(res) {
for(var i = 0; i < res.results.length; i++ )
document.getElementById("output").innerHTML+="<h1>"+res.results[i].title+"</h1><br><img src='"+res.baseUri+res.results[i].image+"' width='400' /><br>Ready in "+res.results[i].readyInMinutes+" minutes"
getsource(res.results[i].id)
}
});
}
});
And the php file it should listen to is this one.
<?php get_header(); ?>
<section class="mst-section more-recipes-section">
<div class="mst-row">
<div class="row">
<div class="mst-column-1">
<div class="mst-inner-column">
<input id="search"><button onclick="getrecipe(document.getElementById('search').value)">Search</button>
<div id="output"></div>
<a href="" id="sourceLink"></a>
</div>
</div>
</div>
</div>
</section>
<?php get_footer(); ?>
In my console I get that the function getrecipe is not defined. How can I get the function to understand that I am calling it in the onclick?
One more thing. If i do the script in the php file it works fine. Like this.
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<input id="search" ><button onclick="getrecipe(document.getElementById('search').value)">Search</button>
<div id="output"></div>
<a href="" id="sourceLink"></a>
<script>
function getsource(id){
$.ajax({
url:"https://api.spoonacular.com/recipes/"+id+"/information?apiKey=acc3c7fd3cb74d02b7564eefd51172cd",
success: function(res) {
document.getElementById("sourceLink").innerHTML=res.sourceUrl
document.getElementById("sourceLink").href=res.sourceUrl
}
});
}
function getrecipe(q){
$.ajax({
url:"https://api.spoonacular.com/recipes/search?apiKey=acc3c7fd3cb74d02b7564eefd51172cd&number=3&query="+q,
success: function(res) {
for(var i = 0; i < res.results.length; i++ )
document.getElementById("output").innerHTML+="<h1>"+res.results[i].title+"</h1><br><img src='"+res.baseUri+res.results[i].image+"' width='400' /><br>Ready in "+res.results[i].readyInMinutes+" minutes"
getsource(res.results[i].id)
}
});
}
</script>
Grateful for help!