So, I'm trying to send a post request to a php script of mine.
On the web I'm in a page like: https://yyy.yyy/test-page
My ajax url is set as such:
url: "https://yyy.yyy/test.php"
But then it returns a 404 error with the following url:
https://yyy.yyy/test-page/test.php
And it definitely won't find in the php file in that path, since it is located at root. Moving the php to another folder is not an option.
This website is located in a WordPress server.
Here's the js code:
$.ajax({
url: "https://yyy.yyy/test.php",
method: "POST",
type: "Json",
data: data,
success: function (res) {...}
});
If you're wanting to make use of Ajax and are running WordPress, you should look into writing a plugin and making use of the hooks and functions available to make this easier as WordPress will do a lot of heavy lifting.
I see you mentioned it can't be moved, but if it's at all possible to at least try and replicate the PHP code into a plugin (or a theme although that's less ideal and might not work properly) then it'll make things easier.
Take a look at using Ajax in plugins.
The JavaScript (jQuery) bit:
$.ajax({
data: {
action: 'my_ajax_request'
},
type: 'post',
url: SOWP_AJAX.admin_ajax,
success: function(response) {
console.warn( response );
}
});
The PHP bit (Part 1):
This ensures that the URL that you post your Ajax function to is mapped to an actual URL. In this case, the WordPress Ajax handler at admin-ajax.php.
wp_localize_script(
'sowp_js', // this is the script name that should be used to enqueue the JavaScript code above
'SOWP_AJAX',
array(
'admin_ajax' => admin_url('admin-ajax.php')
)
);
The PHP bit (Part 2):
Put this inside a plugin or theme file that is activated. The hook my_ajax_request must match the request action in the Ajax request and the function name so it's called correctly.
add_action( 'wp_ajax_my_ajax_request', 'my_ajax_request' ); // the hook that is triggered when the request is made
function my_ajax_request() {
echo 'my ajax request works'; // print something out
wp_die(); // stop script execution
}
Once you've got all of the above in place, when the Ajax request is working and runs, you should see my ajax request works printed in your browsers console. If it returns 0 then it means the request failed somewhere. If it does fail, it usually means the action hook has been registered and called so something might be spelt wrong or missing.
Related
This question already has an answer here:
Wordpress: call to plugin php file via ajax
(1 answer)
Closed 6 years ago.
So I'm making a Wordpress site and want to send data (css styles dynamically created by jQuery) to PHP. The reason for this (not fully relevant to this question) is to write the data as a .css file that is loaded at the beginning of every page--making it so there's no visible 'change' of styles when js executes (well, only the first time the page is loaded). I'm sure there's probably a better way to do this.
But back to the main part (sending data from jQuery to a .php). I'm executing a js script (on "front-page.php") that does this:
jQuery(function($){
$(window).on("load", function() {
$.ajax({
type: "POST",
url: "create-style.php",
data: { style : styleString },
dataType: "json",
success: function () {
console.log("success");
}
});
});
});
The console says 'success', so I assume data is getting passed to create-style.php.
create-style.php's write function does this
$file = 'new-style.css';
$style = $_POST['style'];
file_put_contents($file, $style, LOCK_EX);
Now the first thing I tried was having the function included in Wordpress's functions.php. I don't know a lot about Wordpress or web development in general, but it seems intuitive that this wouldn't work since probably the php files get executed before the js (so how could it get the data?)
In an attempt to solve this I rewrite the create-style.php as a cron using wp_schedule_single_event to fire when someone visits the site, with a slight delay:
add_action('write_style_cron', function(){
// the above writing function
});
wp_schedule_single_event(time() + 10, 'write_style_cron'); // give it a slight delay to make sure jQuery happens
However, no $_POST data gets written to the file and doing any tests shows it's empty. I've done a lot of tests and know that:
cron functionality is basically working
the writing function works with test values
$_POST is showing as completely empty and I get an "Undefined index" error in the /wp-cron.php?doing_wp_cron
$.ajax is firing success
there are no other php / js errors
Thanks for reading this very long post. Been searching the internet all day for solutions and decided it might be best to just ask. I'd much appreciate any ideas.
Try using this code:
jQuery(function(){
$('#yourFormName').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'create-style.php', //URL of page where to pass values
data: $('#yourFormName').serialize(), //seriallize is passing all inputs values of form
success: function(){
console.log("success");
},
});
}
});
I am trying to pass data from an ajax call to a specific page of Wordpress.
Below is the code I am using:
jQuery.ajax({type: "POST",
url: 'single-member-page.php',
data:{ size: 'item' },
success: function(){
//alert(data);
jQuery('#display-member-size').text(data);
}
});
The script does not work for WP. I also inspected the page using the console and I get an error:
single-member-page.php" NOT FOUND
I am new to WP and I do not know how to pass data from an ajax call to a specific page.
#Daniel
You asked a very good question, before proceeding to solution we need to understand thumb rules of wordpress ajax.
Thumb Rules:
According to wordpress standards all the ajax request should come to "ajaxurl" in javascript. It actually contains the "wp-admin/admin-ajax.php" file path.
Example:
$.ajax({
url: ajaxurl,
data: {'action':'generateCptApiKey'},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
If you are doing some sutff in wp-admin dashboard section or related to wp-admin section like creating an option page in wp-admin dashboard area, than "ajaxurl" global variable will be always available there in javascript.
If case of this ajax request is initialized from front end page/post than you have to specify admin-ajax.php files path using following method and better if you localize this for front-end javascript,So it will be available in javascript variable like it is available in wp-admin dashboard section.
In order to achieve this we need to add few more lines of code.
Method:
Updated Example code front-end ajax call :
// Register the script
wp_register_script( 'ajaxsettings', 'path/to/ajaxsettings.js' );
// Localize the script with new data
$ajaxsettings = array(
'ajaxurl' => admin_url('admin-ajax.php')
);
wp_localize_script( 'ajaxsettings', 'ajaxsettings', $ajaxsettings );
// Enqueued script with localized data.
wp_enqueue_script( 'ajaxsettings' );
$.ajax({
url: ajaxsettings.ajaxurl,
data: {'action':'generateCptApiKey'},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
After this we need to write method to handle this ajax request and send output back to the ajax call.
For detecting ajax request call in wordpress they have two standard hooks, hooks are just events like when i send a ajax request, wordpress ajax related hook will trigger and i can call any function on that trigger.
So basically for handling ajax request below are two hooks:
wp_ajax_(action) : It handles request from authenticated / logged in users. (Used for back-end wp-admin dashboard related tasks )
wp_ajax_nopriv_(action) : It handles front-end unauthenticated requests.
(Used for front-end page/post ajax call related tasks )
Here (action) is the name of the method that you have to code in your current theme function.php file, and this method will handle this ajax request.
Examples:
Object oriented style:
add_action( 'wp_ajax_cleanResponseFiles', array($this, 'cleanResponseFiles'));
add_action( 'wp_ajax_nopriv_cleanResponseFiles', array($this, 'cleanResponseFiles'));
Note: Here "cleanResponseFiles" is Method of class that will handle ajax request. and $this is pointing current class object.
Procedural style:
add_action( 'wp_ajax_cleanResponseFiles', 'cleanResponseFiles');
add_action( 'wp_ajax_nopriv_cleanResponseFiles','cleanResponseFiles');
Note: Here "cleanResponseFiles" is function added in current theme function.php file and it will handle ajax request.
In this we are considering that ajax request can be made either from wp-admin dashboard or from front-end page/post.
Example ajax request handler method:
function cleanResponseFiles(){
echo "<pre>";
print_r($_POST);
echo "</pre>";
//Always use exit() in ajax request handler function end
exit();
}
Thumb Rule :
Always use exit() method in ajax request handler method, it's essential.
The best practice of sending ajax request is use Wordpress_nonce.
It's just for avoding CRSF (Cross site request forgery ) by adding Honeypot , A hidden input field with generated random key and at in request handler method it should be validated.
These are the methods that we can use for creating Wordepress nonce and verifying Wordpress nonce and ajax request handler or simple http request handler.
Wordpress Nonce Methods:
wp_create_nonce : Used for creating random key for sending in forms as a hidden field.
wp_verify_nonce : Used for verifying random key in request handler method.
I will attach a working example of wordpress ajax call ASAP in this comment.
Just a brief: All ajax post should be sent to admin-ajax.php Each request needs to supply at least one piece of data called action. Based on this action, the code in admin-ajax.php creates two hooks.
if the value of action is cusom_action, wp_ajax_custom_action and wp_ajax_nopriv_custom_ction are auto created. Check WordPress coddex. https://codex.wordpress.org/AJAX_in_Plugins
Refer this https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
Basically you create an action like wp_ajax_myaction, this you can define in your functions.php or somewhere where you seem fit. And then call it as shown in the example(Usage section) on the page.
EDIT:
Adding some code to help you understand
In your functions.php
add_action( 'wp_ajax_my_ajax', 'my_ajax' );
add_action('wp_ajax_nopriv_my_ajax', 'my_ajax');
function my_ajax() {
die( "Hello World" );
}
In your JS:
$.ajax({
url: "http://yoursite.com/wp-admin/admin-ajax.php",
data : {action : 'my_ajax'},
success: function( data ) {
alert( 'The code says ' + data);
}
})
Few things about the code:
This is just a quick and dirty code, mostly ripped off from the example just to show you how it will work.
The no_priv action is used for allowing unauthorized access(i.e to non-admin users as well)
The url is usually not hardcoded in the way shown in the example, people usually pass it to the script using admin_url( 'admin-ajax.php' )
The action, sent in the data determines which function should be called. (my_ajax in our case)
Let know if you still have issues.
I have a PHP script on my server that needs to be run from my clients websites using Javascript in a plain HTML page. After the script is run the HTML page will redirect. The problem is that sometimes the script doesn't run before the redirect happens.
This is the code I am using...
$.ajax({
async: false,
type: 'GET',
url: 'the_URL_of_the_PHP_on_my_server.php',
success: function(data) {
}
});
window.location="the_URL_for_the_redirect";
The PHP script on my server is to track hits/sales etc. Is there are way I can force the page to wait for the script to complete before the page redirect.
The HTML page and the PHP page are on different servers. Also, the HTML page is being used on lots of different websites, so I can't give them all permission to access my server. I'm not sure if that's causing a problem or not.
I don't need any information back from the PHP script I just need it to run.
Thank you.
The success function runs when you get a response (unless it was an error, in which case the error function you haven't defined would run).
If you want some code to run after you get a response, put it inside those functions instead immediately after the code which sends the request.
That said: The point of Ajax is to talk to the server without leaving the page. If you are going to go to a different page as soon as you have a response, then don't use Ajax. Use a regular link or form submission and then having an HTTP redirect as the response.
This is normal, that this situation happens.
because $.ajax is async and won't wait till success method
change your code to
$.ajax({
async: false,
type: 'GET',
url: 'the_URL_of_the_PHP_on_my_server.php',
complete: function(data) {
window.location="the_URL_for_the_redirect";
}
});
UPDATED
changed function success to complete
difference is =>
complete will be called not matters what happened with request
UPDATE 2
think about #Quentin variant by html redirects.
How can I pass data between scripts in PHP without $_SESSION? I need to send the information specifying a method, the thing is that this is a script that will run only on the server side, without interaction with user. Right now, I have a view in which the user do the operations, for that I'm using the ajax provided by jQuery, I have:
$.ajax({
url: "action.php",
cache: false,
dataType: "html",
method: "POST",
data: {
method: "sendMessage",
target: target,
message: message
}});
that works pretty well, but I need to remove the view and the interaction with the user, and make that works without JavaScript. So I want to know, which is the equivalent in PHP to call the script action.php and send it all the data whit the specified method?
Write your function as a function.
include() the file containing your function.
Just call the function passing whatever data you like as an argument.
If you also need to present it as a front end view, then you would write a separate wrapper script and put that on a publicly accessible URL.
I just started learning PHP and was wondering if there is a way to trigger a portion (a function really) of a php script when a user clicks on a link/button without redirecting the user to a new php script page?.
Basically, is there a way to invoke php functions through client side user actions like you have in javascript?.
PHP is not client side. It simply generates a page and sends it to the user's browser.
You would need to incorporate javascript into the page you are returning for client side actions. The most common approach is having javascript make AJAX calls to php scripts on the backend.
Here's how you can do it with JQuery using $.ajax() [Docs]
$('#my-button').click(function(){
$.ajax({
url: 'my_php_page.php?route=my_preferred_function',
data: 'foo=bar',
type: 'post',
dataType: 'json',
success: function(data){
alert('Response = ' + data);
}
});
});
Most MVC frameworks - one example being CodeIgniter allow you to execute specific functions in the controller via the URL: http://domain.com/mycontroller/myfunc. If your function takes two arguments, for example:
public function foobar($foo,$bar){
// do something
}
You can access it via http://domain.com/mycontroller/foobar/abc/123 making your ajax calls super easy.