From the below code I need to display the values of data1. I have declared it by using id as "id="data1". Suggest me how to pass this "data1" as a variable in phpMysql.
<div class="col-lg-12">
<p id="data1"></p>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "projects", "pwd", "projects") or die(mysql_error());
mysql_select_db("projects") or die(mysql_error());
$var='data1';
// Get all the data from the "Race" table and create table
$result2 = mysql_query("SELECT
A.service_center_name,
A.status,
C.branch_name
FROM
customers A
INNER JOIN
ascs B ON A.serv_cent_mob_no = B.contact_number
Inner Join
branches C on B.branch_id=C.id
where C.branch_name='". $var. "'
GROUP BY A.service_center_name ,A.status,C.branch_name;")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Service Center Name</th> <th>City</th> <th>Branches</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result2 )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['service_center_name'];
echo "</td><td>";
echo $row['branch_name'];
echo "</td><td>";
echo $row['status'];
echo "</td></tr>";
}
echo "</table>";
?>
</div>
How to pass the data1 using variable in the below code "$var='data1';".
Solution:
You can use the jQuery AJAX function to parse the data to the desired file of your choosing. More about jQuery AJAX here.
Your AJAX function could look like so:
function postData() {
var data = $('#data1').html();
$.ajax({
type : "POST",
url: "/some/path/some_page.php",
data: { dataVariableName : data },
success: function (html) {
//Success handling
}
})
}
You could then fire the function from a button. For instance:
<button onclick="postData();">Submit data!</button>
In your some_page.php, you will then need to access your POST variable, like so:
<?php
$var=$_POST['dataVariableName'];
//Continue with SQL logic etc.
?>
Explanation:
What we basically did here, is that we encapsulated the AJAX function into another function named, postData, which we can use to call onclick, or however we desire. We could also simply add an onclick event to the ajax function directly, but I thought this would make for an easy understanding.
We then go on to define a variable that contains the data we wish to parse.
Then in our AJAX function, we first define our data type. As you can see in this example, we're using the data type POST. There are other data types that you can define here, and each for a different purpose. Another well-known data type would be GET for instance. I suggest you look up the data types to find out what they mean, and what influence they have. For instance, GET types will show as parameters in the URL.
Next we define what page we are sending our data to, which will be some_page.php in our example.
We then go on to define our POST variable, which is going to contain the data we're supposed to parse. You can parse more than one variable at a time in your AJAX function, by doing so:
data: {
dataVariableName : data,
dataVariableName2 : otherData,
//more variables [...]
},
Note that I also defined a success function in our AJAX function. We can use this to do a lot of things upon success, if we so desire. I.e. redirect to another page, alert(); a success message etc. etc. A lot of things.
If you run into trouble with the SQL, let me know, and I can take a look at that as well.
Important note:
You should really consider switching to mysqli_* or PDO, instead of using the deprecated mysql_* notation. You won't be able to use the mysql_* notation in the newer version of PHP, i.e. PHP 7.0 and forward. You should also look into prepared statements and sanitizing your inputs in general, in case you continue with the mysql_* notation.
using Jquery you can get the data in p tag like below
var pdata = $('#data1').html();
you can post this data to php using jquery Ajax as below
request = $.ajax({
url: "/form.php",
type: "post",
data: pdata
});
In your php, you can make it as
$var = $_POST['data'];
Related
I'm beginning to work with AJAX, and I'm struggling with the next few things.
I'm working in Wordpress, with custom tables.
By the way, that's why the global $wpdb is there.
First, I have a Select, when you choose an option, the ID value will get stored in a variable in jQuery. This is done by the
onchange="selectRequest(this)"
global $wpdb;
$Estado = $wpdb->get_results("SELECT * FROM cor_estado;");
?>
<p>Busqueda por Estado</p>
<select class="select" id="estado" name="estado" value="" type="text" onchange="selectRequest(this);">
<option value="" disabled selected>Seleccione un estado...</option>
<?php
foreach ($Estado as $Estados ) {
echo "<option value='".$Estados->estado_id."' type='text'>".$Estados->nombre_estado."</option>";
}
?>
</select>
The Select will fill up with the id on value and the name.
This is my jQuery, but I'm having a problem here, if I leave everything on the jQuery(document).ready(){CODE HERE}, the Function selectRequest(id), won't work at all, I don't know if that has anything to do with the way that I am getting the id from the select.
Here it changed, now I am trying to receive HTML, I created the complete table on "table.php", and now I am trying to get it back
<script type="text/javascript">
function selectRequest(id){ // id of select
var selectVal = jQuery(id).val(); // currently selected
selectVal = selectVal.toString();
alert(selectVal);
jQuery.ajax({
type:"POST",
url:"<?php echo get_template_directory_uri(); ?>/table.php",
dataType: "html",
data:{selectVal:selectVal},
success:function(resultHtml){
jQuery("#resultado").html(resultHtml);
},
error:function(resultHtml){
alert("What follows is blank: " + data);
}
});
}
</script>
my PHP is like this at the moment, one big change was in the WHERE, since I am using an INNER JOIN, I needed to specify on which table the "estado_id" was going to be, since Wordpress uses table prefix, it was necessary to add it in this place too.
Like I said before, I decided to build the table here, and send it to AJAX with an echo, I created $table, and each time something was created inside the table, I added it with ".=".
Testing this inside the table.php without the "If(isset($_post['selectVal']))", and having an static ID it worked on the table.php document, but if I echo $table, I get nothing on AJAX, it appears as blank.
<?php
//table.php
global $wpdb;
if(isset($_POST["selectVal"])){
$Estado_id = $_POST["selectVal"];
$Estado = $wpdb->get_results("SELECT * FROM cor_municipio INNER JOIN cor_estado ON cor_municipio.estado_id = cor_estado.estado_id WHERE cor_estado.estado_id = $Estado_id;");
$table = "<table>";
$table .="<thead>";
$table .="<tr>";
$table .="<th>Municipio</th>";
$table .="<th>Estado</th>";
$table .="</tr>";
$table .="</thead>";
$table .="<tbody>";
foreach ($Estado as $row) {
$table .="<tr>";
$table .="<td>".$row->nombre_municipio."</td>";
$table .="<td>".$row->nombre_estado."</td>";
$table .="</tr>";
}
$table .="</tbody>";
$table .="</table>";
echo $table;
}
?>
This is the HTML div where I want to display the echo $table content. At the moment if I select an option, the only thing that happens is that the P element disappears.
<div id="resultado">
<p>Estado Seleccionado</p>
</div>
The new problem is receiving this echo $table and displaying it where AJAX receives it.
instead of receiving data in JSON format, use HTML formatted data & replace your data directly in table. Using that your base issue "the amount of information in them will be different on each select option" will be resolved.
There's not a fixed rule... Sometimes is faster to create the html in the php and return it formatted so you can show it directly and sometimes is better to return raw data and handle it in javascript/jquery.
If the data you get from the ajax request is just for showing and you don't need to modify anything that depends of other elements in your current view, I will format the html response directly in the php. If you need to change something, then maybe I will go with JSON.
In your ajax request you establish JSON as the data format, so the response in your PHP has to be JSON. You almost have it. Uncomment the foreach but instead of independent variables ($info1, $info2) create an array with the fields you need for your response, and set key names. For example...
$response = array();
foreach ($Estado as $row) {
$response['municipio'] = $row->nombre_municipio;
$response['estado'] = $row->nombre_estado;
.....
}
Once you have the array created, convert it to JSON and return with...
print_r(json_encode($response));
Then, in your jquery ajax success function you can access each field with...
data.municipio or data['municipio']
data.estado or data['estado']
...
I hope it helps
So, the basic problem here was that I was following the steps to do this using the tools (JS, PHP, HTML and CSS) outside the Wordpress environment, this was the issue. I'm still solving some aspects about my AJAX request, I will try to update this answer as fast as I can.
In this Wordpress Codex entry, they explain it in detail.
Basically Wordpress has it's own way of using AJAX, so no matter if this 'looked' correct to me, the Wordpress site wasn't going to display anything from it.
Here is the solution that I used to solve my problem.
<!-- language: lang-js -->
UPDATED CODE
jQuery(document).ready(function() {
jQuery('#estado').change(function() {
var selectVal = jQuery('option:selected').val();
selectVal = selectVal.toString();
jQuery.ajax({
url:"/cors/wp-admin/admin-ajax.php",
type:"POST",
data:{action:'my_action', selectVal: selectVal},
success:function(data){
jQuery("#municipio_result").hide(500);
jQuery("#municipio_result").removeData();
jQuery("#municipio_result").html(data);
jQuery("#municipio_result").show(500);
},
});
});
});
STEP #1
/wp-admin/admin-ajax.php //will be the URL for all your custom AJAX requests.
This is absolutely necessary, because this document verifies the AJAX 'actions', and points them to your functions.php
STEP #2
data:{action:'your_action_name', val1: 1, val2: 2 ...}
The first variable that you have to send will always be action, the value can be the anything you want.
As I said earlier, admin-ajax.php looks for the variable action when it receives an AJAX request from any file, it will look for action, once it finds it, it will redirect it to the functions.php file located inside your_theme folder.
STEP #3
Inside you functions.php file, you will add the PHP code as a function, like this:
<!-- language: lang-sql -->
function selectEstado(){
global $wpdb;
if(isset($_POST["selectVal"])){
$Estado_id = $_POST["selectVal"];
$Estado = $wpdb->get_results("SELECT * FROM cor_municipio INNER JOIN cor_estado ON cor_municipio.estado_id = cor_estado.estado_id WHERE cor_estado.estado_id = $Estado_id;");
$table = "<table>";
$table .="<thead>";
$table .="<tr>";
$table .="<th>Municipio</th>";
$table .="<th>Estado</th>";
$table .="</tr>";
$table .="</thead>";
$table .="<tbody>";
foreach ($Estado as $row) {
$table .="<tr>";
$table .="<td>".$row->nombre_municipio."</td>";
$table .="<td>".$row->nombre_estado."</td>";
$table .="</tr>";
}
$table .="</tbody>";
$table .="</table>";
echo $table;
wp_die();
}
}
add_action('wp_ajax_my_action', 'selectEstado');
add_action('wp_ajax_nopriv_my_action', 'selectEstado');
STEP #4
Inside your functions.php file you will create a function, can be called whatever you want, for example 'your_function_name'.
To access easily to the database, Wordpress uses the variable $wpdb, by including the line like this global $wpdb; now you can use it to access the database without any problems.
Now you have to check if the values after action got there, the if(isset($_POST)) will take care of it. To check the Database, you use the $wpdb->get_result("");
Basically what I am doing with the INNER JOIN, is checking a column name, and checking where the two tables match, and then pulling the rest of the columns that the element on the table has in "cor_municipio" and "cor_estado".
(In this code I am using JOINS, if you want to know more about them, I'll leave a link below)
Here they explain JOINS with Venn diagrams
Then I created a variable that each time a part of the table was created, it was being added to it.
You echo your data, and don't forget "wp_die();"
STEP #5
This is the last part to have your AJAX request working on Wordpress.
The next two lines are very important for it to work, this is the action that admin-ajax.php is looking for, and it's here that it references it's value, these lines look like this for every new AJAX request you need to make:
add_action('wp_ajax_', '');
add_action('wp_ajax_nopriv_', '');
this is the "default" way the lines are written, but you will need to complete them with two things.
The action value you used in the AJAX request, in my case is 'my_action', or in this example 'your_action_name'.
The second value is the name of the function created inside your functions.php file.
It will end up looking like this for me:
add_action('wp_ajax_my_action', 'selectEstado');
add_action('wp_ajax_nopriv_my_action', 'selectEstado');
Using the value of 'your_action_name' and 'your_function_name':
add_action('wp_ajax_your_action_name', 'your_function_name');
add_action('wp_ajax_nopriv_your_action_name', 'your_function_name');
The first line is for logged in users, and the second one is for visitors, if you want to display something different for logged in users and another one for visitors, you will need to create a function for each of them, and just use one attribute.
add_action('wp_ajax_your_action_name', 'your_function_name1'); // for registered users
add_action('wp_ajax_nopriv_your_action_name', 'your_function_name2'); // for visitors
Again, this is PHP code written in admin-ajax.php, if you want to look deeper into it.
I already found out my problem, when I was sending the data on the first time I was using:
data:{action:'my_action', selectVal: 'selectVal'},
Basically what I was sending to Wordpress on selectVal, was the string
selectVal
So when my function tried to find the id based on the receiving data, it wasn't going to find anything, because it was a string with those letter.
SOLUTION
jQuery(document).ready(function() {
jQuery('#estado').change(function() {
var selectVal = jQuery('option:selected').val();
selectVal = selectVal.toString();
jQuery.ajax({
url:"/cors/wp-admin/admin-ajax.php",
type:"POST",
data:{action:'my_action', selectVal: selectVal}, // The right way to send it
success:function(data){
jQuery("#municipio_result").hide(500);
jQuery("#municipio_result").removeData();
jQuery("#municipio_result").html(data);
jQuery("#municipio_result").show(500);
},
});
});
});
What I am sending now is the value, and now my AJAX success:function, receives the complete table, I also changed the jQuery code, because in the first example, when adding ".hide() or .show()", it was sending multiple errors.
To add conditions by user role you can edit the admin-ajax.php to make it simpler for all the AJAX requests.
I know is way too long, but if you were having some trouble, I wanted to explain all the different elements that are used, to make it easier to understand what is happening with AJAX in Wordpress.
I'm very new to php and SQL so i'm really sorry if this is very trivial.
My site has multiple divs with table names inside it. The HTML is of the form:<p class="listname">(table name)</p>
I am trying to write a function so that when a user clicks on a div, the function gets the text using innerHTML and the contents of that particular table are shown.
The jquery function i wrote is:
$(document).ready(function(){
$(".listname").click(function(){
var x=($(this).html()).toLowerCase(); //this assigns the text in the class listname to the variable x
console.log(x);
$.ajax({
url: 'http://localhost/fullcalendar/events.php',
data: {name:x},
type: "GET",
success: function(json) {
}
});
});
});
And my PHP code is:
<?php
include 'ChromePhp.php';
ChromePhp::log('php running');
$json = array();
if($_POST['name']!=null)//check if any value is passed else use default value
{
$table=$_GET['name'];
ChromePhp::log($table);
}
else
{
$table= 'event';
ChromePhp::log($table);
}
$requete = "SELECT * FROM `$table` ORDER BY id";
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
When i first load the website, the default value for $table is used in the query, and data is retrieved. However, when i try clicking on a div, the correct value is passed to php and assigned to $table (i checked in the console) but the data displayed is of the default table i.e 'event' table.
How can i fix this?
PS: all my tables are in the same database.
You're checking the POST data:
if($_POST['name']!=null)
But using GET data:
type: "GET"
So the $_POST array will always be empty and your if condition will always be false. You probably meant to check the GET data:
if($_GET['name']!=null)
Also of note are a couple of other problems in this code:
Your success callback is empty, so this AJAX call isn't going to actually do anything client-side. Whatever you want to do with the returned data needs to be done in that success function.
This code is wide open to SQL injection. It's... very unorthodox to dynamically use table names like that. And this is probably an indication that the design is wrong. But if you must get schema object names from user input then you should at least be taking a white-list approach to validate that the user input is exactly one of the expected values. Never blindly execute user input as code.
I have a table containing data read from a MySQL database via PHP. The first column holds all item names. Now, on clicking a td element in the first column of the table would link to a page with more detailed information about the item contained in the td.
Now I came up with the following idea:
$(document).ready(function() {
$('#table td:first-child').click(function() {
$('div.main').animate({
height: "50px"
}, 600);
setTimeout(function() {
$('div.data').fadeIn(1000);
}, 600);
});
});
div.main is the div-container that has the table included. What I want to do now is to slide that container up and fade a new div-container in, right below it, the new container include()s a PHP page which holds a dynamic query (pseudocode, no string escaping, simplified version):
SELECT detail FROM items WHERE items.name = $_GET['name'];
What I couldn't figure out is if and how I can tell the PHP file that is included in the in-fading div-container which item name it has to grab details for, off the database.
Right now I can read the item name via JavaScript/jQuery, but I couldn't figure a way out to pass that value to the PHP file without having to reload the page.
Any ideas or suggestions welcome!
I think what you're looking for is asynchronous JavaScript and XML (AJAX). It sounds intimidating, but fortunately jQuery makes it very easy.
You can call $.ajax() directly, but for most cases, you can use one of the convenience wrappers. In this case, I think $.load() will meet your needs.
So, let's say your PHP file is called detail_ajax.php and it returns the HTML you wish to put in your div (with class data). All you would have to do then is this:
$('div.data').load( '/detail_ajax.php', function(data){
$(this).html(data);
});
If you want to pass data TO detail_ajax.php, you can pass it along this way:
$('div.data').load( '/detail_ajax.php', { 'someField' : 'someValue' },
function(data) {
$(this).html(data);
}
});
In detail_ajax.php, if you examine $_POST['someField'], you will see the value passed in.
You can do this by using ajax. Output your query on a separate page in JSON format then fetch it using jquery ajax
you need to use ajax to do the same thing. create an event like onclick and call a
method on click call ajax set variable in js and pass it to and do as you want,
show data in particular div in response. Hope it will help you.
You are looking for $.ajax(). However, 3 things will need to take place for this to happen as you intend.
First, we need a reference held in the HTML that is generated by the table so we can streamline the server request. When you generate the table, add a unique data-name string to the TD.
<td data-name="<?php echo $row['name']; ?>">
If, for instance, the td's were generated in a foreach loop, where we expect an array to be returned.
Now, we need to detect the request on our page so we can properly return the data to the browser, we'll look for $_GET['name'] as per your example.
<?php
if(isset($_GET['name'])):
$mysqli = new mysqli('host', 'user', 'pass', 'db');
$ret;
if($stmt = $mysqli->prepare('SELECT detail FROM items WHERE items.name = ?')):
$stmt ->bind_param('s', $_GET['name']);
$stmt ->execute();
$stmt ->bind_result($details); // we only want one column
$stmt ->fetch(); //get our row
$ret['success'] = TRUE;
$ret['html'] = '<div>'. $details .'</div>';
else:
$ret['success'] = FALSE;
endif;
echo json_encode($ret); //return to the browser
endif;
?>
Now we need to employ ajax to bridge the gap between the server and the browser.
Edit - I forgot to modify the click function.
$('#table td:first-child').click(function() {
$('div.main').animate({
height:'0px'
}, function(){
//once the animation completes
$.ajax({
url: '/',
type: 'GET', //this is default anyway
data:{name: $(this).data('name')}, //send the name from the td clicked
dataType: 'json', //what we expect back from the server
success: function(data){ //will fire when complete. data is the servers response
if(data.success !== false){
$('div').html(data.html);
$('div.main').animate({
height: "50px"
}, 600);
}else{
alert("Something went wrong");
}
}
});
}, 600);
});
This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication
What I'm trying to do is create a slideshow by grabbing database information and putting it into a javascript array. I am currently using the jquery ajax function to call information from a separate php file. Here is my php code:
mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$i = 0;
$sql = mysql_query("SELECT comicname FROM comics ORDER BY upldate ASC");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo "comics[" .$i. "]='comics/" .$row['comicname']. "';";
$i++;
}
What I want is to create the array in php from the mysql query and then be able to reference it with javascript in order to build a simple slideshow script. Please let me know if you have any questions or suggestions.
Ok have your .php echo json_encode('name of your php array');
Then on the javascript side your ajax should look something like this:
$.ajax({
data: "query string to send to your php file if you need it",
url: "youphpfile.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]); //this should tell you if your pulling the right information in
}
});
maybe replace data.length by 3 or something if you have alot of data...if your getting the right data use a yourJSArray.push(data[i]); I'm sure there's a more direct way actually...
You may want to fetch all rows into a large array and then encode it as a JSON:
$ret = array();
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
$ret[] = $row
echo json_encode($ret);
Then, on the client side, call something like this:
function mycallback(data)
{
console.log(data[0].comicname); // outputs the first returned comicname
}
$.ajax
(
{
url: 'myscript.php',
dataType: 'json',
success: mycallback
}
);
Upon successful request completion, mycallback will be called and passed an array of maps, each map representing a record from your resultset.
It's a little hard to tell from your question, but it sounds like:
You are making an AJAX call to your server in JS
Your server (using PHP) responds with the results
When the results come back jQuery invokes the callback you passed to it ...
And you're lost at this point? ie. the point of putting those AJAX results in to an array so that your slideshow can use them?
If so, the solution is very simple: inside your AJAX callback, put the results in to a global variable (eg. window.myResults = resultsFromAjax;) and then reference that variable when you want to start the slideshow.
However, since timing will probably be an issue, what might make more sense is to actually start your slideshow from within your callback instead. As an added bonus, that approach doesn't require a global variable.
If this isn't where you are stuck, please post more info.