Reputation: 95
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...');
}
});}
Upvotes: 0
Views: 147
Reputation: 28196
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.
Upvotes: 0
Reputation: 52
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.
Upvotes: 1