Show data in PHP with AJAX - php

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.

Related

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();
}
});
}
}
);
});

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

AJAX function call within Joomla Component

I have a good understanding of AJAX and normally would have no problems using it but I am relatively new to Joomla and have only recently started building components, etc.
I have created a component (named directory) which is using the 'default' view. Within here I have the following code which is an AJAX call:
<script type="text/javascript">
var url = "index.php?option=com_directory&view=directory&task=clubFilter&format=raw";
jQuery(document).ready(function() {
jQuery('#city').change(function() {
jQuery.ajax({
url: url,
type: "POST",
data: jQuery("#city").serialize(),
dataType: 'json',
success: function(data) {
alert('data');
}
});
});
});
And within my 'views/directory/views.html' file I have created the following function which currently contains a die so I can confirm when it is working:
public function clubFilter() {
die(print_r('here_i_am'));
}
When I run the following code I ge the following error within Firebugs console..
'Error: 500 View not found [name, type, prefix]: directory, raw, directoryView'
I think it is because of the AJAX url var being incorrect but I have tried many different solutions from here nad other sources and just can't get the AJAX function working. Is my URL wrong?
Many Thanks
Normally, I make ajax calls to a task on the controller.
Here is the url format I am using in one of my extensions that uses ajax calls to a component:
index.php?format=raw&option=<component_name_goes_here>&task=<task_goes_here>
Then, in my component's default controller I put a function with the same name as the task:
function getSomeData()
{
echo(json_encode($data));//I normally return json
}
Hope this helps.
try this url. it might help you out.
var url = "index.php?option=com_directory&view=directory&task=clubFilter&tmpl=component";
format=raw replace with &tmpl=component
Else you can try the below format too.
jQuery.post('index.php',{
'option':'component_name',
'controller':'controller_name',
'task':'task_name',
'format':'raw',
'data': jQuery("#city").serialize(),
'dataType': 'json',
},function(result){
//edit the result here
return;
});
If you have any problem regarding this don't hesitate to ask.

Refer jQuery .ajax Post to function

Is it possible to refer an AJAX POST to a specific function within a PHP file?
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: "some data...",
success: function(){
alert('Success!');
}
});
Or is there a way to have functions.php receive data and know what to do with it? If not, are there any other suggestions for getting data over to mySQL (using PHP/jQuery)? Thanks!
The data sent to the php file using POST can be accessed in php using:
$datasent = $_POST['name'];
Given that you sent data as:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
Not directly. You'd need to post certain data, and have PHP check the POST variables to choose the correct function.
Perhaps have a look at some tutorials (unfotunately the jQuery links for php tutorials are broken).
Is it possible to refer an AJAX POST to a specific function within a PHP file?
No. jQuery doesn't know what PHP is, even less what a PHP function is. jQuery talks to server side urls. Whether those urls are static html files, PHP scripts, Java servlets, Python I don't know what, CGI scripts, is not really important.
So you could use the data setting to pass parameters to this server side url which based on the values of those parameters could invoke one or another function.
If you want to call a specific function, change ur jquery:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {function:"doSomething",name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
In your php add:
call_user_func($_POST['function']); // This will call what ever function name is passed as parameter
function doSomething(){
echo $_POST['name'];
}

Calling methods or functions with Jquery

So I can call a php page using jquery
$.ajax({ type: "GET",
url: "refresh_news_image.php",
data: "name=" + name,
success: function(html) {
alert(html)
$('div.imageHolder').html(html);
}
});
However this getting a bit messy, I have a few .php files that only really preform very simple tasks. If I want to call a method
$images->refresh_image();
is this possible. Failing that I could just create a big file with lots of functions in it?
Thanks,
Ross
Well, depends on what the intention is, of course, but if you really only want to run the refresh_image function, you don't need to pass any data, you don't have to handle success etc, then this isn't messy:
$.ajax({
url: "refresh_news_image.php",
});
You could also create a general function, such as:
function php_func(name){
$.ajax({
data: { name: name }
url: "background_functions.php",
});
}
And then background_functions.php:
switch($_GET['name']){
case 'refresh_image':
$images->refresh_image();
break;
case 'something else':
something_else();
break;
}
In javascript, whenever you need it (perhaps on an onclick) then you'd simply invoke:
php_func('refresh_images');
Be careful not to use the GET-parameter to run whatever function is passed, as that's obviously a huge security risk. :-)
You cannot call php functions directly from jQuery because jQuery knows nothing about php. You could create a file that based on a given request parameter calls the respective function and returns the result.

Categories