How do I define onclick function from php file in jQuery? - php

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>
</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>
<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!

If i do the script in the php file it works fine.
The problem isn't that you moved the code to a different file. The problem is that you changed the code, and what you changed it to no longer works.
In your working version the functions are defined in global scope. In your non-working version they are not defined in global scope. They're defined within the callback function to the document.ready event. (Why the change?)
Move the functions back into global scope (remove the jQuery(document).ready(/*...*/); operation) and the code will behave the same as the working version.
Alternatively, if you don't want to have functions in global scope (it's generally considered poor form and can lead to bugs as complexity grows) then you can define them locally within that function scope and then assign the click handler also within that scope.
So instead of using the onclick attribute directly in the HTML (also considered poor form and more difficult to maintain as complexity grows) you would apply the click handler in JavaScript:
document.getElementById('search').addEventListener('click', getRecipe);
In this case the event object will be automatically passed as the argument to getRecipe, and you'd use that within the getRecipe function to get the value. For example:
function getrecipe(e) {
var q = e.target.value;
// the rest of the existing function...
}

Related

Ajax is driving me nuts. Why is Jquery post method failing in this specific case?

Ok, so ajax seems to be misbehaving. In other words i'm doing something wrong. I have a simple angular js app. The html looks like this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="../scripts/form_controllers.js"></script>
</head>
<body ng-app="EditDocApp">
<div ng-controller="EventDetector">
<input ng-model="event">
<button ng-click = "SelectEvent()">Click</button>
</div>
</body>
</html>
form_controllers.js contains a call to the Jquery post method in the EventHandle angular service. This is invoked in the calling of EventHandle.ajaxRequest() in the $scope.SelectEvent method in the EventDetector controller. This is form_controllers.js:
var editDocApp = angular.module("EditDocApp", []);
editDocApp.controller("EventDetector", eventDetector)
.factory("HandleEvents", handleEvents);
function handleEvents() {
var pass_back = {
ajaxLastReturn: "one",
ajaxRequest: function() {
$.post("http://localhost/TrailGuide/Website/Interface/webDataModelBuild/Documentation/scripts/test1.php", {}, function(response) { alert(response); })
.fail(function() { alert("nah"); });
}
}
return pass_back;
}
function eventDetector($scope, HandleEvents) {
$scope.event = "";
$scope.SelectEvent = function() {
$scope.event = "select";
HandleEvents.ajaxRequest();
};
}
The $.post method is failing every time i execute it by calling $scope.SelectEvent() from the button in the view (an alert box with "nah" pops up). I've tested the address passed to $.post by copying and pasting to the browser address box and it runs fine. I've tried the $.post method with and without data, no dice. I've tried jquery.ajax, still no dice. The php file, test1.php, is as follows:
<?php
echo "I am here!";
?>
Can somebody please point out what i am missing here? Is there some setting in php.ini that could be effecting this? Btw, this is my very first post on stack overflow so go easy on me! I'll get the hang of it. Thanks a bunch!

How to load php instantly from ajax?

I am trying to directly load a page using ajax. Here are the details:
HTML:
<div id="feedback"> </div>
<script type="text/javascript" src="script.js"></script>
script.js:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
do.php:
<?php
//Do whatever...
echo "Done!";
?>
What I am seeing is: the page first loads, and there is a delay before the "feedback" div gets written. How can I solve this?
As far as I know of course it will have that delay. Suppose your page containing <div id="feedback">[…]</div> is loaded at 0th second now:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
Is called as apparently it’s visible when document loads. So suppose its called at 3rd second when the document is ready—you can refer to this page for details—now you will be seeing that feedback div blank for 3 seconds.
I can suggest 2 things:
You can place a loader image by default inside the div so your code will change to <div id="feedback"><img src='loader.gif'></div> (Assume you have the loader.gif in the same directory of the page). By doing this you will make the user visually understand that some processing is going on and will load data.
Instead if you can place file_get_contents() or include() so it will look something like this <div id="feedback"><?php file_get_contents('do.php');?></div> or <div id="feedback"><?php include('do.php');?></div> As far as I know file_get_contents will execute the page and then load while include will load and then execute hence in include() you have the variables in the page available whereas in file_get_contents are not available but CSS would work in both cases.
You could start loading immediately and then add the data when everything has completed.
var _data = null;
var _ready = false;
$.ajax({
url: 'do.php',
success: function(data){
_data = data;
tryAddData();
}
});
$(document).ready(function() {
_ready = true;
tryAddData();
});
function tryAddData(){
if(_ready && _data !== null){
$('#feedback').html(_data);
}
}

Global variable inside Ajax function

I'm learning the Ajax method with jQuery. I've a simple code here. It's to load data from a csv file by jQuery Ajax method, and put it into an array for further use. But it seems the array lost outside of the Ajax function even I do make the array global in the first place.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var db=[];
$(document).ready(function(){
$.ajax({
url: 'loaddata.php',
success: function(data){
var arr = data.split('|');
for(var i=0; i<arr.length; i++){
var miniArr = arr[i].split(',');
db.push(miniArr);
}
printTest(); //work here
}
});
printTest(); //not working and collapse here
});
function printTest(){
document.getElementById('test').innerHTML += db;
}
</script>
</head>
<body>
<div id="test" />
</body>
</html> `
My php file should be fine,
<?php
$database = file('database');
foreach($database as $item){
if ($item===end($database))
echo $item;
else
echo $item.'|';
}
?>
Thanks in advance.
Your second printTest() is where the .ajax parameters go, so there's a syntax error there. The reason the first call works is because it's inside the success callback, and since AJAX is asynchronous this is called when the call has completed.
If you put the printTest() call after the AJAX call, it will be called immediately after the AJAX call has started, not waiting until it completes, due to async.
You can't call your second printTest() here.
And for the record, try to use JSON to retrieve your datas, it's way much easier.

Calling PHP function from wordpress in ajax?

reset.php file:
<?php
add_action('admin_init','popup_template_reset_options');
function popup_template_reset_options()
{
delete_option('popup_template_on');
delete_option('popup_template_close');
delete_option('popup_template_escape');
delete_option('popup_template_external');
delete_option('popup_template_home_page');
delete_option('popup_template_all_pages');
delete_option('popup_template_template');
delete_option('popup_cookies_display_after_like');
add_option('popup_cookies_display_after_like','365');
//add_option('popup_template_on','1');
add_option('popup_template_close','1');
add_option('popup_template_escape','1');
add_option('popup_template_external','1');
add_option('popup_template_force_timer','2');
add_option('popup_template_home_page','1');
add_option('popup_template_all_pages','1');
add_option('popup_template_template','2');
}
?>
Script Ajax:
<script type="text/javascript">
$(document).ready(function() {
$('#reset_general').click(function()
{
$('#result1').css("display", "block");
jQuery('#result1').animate({'opacity': '1'});
});
});
function resetgeneral() {
$.ajax({type: 'POST', url: '<?php echo WP_PLUGIN_URL; ?>/fantasticpopuptemplate/inc/reset.php', success: function(response) {
//$('#fff').find('.form_result').html(response);
$('#result1').css("display", "none");
$('#resets1').css("display", "block");
$('#resets1').html("Settings Resets");
$('#resets1').fadeOut(2500, "linear");
}});
return false;
}
</script>
<form onsubmit="return resetgeneral();" id="form_general_reset" class="form-1">
<input type="submit" value="Reset" id="reset_general" name="reset" class="button-secondary"/>
<input name="action" type="hidden" value="reset" />
</form>
Hi i trying to call the php reset function in ajax but when i googling i know that not possibilities of direct calling php function so I put that particular function in seperate php file and call that php file i am not sure how can i do this in ajax i tried this above code but nothing happen. Settings Resets Message appear. How Can I do this Any Help would be great. Before using the ajax concept i tried with isset function in php But it getting page load every time for that only i jump into the ajax.
There is a standard way of achieving AJAX in WordPress plugin by relying on the admin_ajax.php. The file name is misleading, as it can be used in the frontend too, by assigning functions to AJAX actions.
There is a good description on the WordPress Codex:
http://codex.wordpress.org/AJAX_in_Plugins
One thing to be aware of: Your AJAX handler functions will always have to terminate with a die() command, to avoid the extra '0' output from WordPress.

how to stop setInterval after php script is done executing through ajax

I have searched for the answer to this and the reason I'm not finding it could just be that I'm completely botching my script from the getgo, so please anyone who can help I greatly appreciate it.
I have a javascript function which fires onClick of a form submit and runs an ajax call to script1.php, then starts a timer with setInterval. setInterval is calling another javascript function to poll an output file from script1.php so we can get new data added to the screen. This part works fine.
However, I'd like to stop the timer when script1.php is done processing. How do I do this? I've tried putting in a clearInterval(myTimer) in script1.php as the last statement it runs, and it seems to be showing up in the browser, but it's not stopping the timer.
<script type="text/javascript">
var myTimer;
var file1 = "script1.php";
var file2 = "script2.php";
function startTimer(myTimer) {
myTimer = window.setInterval(loadData, 2000);
}
function stopTimer() {
clearInterval(myTimer);
}
function startData()
{
ajaxRequest(file1,data);
startTimer(myTimer);
}
function loadData()
{
ajaxRequest(file2)
}
</script>
<form action="index.php" method="post">
<div style="text-align:left;width:300px;">
<textarea style="width:300px;height:200px;"> </textarea><BR>
<button type="button" onclick="startData()">get data</button>
</div>
</form>
<div id="myDiv" style="text-align:left;width:500px;border:solid 1px #ccc;padding:50px;">
please enter data above
</div>
Yes, you botched it. You should just have PHP return the data directly to the script that does the AJAX call.
On AJAX success, any text outputted by the PHP script will be available to the success callback.
If you were using JQuery, it would be as simple as:
$.ajax({
url: 'someurl',
success: function(response) {
// do whatever with response
}
});
You're passing myTimer as a parameter to startTimer. This makes myTimer a local variable to startTimer. Therefore it's not updating the global myTimer.
It should be:
function startTimer() {
myTimer = setInterval(loadData, 2000);
}
function stopTimer() {
clearInterval(myTimer);
}
Then you just need to call startTimer() and stopTimer().
when you starting your interval assign it to any PUblically accessible variable say "INTERVAL_ITEM"
and when your response achieved clearInterval(INTERVAL_ITEM);

Categories