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.
Related
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...
}
<form>
<input type="text" id="user"/>
<input type="button" value="Submit" onClick="post();" />
</form>
<div id="result"> </div>
<script type="text/javascript">
function post()
{
var username = $('#user').val();
$.post('battlephp.php',
{postuser:user}
)
}
</script>
Its a simple Ajax code.. It should take username and display the Php code!
But don't know why its not running?? Actually I am learning...so I cant rectify the error or fault??
I am running ii on localhost.. so is there any problem with using:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
display the Php code
No, it shouldn't.
First, you've changed your mind about the variable name you are using (user, username) half way through your script, so you are going to throw a reference error.
Second, you haven't provided a function (the third argument) to $.post, so you aren't doing anything (such as displaying it) with the returned data.
Third, the server should execute the PHP and return its output. You shouldn't get the actual PHP code.
function post() {
var username = $('#user').val();
$.post(
'battlephp.php',
{postuser:username}, // Be consistent about your variable names
function (data) {
alert(data);
}
);
}
Instead
document.ready()
you can use
jQuery(function($){...});
Try to do this:
<script>
$(document).ready(function() {
function post() {
var username = $('#user').val();
$.ajax({
type : 'post',
url : 'batttlephp.php',
data : {
postuser : user
},
success : function(data) {
alert(data);
},
error : function(data) {
alert(data);
}
});
});
});
</script>
if you're doing a ajax request then is good also handle success and error...
Also I suggest to you "to start the document".
Try the code above and let us know if worked
I cannot for the life of me figure out what is going on here. I'll open a different browser to check if what I changed works, and maybe my other browser cached something, and it will work! But then I do it again and it doesn't seem to. I'm going crazy.
On my website, syllableapp.com, I created a MySQL database I could connect to. I made a PHP script that connects to it, adds a simple entry to it, and is done. It's called register_email.php, and it's available to access here. Accessing it manually via that URL will add the entry. Its code is as follows:
<?php
$db = new mysqli("localhost", "username", "password", "table");
if ($db->connect_error) {
echo "Could not connect to database.";
exit;
}
else {
$db->query("INSERT INTO emails (email) VALUES ('weird')");
echo 1;
}
?>
If I check, it gets added.
However, I want it to be added from a form. I have an HTML file at http://syllableapp.com/test/index.html that looks like this:
<html>
<head>
<title>Syllable - iPhone Speed Reader</title>
<link rel="stylesheet" href="styles/style.css">
<script type="text/javascript" src="scripts/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.23.min.js"></script>
</head>
<body>
<div class="content">
<img src="images/app-icon.png" alt="App icon">
<h1>Syllable</h1>
<p>Speed reading app for iPhone. Devour all your Instapaper and Pocket articles, and learn to read much faster in the process.</p>
<form method="post" action="">
<input type="email" class="email" placeholder="Email me when it's live">
<input type="submit" class="submit" value="Send">
</form>
</div>
</body>
</html>
So when the user submits the form, the JavaScript file I linked to at the top intercepts the submit button press, and calls an AJAX function to submit it to the PHP form. The jQuery for that looks like:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var email = $.trim($('.email').val());
var emailRegEx = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (email == "" || !emailRegEx.test(email)) {
event.preventDefault();
$(this).effect("shake", { times:2 }, 75);
}
else {
$.ajax({
type: "POST",
url: "http://syllableapp.com/test/register_email.php",
data: { "message": "hi" },
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
});
});
Which basically just checks if it's a valid email address, then if so, calls the PHP file.
However, every time I click submit, it says failure. Why on earth is this happening? Why can I access it directly, but it won't let me use AJAX?
Just a guess, but in your AJAX block change the URL line to this:
url: "register_email.php",
Also, as a test,
(1) change your alert command in the AJAX success function to:
alert(data);
and (2) insert this line immediately following the <?php directive in the file "register_email.php":
die('Made it to here');
A few things:
1) You're form needs an action or else it's not proper HTML. You can set it to a value like "#"
2) When you click the submit button, you want the form submitted using custom ajax, and not through the standard way. Your ajax handler for the click event should be something like:
$('input[type="submit"]').click(function(event) {
event.preventDefault();
//...
});
You have event.preventDefault in your code, but the event variable isn't being passed to the function. And I think you want event.preventDefault called every time, not just in the case of input validation failure.
3) Instead of using alerts, try using console.log and monitoring your javascript console to see if you get any errors. Add those errors to your question to help us with your issue.
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);
i made this form:
<form id="form" name="msgform" method="" action="">
<input type="text" size="40" id="msg" name="message"/>
<input type="submit" id="button" name="clicker" value="click" />
</form>
and this jquery script:
$(document).ready(function(){
$("#button").click(function(){
$("#form).submit(function(){
var submision= $("#form).val();
$.post("txt/process.php", submision, function(data){
alert(data);
});
});
});
});
and this is the process.php file:
<?php
echo $_POST['message'] . "";
?>
now when i click the button the form is submited, but it sends it using the GET method because i can see it in the adress bar, but it never gets sent to the php file, and i checked to see if the names are correct and if i specify the POST method it still doesnt go to the php file.
is the server or browser ignoring the code? or am i doing the whole thing wrong?
thanks
Please find the following code, it works and please go through with the documentation, it will tell you that what the mistake was being done.
$(document).ready(function(){
$("#button").click(function(){
$("#form").submit(function(){
/* var submision= $("#form).val();
THIS DOESN'T WORK TO GET ALL OF THE ELEMENTS IN
FORMAT TO PASS TO $.post EVENT,
We can do this as I did in following example
*/
$.post("txt/process.php", { msg: $("#msg").val() }, function(data){
alert(data);
});
/* Also you didn't put return false statement just at the end
of submit event which stops propagating this event further.
so it doesn't get submitted as usually it can be without ajax,
So this stops sending the form elements in url. This was because
by default if you define nothing in method property for form
then it consider it as GET method.
*/
return false;
});
});
});
Let me know please you are facing any issue.
You don't need to register the submit event for the form inside the click handler of the button. As it is a submit button it will automatically try to submit the form for which you register the corresponding handler:
$(function() {
$('#form').submit(function() {
// Get all the values from the inputs
var formValues = $(this).serialize();
$.post('txt/process.php', formValues, function(data) {
alert(data);
});
// Cancel the default submit
return false;
});
});
$("#form).submit(function(){
see if this selector is missing a "
$("#form").submit(function(){