WordPress simple function call blocks page loading - php

I am currently writing my first WordPress plugin.
If I now make a jquery ajax call on a click and call a php function, even if in this function is only sleep 10 and wp_die(), and I try during this to load the page in the frontend, the page loads only after the 10 seconds are over.
this call blocks the whole page at that moment. Why?
Here is my js
var data = {
'action': 'my_export_retailer_import',
'csv_file_path': csv_file_path
};
$.ajax({
type: 'POST',
url: ajaxurl,
data: data,
success: function(data){
}
});
Heres the PHP Function
add_action('wp_ajax_my_export_retailer_import', 'my_export_retailer_import', 30);
function my_export_retailer_import() {
sleep(10);
wp_die(); // this is required to return a proper result
};
// ----------
Edit:
I have been able to identify the problem. When starting the website, there is a session_start() in the functions.php.
If I comment this out, all is well.
Fortunately, I don't actually need the session at that moment. Just a little redo in another function :-)

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

Self-POST AJAX request

I am having some issues running an AJAX request to the php class that contains the AJAX request. The AJAX request is called used a button, and works partially.
My AJAX request is held in a header.php file, which is included in my kpi2.php. If I specify the "url" for the AJAX call to a test file (in the same directory) the POST is successful and I can see the output. I was under the impression if I removed the "url" option it would indeed post to the same page, what am I doing wrong here?
function executeRefresh(){
if (control){
$(".loader").show();
$.ajax({
type: "POST",
data: { refresh: '1' },
success: function(json) {
if(!json.error) location.reload(true);
$(".loader").hide();
}
});
}
}
Output when no url is specified (meaning it should be posted to the same file that is calling the AJAX)
Written from /home/kpi/pages/kpi2.phpArray
(
)
This is the output when I have the option url: "test.php" (which has the exact same output but just in a different file.
Written from /home/kpi/pages/test.phpArray
(
[0] => refresh
)
EDIT:
To obtain the output generated from above, a simple export.
$v1 = print_r(array_keys($_POST),true);
$fp = fopen('../data/output.json', 'w');
fwrite($fp, 'Written from /home/kpi/pages/test.php'.$v1);
fclose($fp);
As for the control variable, it is just a simple listener that is true/false depending if the control key is clicked. It does indeed work and I've never had issues with it before.
As for the location.reload() I tried removing it and now it seems that it isn't even writing the php code now.
Originally in the header.php I had a button on the navbar that would call the AJAX function thus having the kpi2.php (which included the header.php) to have something posted to it. Once it was posted it would then call another php class.
Instead what I did was get rid of the onclick=executeRefresh() and then just listened to the button press specifically in the kpi2.php class. This way I could instantly execute the AJAX request to the other class without the un-needed post request to the class.
$(function() {
$(".btnRefresh").click( function()
{
if (control){
$(".loader").show();
$.ajax({
url:"../setup/kpi_quality.php",
type: "GET",
data: { casp: 'AVANT-CAP-321' }, // name of the post variable ($_POST['id'])
success: function(json) {
//if(!json.error) location.reload(true);
$(".loader").hide();
}
});
}
}
);
});

Show data in PHP with AJAX

I'm novice with Ajax syntax. So I create my load content with append but, I want to know if its possible with PHP? Say to ajax "Learn this php file to display data" and on my PHP file we find a while or foreach with the data of my json file.
I want to use it in PHP because I use this template in some file (this "append") was normally call in 10 files, so i don't want to copy and paste all code, I need to change something, I want to edit only one file.
This is my actually ajax file:
$.ajax(
{
url: 'http://localhost/concerts/json/getConcerts?date=previous&limit=10&offset=' + i++ + '',
type: "get",
dataType: 'json',
success: function (data) {
$.each(data, function (idx, elem) {
$('#concertHome').append('<div>'+elem.bID9+'</div>')});
},
error: function () {
alert('Erreur lors de la requête...');
}
});}
PHP scripts execute when you open a file and before everything else (It's server side language). Ajax calls exectue when the Javascript is completely loaded. (After php).
So you cant do that. they cant communicate with each other without someting like Ajax Call or Fetch etc.
It seems to me that you do not necessarily need to have the Ajax code portion in a PHP file. What you really require is some reusable chunk of code that you can apply in various places within the same page or, in your case, in different pages.
What you should take from the itsolutionstuff post is the idea of putting the Ajax call into a function which you can then call with varying arguments like:
function doAjax(params)
$.ajax(
{
url: 'http://localhost/concerts/json/getConcerts?date=previous&limit=10&offset='
+ (params.i++),
type: "get",
dataType: 'json',
success: function (data) {
$.each(data, function (idx, elem) {
$(params.target).append('<div>'+elem[params.prop]+'</div>')});
},
error: function () {
alert('Erreur lors de la requête...');
}
});}
}
You should put this code segment into a separate .js file which can then be included into all your pages with a <script src="ajaxcode.js"></script> directive. Each time you want to trigger the ajax event you need to call the function doAjax(actualParamaterObject). The actualParameterObject contains various properties to be used in the function, like - for example -
actualParameterObject={i:25, prop:'bID9', target:'#concertHome'};
Handing down the offset i inside this parameter object will have the desired side effect that it will be incremented within the function call. Handing it down as a direct argument would not work in this way.

Wrong request url with ajax?

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.

Passing data using $.ajax to PHP leaves $_POST empty [duplicate]

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");
},
});
}
});

Categories