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.
Related
I'm creating a small project using php and jax, when I fetch data to database and display to a textbox using specific variable declared in may query it is working but when I try to use declared variable it is not working.
For example:
SELECT remaining FROM sys_stocks WHERE particulars='MONITOR' - Working Fine.
$particularslogs = $_POST['particularslogs'];
SELECT remaining FROM sys_stocks WHERE particulars='$particularslogs' - Not Working
What should be the problem?
Thank you in advance.
Here's what I tried so far.
PHP Code.
<?php
include_once('../connection/pdo_db_connection.php');
$particularslogs = $_POST['particularslogs'];
$database = new Connection();
$db = $database->open();
$query = $db->prepare("SELECT remaining FROM sys_stocks WHERE
particulars='$particularslogs'");
$query->execute();
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $query->fetch()) {
echo $row['remaining'];
}
//close connection
$database->close();
?>
AJAX Code.
<script type="text/javascript">
$('#stocksdatelogs').on('blur', function(){
$.ajax({
type : "get",
url : 'function/remaining_stocks_fetch.php',
success : function(remaining)
{
$('#remaininglogs').val(remaining);
}
});
});
</script>
I expect the output will display the MONITOR remaining count into my database table which is 5 to a remaining textbox field using WHERE particulars='$particularslogs' and not WHERE particulars='MONITOR'.
You are not sending the data.
1 - send the data from ajax method to php file something like this.
url : 'function/remaining_stocks_fetch.php',
data: {particularslogs: your data field name},
2- You are using GET method so you need to change the method POST to GET, something like this.
$particularslogs = $_GET['particularslogs'];
OR
Change the type var in the ajax method, like this.
type : "POST",
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'];
I have checked through numerous questions to find the solution. I know I'm close, but I'm still not getting anything happening with my deleteData.php after confirming to delete.
Status:
Testing the array provides successful result.
Example: I checked rows 1, 2 & 31...then press #btn_del.
First, I get the confirm "Are you sure...?"
Next, I see the correct alert(array) 1,2,31
The next step...ajax is supposed to be sending this array data to deleteData.php for processing.
script
$('a#btn_del').click(function(e) {
e.preventDefault();
page = $(this).attr("href");
ids = new Array()
a = 0;
$(".chk:checked").each(function(){
ids[a] = $(this).val();
a++;
})
// alert(ids);
if (confirm("Are you sure you want to delete these courses?")) {
$.ajax({
url : 'deleteData.php',
data : ids,
type : "POST",
//dataType : 'json',
success : function(res) {
if ( res == 1 ) {
$(".chk:checked").each(function() {
$(this).parent().parent().remove();
}) // end if then remove table row
} // end success response function
} // end ajax
}) // end confirmed
}
return false;
}); // end button click function
}); // end doc ready
deleteData.php
<?php
require_once('config.php'); // Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.'.$dbc);
foreach ($_POST['ids']
as $id) {
$sql = "DELETE FROM unit_genData
WHERE unit_id='" . $id . "'";
$result = mysqli_query($sql)
or die(mysqli_error($dbc));
} // end echo result count
mysqli_close($dbc); // close MySQL
echo json_encode(1);
?>
Edited:
Updated GET to POST.
Updated data: 'ids' to data: ids
Tested:
a) In php...echo $_POST['ids'];
NO RESULT
b) In js...commented out the if(confirm...
NO RESULT
Status:
Looks like the AJAX isn't firing (so to speak)
First of all, I would use POST instead of GET for a delete.
Then you need to send the correct data to your php script. What you have now is just a string, no key-value pairs which is what you expect at the backend.
The easiest way to send your data would be to use something like (assuming you have a form):
data: $('form').serialize(),
but you can also send an array like the one you are building:
data: ids,
The advantage of the first method is that values automatically get escaped / encoded (wouldn't make a difference with just integers obviously...).
At the backend you would need to prevent the sql injection problem you have now. You can do that using a prepared statement with bound parameters or in the case of numeric ID's you can cast them to integers.
Edit: As noted in the comments by #Fred-ii-, additional spaces in a string will cause your condition to fail. I would recommend a prepared statement but if you decide to cast to int and use that, just remove the quotes.
Also note that the procedural mysqli_* functions take the database link as the first parameter, that applies both to the query and to the error handling.
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);
});
There seems to be a problem with the code I have for calling php from javascript with jquery ajax. The ajax call seems to be successful but I don't get the correct information returned from the php function.
In the php function I create a SQL query. I send back the query as a reponse to debug it before performing a delete query. Here is the HTML for the div to show the query.
<div id="thenode" style="position: absolute; top: 30px; left: 0px; width: 150px; background-color: white; z-index: 9999;"> </div>
Here is the jquery ajax call. There are two variables being sent to the PHP function: nodeid for node to be delete, and option delete for the function.
function deleteitem()
{
//get selected node
var selectnod = getCookie('pnodid');
//define php info and make ajax call
$.ajax({
url: "uptree.php",
type: "POST",
data: { node: selectnod, option: "delete" },
cache: false,
success: function (response) {
$('#thenode').html(response);
}
});
}
Here is the PHP function.
<?php
function uptree() {
$node = $_POST['node'];
$option = $_POST['option'];
if($node == '' || $option == '') {
return '';
}
$dbco = mysql_connect('localhost', 'root', 'mmowebdb');
if (!$dbco)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("pagelinks", $dbco);
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
return $sql;
}
?>
Should be straightforward but this ajax call returns an empty string and causes the div in the HTML to disappear. This is the first time I use ajax in an actual project. The problem must be easy to find for someone who knows what ajax really does. Can you tell the problems?
I found the answer! Thanks to all of you who had suggestions about the SQL call. But here is the actual answer to my question.
There are four steps in making an ajax Javascript to PHP call. The first two steps happen in the Javascript. The other two steps happen in the PHP.
Step 1. In Javascript decide what variables are needed in the PHP function, retrieve them.
Step 2. Make the ajax call to the PHP function. jquery has a convenient way of passing values to PHP. You have a an array of name-value pairs like this in the data item for the ajax call.
data: { node: selectnod, option: "delete" },
Step 3. Have your PHP function ready in a PHP file. Write the function like this.
function updatetree($node, $option) {
Step 4. Echo a call to the php function within that PHP file.
With these four steps you should have a succesful call to PHP and be able to return information to javascript from the PHP function.
Here is the javascript function.
function deleteitem()
{
//Get selected node to send to PHP function
var selectnod = getCookie('pnodid');
//Define php info, specify name of PHP file NOT PHP function
//Note that by loading the PHP file you will probably execute any code in that file
//that does not require a function call
//Send PHP variables in the data item, and make ajax call
//On success perform any action that you want, such as load a div here called thenode
$.ajax({
url: "uptree.php",
type: "POST",
data: { node: selectnod, option: "delete" },
cache: false,
success: function (response) {
$('#thenode').html(response);
}
});
}
Here is the PHP file uptree.PHP. It has a function defined, called updatetree. It also has an echo statement to call that function. This just seems to be the way to cause the function to run. Ajax itself doesn't call the function.
<?php
//Function defined here
//The variables will come from the ajax data statement
function updatetree($node, $option) {
if($node == '' || $option == '') {
return 'Select an item in the tree.';
}
$dbco = mysql_connect('localhost', 'root', 'mmowebdb');
if (!$dbco)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("pagelinks", $dbco);
$sql = '';
switch($option) {
case 'delete':
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
break;
case 'add':
list($pagename, $address) = explode(",", $page);
$pagename = trim($pagename);
$address = trim($address);
$sql = "INSERT INTO dtree_table (nid, pid, name, url) values (NULL, ".$node.", '".$pagename."', '".$address."')";
break;
case 'update':
break;
}
if (!empty($sql)) return $sql;
}
//echo statement to run function, variables sent by ajax are retrieved with $_REQUEST
//they could have also been retrieved with $_GET or $_POST
echo updatetree(trim($_REQUEST['node']),trim($_REQUEST['option']),trim($_REQUEST['page']));
?>
So to recap. Javascript gets variables, makes ajax call to PHP file. Ajax loads PHP file which contains echo statement that causes PHP function to run. That PHP function is defined in that same file. The function return statement sends information back to javascript through ajax. Javascript does something with that information, e.g. load it into a div on the HTML page.
You actually need to execute the query you create:
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
$result = mysql_query($sql);
return $sql;
Then result will contain a Boolean of success status.
Also when you pass it back to the javascript call you may need to set the appropriate page header of plaintext or json (if you decide to use json)
I highly recommend using a tool like Firebug to watch each ajax request. Then you can see the posted data, response data, and headers to help you diagnose your issue further. Currently only Firefox (AFAIK) fully supports the firebug extension, but firebug lite is also available for other browsers.
You haven't passed $sql into mysql_query();
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
mysql_query($sql);
// -------^^^^^^^^
return $sql;
Your code is vulnerable to SQL injection, as it only checks for an empty $node. As an end user, I could delete any id in the database I wish, or all of them if I ran the code in a loop. You will need something to check that the user running the code has permission to delete the node, and also, call mysql_real_escape_string() on $node.
$node = mysql_real_escape_string($node);
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
$result = mysql_query($sql);
// Check for success...
if ($result) {
// return success codes to ajax caller
}
else {
// return error codes to ajax caller
}
ADDENDUM
We don't see the code where you call upTree() in PHP. Are you actually calling the function? If you don't call it and that's your whole PHP script, then it will execute, do nothing, and return a blank HTTP response to your Ajax calling function with a successful 200 response code.
I send back the query as a reponse to debug it before performing a
delete query.
...
this ajax call returns an empty string and causes the div in the HTML
to disappear.
I assume you want the query displayed inside your div. You need echo($sql); or echo(uptree()); or equivalent somewhere in your program. You might also create an HTML form that POSTs the same data as your AJAX to see what PHP is returning.