I restarted my old project and have a question regarding old code. 3 years ago I had this type of code to sent data from database to JavaScript arrays using php:
echo json_encode($result_array);
and JQuery:
$.ajax({
type : "POST",
url : "poli.php",
success : function(data) {
poli_owner = $.parseJSON(data);
},
async : false
});
to populate JavaScript array.
My question is - is it still good code or not recommended anymore. If the code is not OK what code is better to use to take data from database and populate JavaScript array using php and JQuery? Thank you.
Yes, it is still good. All the web is still using Ajax and JSON.
Depending on your use case, you can load your data via a separate Ajax request, or just make your server-side language generate data for JS and include it in the page source code.
Related
I have a JQuery script which dynamically generates HTML elements on button click.
I am connecting to a mysql database using PDO and PHP but am wondering how you can target dynamically generated variables in an external JS file directly from PHP.
I have tried using AJAX but as far as i can understand it seems to only get data from PHP pages and not the opposite.
The JQuery code is like this...
//Where i want to use indexes from a lookup table to populate the select element
$("#main").append('<select><option value=""></option></select>');
I tried AJAX in this way
function getData(dataToPass)
{
$.ajax({
type: "POST",
url: "getData.php",
data: dataToPass,
success: function (returnedData)
{
$("#main").html(returnedData);
}
});
}
But you cant pass variables this way can you?
Im very new to PHP and JQuery and would appreciate the help.
First off, PHP has nothing to do with JavaScript. They are totally different languages, in their own separate domain. They co-work however if you want to. PHP can generate JavaScript code, which will then run on the client browser. The client browser though has no idea that the JavaScript code that is running was generated by PHP. Neither does PHP have any idea how to work with a browser. PHP doesn't even have any idea about HTML.
Thus, you can't pass to PHP a complex JavaScript object, the same way as you can't pass an object from PHP to JavaScript. However you CAN pass values and data structures (arrays, data objects).
In this case, you can either get the inner HTML code of the jQuery object in your JavaScript, by running
dataToPass = {html: $("#main").html()}; //it will be a string
or by constructing an object that will have just the data you need, for example:
dataToPass = {elements: [
{node: "select", options: [{node: "option", value: ""}]},
{node: "input", value: "someValue", type: "text"},
]};
As you have this JavaScript, it will send this data via the script you already have, to the server. On the server side you will have to intercept the $_POST superglobal, and ask for either the HTML string, which will be $_POST['html'] if you chose the first example, or access an array of elements by $_POST['elements'] if you used the second example.
I have one quick question for experienced ones.
I have a page that does a jquery ajax post to another php page with javascript in it.
My question is, will the javascript get executed as well?
Another question.
lets say, that instead of javascript, I have another jquery ajax post request to a third php.
Will any of the 2 work?
Unless the javascript in that "another php page" is actually returned to the client and somehow inserted into the DOM, the JS cannot and will not execute. The resulting output of an AJAX operation is returned as a string to the code that performed the ajax call. It's not interpreted/parsed except in a few very specific cases.
If you're using jQuery's AJAX function to send POST variables to a PHP file, only the backend code will be executed. However, upon success of the AJAX call, you can execute some more JS code as follows
//Define whatever variables you want to pass along to the PHP file
var variable = "";
$.ajax({
url: "file.php",
type: "POST",
data: "variable="+ variable,
success: function(data)
{
//Upon success of the call, you can execute JS code here
}
});
Additional info here
I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:
JQUERY:
$.ajax({
type: "POST",
url: post_url,
success: function(group) //we're calling the response json array 'tree'
{
//WANT TO CALL THE PHP FUNCTION HERE
} //end success
}); //end AJAX
PHP:
<?php
foreach($groups as $group){
echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server.
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server. This is because javascript executes client side and PHP executes server side. Therefore, javascript does not have direct access to PHP functions.
You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.
Can you replicate the functionality of the PHP function with a JavaScript function?
Would this, or something similar, work for you:
$.ajax({
type: "POST",
url: post_url,
success: function(groups) //we're calling the response json array 'tree'
{
for(group in groups){
document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
}
}
}); //end AJAX
Alternatives:
Change the PHP that backs the original AJAX call so that, instead of sending back JSON, it sends back HTML exactly as you want it.
Chain a second AJAX call "inside" the success of the first, so that a second round-trip to the server is done for the JSON->HTML conversion.
Accept that sometimes you need to "duplicate" presentation-rules when you are working with multiple languages, and use something like EJS to do the same <option> stuff that PHP does elsewhere.
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).
Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.
If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.
I'm looking to display data from a table in a mysql database using PHP, however, I want the data to automatically update itself and retrieve current values every 5 seconds.. WITHOUT having to refresh the page. Is this possible? Maybe with JQuery/ AJAX? If so, please explain how it can be done / point me to a resource where I can find such information
Thanks
If you use window.setInterval() and jQuery's .load() you should be able to do what you want. The PHP script should return the HTML that needs to replace the previous one.
Javascript:
function refreshData()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#container').load('path/to/script.php');
}
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
A really basic example:
function poll(){
$.ajax({
type: "GET",
url: "your/php/script/",
success: function(data){
// do something with data
}
});
};
setInterval(poll, 5000);
jQuery is a good option. Here are the docs for ajax.
You will want to make this call with setInterval
Something like this might get your started.
setIntervla(updateFromDb,5000);
function updateFromDb(){
$.ajax({
url: "getUpdates.php",
success: function(){
$(this).addClass("done");
}
});
};
What you are describing is exactly the type of the AJAX is used for, AJAX allows for asynchronous requests to be made to your server.
For learning I would suggest using a framework like Jquery and look into the AJAX api.
Basicly you will need a PHP script that query the database and responds the results the way you want them. A suggestion would be to JSON encode them.
In JavaScript on the client you will need to you things like:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "yourpage.php",
success: function(data){
//HANDLE DATA
// use JSON.parse(data); if your JSON encoding your data
}
});
},5000)
Just go to the documentation of jQuery:
http://api.jquery.com/category/ajax/
Use the command "jQuery.get()" or better "jQuery.getJson()" to make a http request to the server. Use JSON to get a better communication between server and client. Return from server side a json string and convert this on the client to an javascript object. (the function jQuery.getJson already do this for you) so you can easily access the key and values in the data array.
Just an example:
SERVER Part with PHP:
<?
$data = array('key'=>'value');
return json_encode($data, true);
CLIENT Part:
$.getJSON('myurl.php', function(data) {
// THIS ONE IS CALLED with your PHP data
alert(data.key);
});
$(function(){
window.setInterval(function(){
$.post("filename.php",{'field1':field1,'field2':field2,'field3':field3},function(data){
//callbackfunction(data)
})
},30000);//millisecs
});
And have your php file do all your sql
i followed this tutorial and also the official one about jquery using ajax and php and had no luck whatsoever. If I use an xml file instead of a php file for pulling data with jquery everything works splendidly.
(All this on a LAMP server, php works for sure(running joomla with the same configuration))
This is standard ajax usage
$.ajax({
url : url
success : function(data) { //do stuff with data here }
})
Decide what kind of data you are passing and what is returned from ajax.