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

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

Related

WordPress simple function call blocks page loading

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 :-)

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

Show each response of php file using ajax

I use ajax type for send data to php file and get response and show. In my php file i have
while($i<14){ echo $i.'<br />'; $i++;}
that return 14 replay.
So, my webpage when call data with ajax method, after some secounds, show all 14 results. But i want get live response from my ajax file.
So i want my webpage show :
1
...
and then
1
2
....
etc
This is my Ajax code that return all response together in shower div.
I want get live responses. for any responses that sent from php file
function update_table(uptype){
$("#shower").html("Loading...");
var dataString = 'type=' + uptype;
$.ajax({
type: "POST",
url: "motor.php",
data: dataString,
cache: false,
success: function(html) {
$("#shower").html(html);
}
});
return false;
}
What you are asking is not possible with your current setup.
Think of an ajax-call to a PHP-script is like visiting a website like www.example.com/yourscript.php
PHP will then server-side render a code which is sent to your web-browser. This is a one call and one answer operation. PHP will not dynamically add elements to the website. Neither will it then be able to dynamically send answers to your ajax-call. What you have to do to solve this is storing the progress of the PHP script somewhere, and do several calls to get a update on the status.

php script from Ajax stops loading after browser is closed

A site Im working on builds a pdf based on the clients input, I have decided that once the purchase is complete thats when the pdf will begin to get generated. The reason is the pdf may be up tp 50/60MB and I dont want the client to have to wait for this to complete.
Im using Opencart and on the checkout success page I have an Ajax command loading a PHP script.
I was under the impression that the user could close the page once the script starts, but for some reason I find I have to wait for 5/10 seconds before closing if I want the file to appear on my server.
Its a little difficult to debug as part of testing involves closing the browser immediately.
Here is my Ajax...
$(document).ready(function() {
$.ajax({
url: 'index.php?route=pdfengine/pdfengine/generate_final_pdf',
type: 'post',
dataType: 'json',
data: {
},
beforeSend: function() {},
complete: function() {},
success: function(json) {}
});
});
and my php (currently Im loading huge images on it to represent the load time)
public function generate_final_pdf() {
include('convert-to-pdf/mpdf.php');
$mpdf=new mPDF();
$stylesheet = file_get_contents(DIR_APPLICATION.'view/theme/rascal/stylesheet/stylesheet.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML('<html><body><div class="pdf-test-style"><img src="http://example.com/top_quality_image.jpg" />test</div><pagebreak><img src="http://example.com/top_quality_image2.jpg" />test<pagebreak><img src="http://example.com/top_quality_image3.jpg" />test</body></html>',2);
$mpdf->Output(DIR_FINAL_PDFS.'order_idpdfid-'.$this->session->data['pdf_id'].'.pdf','F');
}
EDIT:
Just adding more info that Ive tried since reading those articles and seeing the responses,
So on the file where the ajax is Ive set..
ini_set('ignore_user_abort',true);
and in the function that the ajax calls Ive set...
ini_set('ignore_user_abort',true);
set_time_limit(0);
For the first one I ran phpinfo() and it did confirm to me that ignore_user_abort was on, meaning obviously that part isnt an issue.
Use ignore_user_abort(true) to keep the script running even if the user closes the page.

jQuery update div the moment a table is updated

I'm trying to figure out a way to have jQuery update a div the moment a table in mysql is updated. I've spent a vigorous amount of hours searching online for an answer, and so far, nothing. Can anyone help me out with this problem?
Well the steps you should probably take are:
Have a piece of AJAX code that queries the server for a change (like row count changing or something along those lines). Using jQuery you can do that:
function checkUpdates()
{
$.ajax({
type: "POST",
url: 'hasDataChanged.php', // a webservice or other URL that queries the database
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// return a JSON string like { "hasChanged" : "true" } or something
if (data.hasChanged) {
// data has changed, do something
}
}
});
}
Then you can use the Javascript method setInterval to call the code every few seconds. It is unrealistic to do it instantly.
$(document).ready(function() {
setInterval("checkUpdates()", 3000); // Calls the function every 3 seconds
});
You'll have to poll the database via ajax and php every (couple of) second(s) and check if the data has changed. if so, update the div.
i don't think there's a way of detecting the exact moment the db is updated.
Useful links on polling. It attempts to make server send data to browser:
http://onepixelahead.com/2010/04/30/html5-web-sockets-example/
http://en.wikipedia.org/wiki/Comet_(programming))

Categories