Search and Insert multiple values selected in textbox into MySQL - php

I'm doing something in PHP which displays all the data let's say animals table for easier understanding. Now I have a kingdom table where all of the animals that falls into their respective kingdoms. Now In my Page I displayed two tables: Those animals who falls into the Kingdom I logged in (given Animalia) and Those who dont.
In those animals who are not part of the Kingdom Animalia there is a checkbox besided each names where I can select one or more names. Now I have an add button to serve as the trigger to add those animals I selected to be assigned in Kingdom Animalia.
Now it becomes a zoology class, sorry for the sample but I think I can explain in much better this way.
To add, as much as possible I wanted my code to be limited in using javascript and php codes only since I'm not used in working with jQuery.

From what i understand....
Post a checkbox with each of your table records along with your form
<!--non assigned table-->
<table id="non-table">
<tr id="nonassignedid">
<?php foreach($nonassigneddata as $data){ ?>
<td>....</td>
<?php } ?>
<tr>
</table>
<!--assigned table-->
<table>
<tr id="assignedid">
foreach($yourresults as $result){
<td>...</td>
<?php
$check = someFunctionToCheckAssigned($result,$youruserId);
if($check){
$checked = "checked='checked'";
}else{
$checked = "";
}
?>
<td><input type="checkbox" userid="<?php echo $userid; ?>" assigningproperyid="<?php echo $assignid; ?>" name="both" class="updateuser" <?php echo $checked ?> /></td>
}
</tr>
</table>
Using Jquery Ajax method
$(".updateuser").click(function(){
var userid = $(this).attr('userid);
var propertyid = $(this).attr('assigningproperyid'); //what ever thing you want to assign
$.ajax({
url: 'updateuser.php,
type : "POST",
data : {'userid':userid ,'propid':propertyid },
success: function( data ) { //return the data as assigned element id
$('#non-table #data).remove(); //removing that tr from non -assinged
}
}
});
})

According to my understanding of the question...in the not assigned table i'm presuming that you have a checkbox besides a user name who is not assigned(linked) to our current user..
Now, add a button next to that new user's name to be assigned to our user.
Trigger the onclick event on that button using jquery on just javascript.
function adduser(){
var elems = $(".Checkbox");
for(var i=0;i<elems.length;i++)
{
if(elems[i].checked){
var userId = elems[i].id;
$("#dummy").load("adduser.php?user_id="+userId,function(){
$("#"+userId).parent().remove();
});
}
}
$("#dummy").html("succesfully Added selectd users to your account.");
}
In the file adduser.php write the code for adding a user to the current user.

Related

PHP AJAX HTML: changing unique table data in foreach loop

I'm new to PHP and Ajax. I am trying to create a table of object data where I can select the displayed data based on a <select><option>... form.
I have a PHTML template which looks like the following:
<?php
$content = "";
// creates data selector
$content .= "
<form id = select_data>
<select id = data_selection>
<option value = data1>Data 1</option>
<option value = data2>Data 2</option>
<option value = data3>Data 3</option>
<option value = data4>Data 4</option>
</select>
<input id = selected_data type=submit />
</form>";
// creates table header
$content .= "
<tr>
<th>Data</th>
</tr>";
$array_ids = array(1, 2, 3); // etc, array of object id's
foreach ($array_ids as $array_id) {
$object = // instantiate object by array_id, pseudocode
$object_data = $object->getData('default-data'); // get default data to display
// create table item for each object
$content .= "
<tr>
<td><p>$object_data</p></td>
</tr>";
}
print $content;
?>
This prints out the table content, loads objects by their id, then gets and displays default data within the <p> tag.
And then I have some Javascript which looks like the following:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){ // get selected data type
e.preventDefault();
var data_selected = $("#data_selection :selected").val(); // create var to pass to ajax
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected},
success: function(data){
$("p").html(data); // replace all <p> tag content with data
}
});
});
});
</script>
This Javascript gets the selected data type, creates a variable out of it to pass on to the ajax which then calls post.php, which looks like the following:
<?php
$attribute = false;
if (isset($_POST['data_selected'])){
$data = $_POST['data_selected']; // assigns variable out of ajax data
$object = //instantiate object, again pseudocode
$object_data = $object->getData($data); // get new data to replace into the ```<p>``` tag
echo $object_data;
}
?>
The problem is that the Javascript that I have changes every single <p> tag to the last data iterated by the foreach loop because each <p> tag is not uniquely identified and the Ajax does not update the data based on a unique identifier, such as maybe the $array_id. Which brings me to my attempted solution.
I tried to identify each <p> tag with the following:
<td><p id = $array_id>$object_data</p></td>
And then creating a new Javascript variable out of the array ID:
var p_tag_id = <?php echo $array_id; ?>;
And finally making the Ajax success function target element ID's based on var p_tag_id:
$("#" + p_tag_id).html(data);
While this does not change all the <p> tags like previously, it only changes the final <p> tag and leaves all instances before it unchanged because the Javascript is not iterating over each <p> tag, or because the foreach loop does not call the Javascript as a function for each $array_id.
How can I rewrite this code so that the Ajax updates the data of each table item uniquely instead of updating them all with the same data? Is there a better way to approach this problem?
You need a way to identify the table row containing the <p> tag you wish to update, and perhaps the value attribute of the SELECT element could help.
You can get the number of the clicked option from your data_selected variable by using slice to strip-off the last character (i.e. the number):
var num = data_selected.slice(-1) - 1;
(Subtract 1 because the table rows are zero-indexed)
Then, in the AJAX code block's success function:
$('table tr').each(function(i,v){
if (i == num){
$(v).find('td').find('p').html(data);
}
});
The above grabs all the table rows (as a collection) and loops through them one-by-one. In the function, i is the index number of the row and v is the row itself. Index numbers begin at zero, which is why you earlier subtracted 1 from the (for eg) data3 [3] value, leaving num == 2. When you find the right row number, use .find() to find the <td> in that row, and then the <p> in that <td> and Bob's yer uncle.
I haven't tested the above code so there could be bugs in the example, but off-the-cuff this approach should work.
I figured out a solution. I assigned the $array_id to each <p> tag after all in order to identify them uniquely:
<td><p id = $array_id>$object_data</p></td>
Then I looped over all the <p> tags and assigned the $array_id of this <p> tag to a variable like so:
$("p").each(function() {
var array_id = $(this).attr("id");
And finally I made the Ajax success target elements based on their ID:
$("#" + array_id ).html(data);
Here is the full Javascript code for anybody who is interested. Hopefully this helps someone else out!
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){
e.preventDefault();
var data_selected = $("#data_selection :selected").val();
$("p").each(function() {
var array_id = $(this).attr("id");
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected, array_id: array_id},
success: function(data){
$("#" + array_id).html(data);
}
});
});
});
});
</script>

Hello i'm trying to do multiple sorting using php mysql where i'm searching and then sorting the data

i'm printing a table in php where data is coming from mysql now i'm creating functionalities like searching and sorting so when i click on sort it sorts the data and when i click on search i get searched data now the problem is i want to perform sorting on searched data like for example i sorted the data and then i searched for words starting with a i.e i got results like adam,azan,anand so i want to perform resorting on these searched data and get data as adam,anand,azan
my approach is:
<?php
if(isset($_GET['search_btn'])){
$search=$_GET['search'];
$result=GetWords(mysqli_escape_string($conn,$search));
}
/*if(isset($_GET['q'])){
$id=$_GET['q'];
$result=GetWordsById($id);
}*/
if(isset($_GET['sort'])){
$sort=$_GET['sort'];
}
if(isset($_GET['sort'])){
if($sort=="asc"){
$result=SortContent();//Here Get Sort Content is a function calling Store Procedure SortContent which is working at first sorting
}
if($sort=="desc"){
$result=SortContent2();
}
}
else{
$result=GetAdminWords();
}
if(mysqli_num_rows($result)>0)
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tbody>
<tr>
<td><?php echo $row['word'];?></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td><i class="fa fa-edit"></i> <a onClick="javascript: return confirm('Please confirm deletion');" href="view.php?id=<?php echo $row['id'];?>"><i class="fa fa-trash"></i></a> </td>
</tr>
</tbody>
<?php
}?>
and i'm talking in context of large amount of data i hope i have made myself clear and if possible how can i implement ajax using mysqli
You will need to trigger an event in JavaScript, which in turn will use your HTML search input, which is then sent to the server, where a query will be executed and the results returned (as HTML) to the JavaScript code, and finally placed back on the page. At least this is how I solve my ajax searches...
So the flow could be something like:
Input -> JavaScript event -> ajax -> result -> page
Here is some code that might get you started, though I haven't tested i myself:
HTML:
<input type="text" id="my_search_input">
<div id="my_search_result"></div>
JS (jQuery):
var $inputField = $( "#my_search_input" );
var $result = $( "#my_search_result" );
$inputField.on('keyup', function(){ //triggered when a pressed key is lifted
var searchTerm = $inputField.val();
$.ajax({
url:"/mySearch.php",
method:"post",
data:{searchTerm:searchTerm},
success:function(response){ //response contains the data from mySearch.php
var parsedResponse = JSON.parse(response);
var resultHtml = parsedResponse.html; //this is the array key of what the PHP script returns
$result.append(resultHtml);
}
});
});
PHP
$searchTerm = $_POST['searchTerm']; //$_POST['searchTerm'] is what we defined in data:{... in the ajax call
// here is where you need to retrieve data from your database
// the db result needs to be processed into HTML and assigned to a variable
$html = "<div>My result based on data</div>";
return json_encode(['html' => $html]);

I need a script to change a link when clicked on it to another content

i am working on student supervision project. i wanted to create a page that contain the available project topics, when clicked on a topic of interest, to assigns the topic to the user with that 'id' and renders the link unavailable e.g a topic that has a link 'available' to change to 'unavailable'.
i will really apreciate if someone in the house can help?
Thanks
You need to use ajax for it, that way and helping with jquery you make the changes in real time
I made some small changes to perform this action with jquery
<body>
<table cellspacing="2" cellpadding="2" border="2">
<?php $sql = "Select * from prject_topic"; $result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['lecturer_name'];?></td>
<td><?php echo $row['topic'];?></td>
<td><span class="actu" id="<?php echo $row['project_id'];?>">
<?php echo $row['status'];?>
</span>
</td>
</tr> <?php } ?>
</table>
<script type="text/javascript">
$(function(){
//We capture the Click in the user item
$(".actu").on('click', function(){
//We take the ide of this item
var id = $(this).attr('id');
//We check the current status of the user
if($(this).html() == "Deactivate"){
var est = "Activate";
}else{
var est = "Deactivate";
}
//We made a request of type ajax sending by post the id for its update
$.post('#.php',
{
'id':id,
'est':est
},
//We received the response from our php file which may be a code as in the example...
function(data){
if(data=="200"){
//If yes, update the content of the selected item in real time
$("#"+id).html('Deactivate');
}else{
//In case of error, we send the information
alert("Unable to disable user");
}
})
})
})
</script>
</body>
The code is written for your understanding

execute a php file on selection of dropdown value

i have been searching a solution for days and i have tried ajax/jquery methods posted online but it just wouldnt work. I have a drop down list which gets its value from the database. On selecting any value apart from "Select", i want to display a value which is called upon by a php file:
here's my code for the form:
<tr>
<fieldset id="Date">
<td class="select"><label><span class="text_9">Date:</span></label></td>
<td><select name="date" id="date">
<option value="">Select</option>
<?php include_once "selectdate.php"?></td>
</select>
</tr>
</fieldset>
</table>
and here's the php to run on selection of the drop down (called retrieve.php)
<?php
include_once "connect.php";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$form=$_GET;
$trade=$form['tradetype'];
$metal=$form['metal'];
$amount=$form['amount'];
$date=$form['date'];
$stmt = $conn->query("SELECT Discount FROM Contracts WHERE Trade='$trade' AND Metal='$metal' AND Amount='$amount' AND ExpiryDate='$date'");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo ($row['Discount']);
}
?>
As you can see, the php to be run uses the value from multiple form elements...
I am very new to jquery/ajax... any help is appreciated as i want the result to be displayed on the same page as the form is. Thank you!
If you want to get data from another file to a select, you should add as option. Plain text inside select will not help you out. So wrap the vales with <option></option>
So change this line,
echo "<option>{$row['Discount']}</option>";
If you want to give values,
echo "<option value='{$row['Discount']}'>{$row['Discount']}</option>";
EDIT
Now onchange of deopdown, date call ajax to do next stuff.
$(document).on("change","#date",function() {
var tradetype = //capture the value here;
var metal = //capture the value here;
var amount = //capture the value here;
$.ajax({
url:"path/filename.php",
data:{date:$(this).val(),"tradetype":tradetype,"metal":metal,"amount":amount},
type: "POST",
success: function(data){
alert(data);//this will alert what you have echoed on php file
}
});
});

Load an html table from a mysql database when an onChange event is triggered from a select tag

So, here's the deal. I have an html table that I want to populate. Specificaly the first row is the one that is filled with elements from a mysql database. To be exact, the table is a questionnaire about mobile phones. The first row is the header where the cellphone names are loaded from the database. There is also a select tag that has company names as options in it. I need to trigger an onChange event on the select tag to reload the page and refill the first row with the new names of mobiles from the company that is currently selected in the dropdown list. This is what my select almost looks like:
<select name="select" class="companies" onChange="reloadPageWithNewElements()">
<?php
$sql = "SELECT cname FROM companies;";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)) {
echo "<option value=\"".$row['cname']."\">".$row['cname']."</option>\n ";
}
?>
</select>
So... is there a way to refresh this page with onChange and pass the selected value to the same page again and assign it in a new php variable so i can do the query i need to fill my table?
<?php
//$mobileCompanies = $_GET["selectedValue"];
$sql = "SELECT mname FROM ".$mobileCompanies.";";
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
echo "<td><div class=\"q1\">".$row['mname']."</div></td>";
}
?>
something like this. (The reloadPageWithNewElements() and selectedValue are just an idea for now)
Save the value in a hidden input :
<input type='hidden' value='<?php echo $row['cname'] ?>' id='someId' />
in your JavaScript function use the value from this hidden input field:
function reloadPageWithNewElements() {
var selectedValue = document.getElementById('someId').value;
// refresh page and send value as param
window.location.href = window.location + '?someVal='+ selectedValue;
}
Now again in your PHP file retrieve this value from url for use as:
$someVal = null;
if (isset($_GET['someVal']) {
$someVal = $_GET['someVal'];
}
see if this works!!!
The best option would be using AJAX.
reloadPageWithNewElements() is a function which calls a page of your own site which will return the data you would like to put in your table.
If you are using JQuery, AJAX is very easy to implement:
$.ajax({
url: '/yourPage',
data: { selectedCompany: $('.companies').val() },
success: function(result) {
//delete your tablerows
$(".classOfTable tr").remove();
//put the result in your html table e.g.
$('.classOfTable').append(result);
},
dataType: html
});
The browser will send a request to "/yourPage?selectedCompany=Google" or something
All you have to do is let this page print out only html (maybe even easier is to print only the tablerow (<tr>).
If you have any further questions, please ask.
I would use jQuery to do it.
first You need to add 'id' attribute to every option tag
<option id="option1">
<option id="option2">
and so on...
then with jQuery:
$('<option>').change(function() {
var id=$(this).attr('id');
...save data here (i.e: with ajax $.post(url, { selected_id: id}, callback }
});

Categories