wordpress - need to add custom php (to be called by AJAX), but not in a theme - ajax

I have a wordpress application, and in one page, I need to make an AJAX call to some custom PHP file. The custom PHP code will create an image file and save it in a directory. Is it safe to store images in a custom directory at the root?
Where is a good place to place this custom PHP file? Should I place it in a newly created folder at the root? Or will it be deleted if wordpress is updated? Do I need to create a plug-in for this?

It's better if you use a custom directory inside of the uploads folder of the site to store images. Create it and then chmod 775
Place the form in the page template for your page. Add an empty div with a class "upload-response". Just before the closing of the container div, insert a script tag that will echo the admin-ajax.php path to a js variable:
<script>
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
</script>
I used jQuery to handle the rest (the contents of the upload.js file):
(function ($) {
$('body').on('click', '.upload-form .btn-upload', function(e){
e.preventDefault();
var imagedata = canvas.toDataURL('image/png');
var fd = new FormData();
//var files_data = imagedata;
fd.append('image', imagedata);
// our AJAX identifier
fd.append('action', 'my_upload_files');
// Remove this code if you do not want to associate your uploads to the current page.
//fd.append('post_id', <?php echo $post->ID; ?>);
$.ajax({
type: 'POST',
url: ajaxurl,
data: fd,
contentType: false,
processData: false,
success: function(response){
$('.upload-response').html(response); // Append Server Response
}
});
});
})(jQuery);
In your plugin file, add:
add_action('wp_enqueue_scripts','ajax_upload_script');
function ajax_upload_script() {
wp_enqueue_script('ajax-upload', plugins_url( '/js/upload.js' ), array('jquery'), '', true);
}
add_action('wp_ajax_my_upload_files', 'my_upload_files');
add_action('wp_ajax_nopriv_my_upload_files', 'my_upload_files'); // Allow front-end submission
function my_upload_files(){
//file handling here
}
Or if you don't want to make a plugin, add the actions to your child theme functions.php and change plugins_url( '/js/upload.js' ) to get_stylesheet_directory_uri().'/js/upload.js'

One way would be to use a plugin like PHP Code for posts. This would be better than hardcoding PHP into templates or WP Pages. The advantage is you can update and change the code easily and when updates are needed to WP, you do not need to re-apply your hardcoded PHP.

If you want implement ajax in wordpress than you need use wp_ajax hook.
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
add bellow code in function.php (theme folder)
javascript add in wp_footer hook on function.php
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
below wp_ajax hook add on function.php
add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
function prefix_ajax_add_foobar() {
// Handle request then generate response using WP_Ajax_Response
// Don't forget to stop execution afterward.
wp_die();
}
Those code will not update when you update Wordpress. but if possible than add those code on function.php on child theme so in case if you want update theme than not update those code.

Related

wordpress - check if slug exists with AJAX

I would like to check from the user interface if a slug url already exists.
I naturally turned to an AJAX solution like this.
`jQuery("#slugBrut").keyup(function() {
var slugBrutText = jQuery("#slugBrut").val() ;
jQuery.ajax({
type:"POST",
url: "theme/is_valid_slug.php",
data:{
slug : slugBrutText
},
success: function(result){
console.log(result);
}});
});`
And on the called script side is_valid_slug.php, it looks like this
`<?php
require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
global $wpdb;
$slug = $_POST['slug'] ;
$post_if = $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_name like '$slug'");
echo $post_if ; // returns 0 or 1`
Everything works fine. However, I am not a wordpress pro and I would like to know if this way of doing things is dangerous and if another approach would be better?
if you are coding in custom plugin or theme (any files in wp-content) No need to require wp-load.php .
if you want better way for create ajax in WP fallow this AJAX wordpress document
NOTE : you can write callback in functions.php in your theme directory or child theme .
NOTE 2 : Also you can use this wp function Instead SQL query.
$exists = get_page_by_path( $slug, OBJECT, $post_type );
return (int) $exists; // 1 or 0

Calling MVC Controller method with Ajax call not working [duplicate]

I been trying to use #Url.Action inside Ajax url in another external .JS file but unfortunately i got no luck.
Here's my Code:
$.ajax({
type: 'post',
url: "#Url.Action("ClearData","Home")",
success: function () {
}
});
This Code working only inside the View itself but not in Javascript externally.
Iv'e been searched some possible solution but it seems different than this.
Is there any alternative way to use #Url.Action in another .Js File?
#Url.Action() is razor (server side) code and is not parsed in external files. Options include
Declaring a global variable in the main file, say
var url = #Url.Action("ClearData","Home");
and then in the external script use url: url in the ajax call
Including a data- attribute in the element your handling, for example if its a button click event, then
<button data-url="#Url.Action("ClearData","Home")" id="mybutton">
and then reading that value in the external file, for example
$('#mybutton').click(function() {
var url = $(this).data('url');
$.ajax({
url: url,
....
if your js code inside view
$.ajax({
type: 'post',
url: "#Url.Action("ClearData","Home")",
success: function () {
}
});
this is work
when js code is an separate (external file)
#Url.Action("ClearData","Home") is not work ,
this case you have to write total url or folder path
You can create a partial view, then inside this view are just list of hidden fields
such as
#Html.Hidden("ActionName", #Url.Action("ActionName", "Controller"))
which generates this
<input id="ActionName" name="ActionName" type="hidden" value="/controller/ActionName">
then you can call it like
var urlAction = $('#ActioName').val();
or you can create a js function like what I did
function ActionCaller(actionName)
{
return $('#' + actionName).val();
}
var action = ActionCaller(ActionName);

Get wordpress posts in categories via Ajax uisng Semantic UI API and tabs

I am trying to create tabs using semantic UI tabs and get content via an ajax call. I looked into the documentation but could't figure out a way to get the content from my wordpress site.
I want to create tab titles with category name and load the posts of that category via ajax when user clicks the title. I don't know if this is possible with the semantic UI API,
Thanks
You can call the wordpress api to get categories and put the category name, id and slug in a javascript object.
http://v2.wp-api.org/reference/categories/
Then loop through the object and show titles.
Use the slug to call
wp-json/wp/v2/posts/?filter[category_name]=uncategorized to get posts from category
Well if you are using symantic ui as a separate instance (not wp theme) and want to get content from the wordpress site then you need a REST api and not ajax. You should follow #Gisha James advice.
But if you are using symantic ui in a wordpress theme, and you want content to be loaded from the same wordpress installation then its a bit tricker because you need to understand how wordpress handles ajax, which basically works on 'admin-ajax.php'.
Here is a very simple implimentation taken from another answer.
// Footer or spearate js file
<script>
$(".post-link").click(function(){
var post_id = $(this).attr("rel"); //this is the post id
$("#post-container").html("content loading");
$.ajax({
url: myapiurl.ajax_url,
type: 'post|get|put',
data: {
action: 'my_php_function_name',
post_id: post_id
},
success: function(data) {
// What I have to do...
},
fail: {
// What I have to do...
}
});
return false;
});
</script>
// Function.php
add_action( 'admin_enqueue_scripts', 'my_ajax_scripts' );
function my_ajax_scripts() {
wp_localize_script( 'ajaxRequestId', 'myapiurl', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
function my_php_function_name() {
// What I have to do...
}

Wordpress FrontEnd Ajax return 0 using Theme

Hi I know this has been asked a few times but I have been through every answer and tried them all with no luck.
I am trying to use Ajax in a Wordpress front end page, I have security in the page to ensure the user is logged in before they can view this page too.
No matter what code i enter my ajax call always returns 0.
function ajaxfoodlookup()
{
echo "ajax fired";
die();
}
add_action('wp_ajax_nopriv_ajaxfoodlookup','ajaxfoodlookup');
add_action('wp_ajax_ajaxfoodlookup','ajaxfoodlookup');
This is what I have in my functions.php (i have also tried exit(); and die($results) where $results = 'ajax fired'; nothing seems to work.
This is what I have in the page to call the ajax;
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: { action:'ajaxfoodlookup'},
success: function (data) { alert(data);}
});
The only thing that I have different to the other questions/answers on here is that I am using a bought Theme which does have some code added, is that theme able to hijack my ajax calls? I thought wordpress would execute the ajax call depending on the 'action' in the data supplied?
Please help its driving me crazy?
Thanks
Official WordPress recommendation is to use the ajaxurl variable instead of hard coded one. Insert this before your JS code and change the url of your jQuery.ajax to use ajaxurl.
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
You can also use wp_localize_script to define the ajaxurl

WordPress - AJAX Code Is Not Triggering Action

I am writing a plugin and the widget contains drop-down lists and needs to retrieve values for each successive drop-down list from the database using AJAX based on the previous drop-down list's selected value.
I am going off a slightly modified version of the code from the WordPress codex found here:http://codex.wordpress.org/AJAX_in_Plugins
For some reason the action function either isn't being called or the there is some error in my code:
// add action hooks
add_action('wp_footer', 'er_qm_ajax_handler' );
add_action('wp_ajax_repopulate_widget_club_type', 'repopulate_widget_club_type');
add_action('wp_ajax_nopriv_repopulate_widget_club_type', 'repopulate_widget_club_type');
// action for the wp_footer hook to insert the javascript
function er_qm_ajax_handler(){
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
jQuery('#widget_manufacturer').val('3').change(function(){
var manufacturer = $("#widget_manufacturer").val();
var data = {
action: 'repopulate_widget_club_type',
selected_manufacturer: manufacturer
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
});
</script>
<?php
}
// The action function
function repopulate_widget_club_type(){
die("Got to the action");
}
Not exactly sure what I am doing wrong as I am getting no response from the AJAX post, I know that the jQuery .change() is working as I set up some alert()'s to test it out once I altered the dropdown lists values.
Any thoughts and help will be greatly appreciated, thanks!
You need to define the value of ajaxurl like this:
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>'
It's prefferable to define it in javascript's global scope so before this line:
jQuery(document).ready(function($) {

Resources