Set_value fallback in code igniter to obtain integer from URL address - javascript

I'm using the codeigniter framework in order to update records from a database, where the user first selects the ID of the item from a drop down list on the form
This ID gets added onto the URL where all of the relevant information for that item is obtained from the database.
I used a small bit of javascript in order to achieve the ID being added onto the URL.
My problem is that even though I have the set_value() field on the form to the ItemID, it still doesn't retrain the ID within the drop down box after the page reloads?
I need the ID to stay inside of the drop down list, as well as being on the URL at the top of the page
here is my code for the form
<?php echo form_dropdown('ItemID', $ItemIDListFromDatabase,
set_value('ItemID', 1), 'id="ItemID"'); ?>
<script type="text/javascript">
$( '#ItemID' ).on( 'change', function( e ){
document.location.href = "<?php echo site_url('site/Myform) ?>" + "/" + $( this ).val();
});
</script>
As you can see above I've tried adding a random fallback number to this set_value call, which works but only to update the item with ID of 1, I need it to be able to update the Item corresponding to the ID on the URL
I hope this makes sense, all help appreciated thanks.

You can do this by very simply using
$this->uri->segment()
Without knowing your full URL address, I don't know the exact number to put into the segment, but going by your code supplied just change the following to this:
<?php echo form_dropdown('ItemID', $ItemIDListFromDatabase,
set_value('ItemID', $this->uri->segment(3)), 'id="ItemID"'); ?>
This will obtain the value within segment 3 of your URL.
A quick tip if you can't figure out what the correct URI segment should be, you can test it out by echoing different values until you find the correct one
E.g.
<?php echo $this->uri->segment(3); ?>
This will display what ever is displayed on your third segment of the URL

Related

How to dynamically generate a link with query

Hi fellow developers,
I want to integrate affiliate program for my website, to earn commissions from bookings made via my links.
Since, I have those properties on my site as well, I need a user to be able to click "book it" and get redirected to a page on booking.com with that particular place highlighted.
So the link has this params, which I need:
http://www.booking.com/searchresults.html?city=-2900142&aid=814610&checkin_monthday=25&checkin_month=3&checkin_year=2017&checkout_monthday=30&checkout_month=3&checkout_year=2017&no_rooms=1&group_adults=1&highlighted_hotels=2197459
City = I have custom field for it,so wordpress can pick it with
get_post_meta(CityID)
Highlighted_hotels = makes this particular object highlighted if it's available, also I have it in custom field, so I can take it with
get_post_meta(HotelID)
But how do I take date values from dropdowns? And how do I make a link afterwards? with
<?php echo '<a href="http://www.booking.com/searchresults.html?';
echo $city;
echo $highlighted;
echo $dates;
Is this a correct method to create a link on wordpress?
Btw, I'm using an official booking.com plugin right now, but it's broken and doesn't fill my needs, I want to change it with above custom code, but you can take a look at what I want to achieve on my site here for example (russian language) :
http://sochi.asp.sale/nedvizhimost/chvizhepse/posutochno/kompleks-zolotoj-kashtan/
Form is on the right side bottom.
Any help much appreciated!
Use Javascript to take the values from the dropdown like so:
var e = document.getElementById("DROPDOWN_NAME");
var strUser = e.options[e.selectedIndex].text;
Now to build a URL just use the variable created called strUser.
var url = "http://www.booking.com/searchresults.html?" + strUser;
I hope that is clear and helps.
EDIT:
If you want to use php to build the link, append the values to the url variable:
<?php echo '<a href="http://www.booking.com/searchresults.html?' . $city . '&' . $highlighted . '&' . $dates;
That will echo the completed url with all the variables added onto the end of it.

How to update a table without changing the onscreen data displayed

I need to display a simple list of hundreds of items which are on a MySQL table, review the list onscreen and click on a link beside each unwanted item to delete it from the table. This is an internal management procedure; no outside user is involved. I do not need the item to disappear from the list immediately; I will refresh the list periodically so items deleted from the table are no longer listed. I do not need any message to confirm that the item has been deleted. The important thing is that I don't want to lose sight of the list each time I delete an item and have to click on a "go back" button to return to the list.
The table uses MySQL. All my coding to date has been in PHP. So I am using php to display the list of items, on a non-html screen. This is the code for each item:
echo $item." <a href='item_delete.php?id=".$item."'>Delete item</a><br />";
This is the code for item_delete.php:
<?php
require ('connect.php'); // To define connection $con
$id = $_POST['id'];
mysqli_query($con, "DELETE FROM `items_table` WHERE `id` = $id");
?>
The item is deleted correctly but a blank screen is (understandably) displayed.
I have done a lot of searching but most people needing help want to do more advanced things and - because I have so far managed to avoid learning JavaScript, jQuery and AJAX - I can't even work out which of those technologies I need to update a table without changing the screen.
I get the impression that each PHP script always takes "focus" with it, so maybe I need a little JavaScript script to do this ?
If so:
- can I just change item_delete.php to item_delete.js or do I have to define the non-html list as an html one ?
- what js code is needed in item_delete.js ?
I have read about using: header("location:javascript://history.go(-1)");
or: header('Location: ' . $_SERVER['HTTP_REFERER']);
but they don't go back to the onscreen list.
I don't think I want the js script to perform a virtual "go back" because the list is originally produced by using (about 20) $_POST parameters, so I still seem to have to refresh it each time.
So I'd like a solution to remain with the list - rather than leave it and return to it. Thanks.
It would make a lot of sense to do the deletion asynchronously using javascript. However, the simplest and messiest way to achieve what you want, is to add target="_blank" to the links, (which will leave you with a open blank tab for each delete request you do).
echo $item." <a href='item_delete.php?id=".$item."' target='_blank'>Delete item</a><br />";
Or you can solve it by adding checkboxes in front of every item, check the items you want to delete and submit them as form parameters to the delete script.
If you want to delete to row in the onscreen table after the actual PHP code has run you can use the following implementation:
The HTML structure for the link requires a unique class name, such as:
echo 'Delete item'
Note the item id is stored inside a HTML5 data attribute. I have also added an onclick event handler which returns false to avoid the link refreshing the page.
The javascript used to delete the item use the JQuery AJAX method and binds to the specified class, which is: item-delete. The implementation requires Jquery version >= 1.9.0
(function(){
$('.item-delete').click(function(event) {
var target = $(event.target);
var id = target.data('item-id');
$.ajax({
url: 'item_delete.php',
method: 'POST',
data: {
id: id
},
}).done(function() {
target.remove();
}).error(function(err) {
console.error('Could not delete item with ID: ' + id);
console.error(err);
});
});
}())
The event listener is defined inside a self-executing function, which is automatically executed when the page-load completes and avoids poluting the global namespace.
You can delete the item directly on the same page without moving to another
page by passing the id through a hyperlink and then get it to finally delete
the unwanted item. CHECK THIS OUT, and please let me whether or not is what you
wanted :-)
// connection
mysql_connect("host", "user", "password");
mysql_select_db("your database name");
// select all the items from table.
$selectQuery = mysql_query("SELECT * FROM table_name" );
// use while loop to list all the items...
while( $row = mysql_fetch_array($selectQuery) )
{
// list the items as a hyperlink, passing their id through the URL.
?>
<?php echo "delete " . $row["item_name"]; ?>
<?php
}
// Below is the code to delete the item.
if( isset( $_GET["id"] ) )
{
$itemId = $_GET["id"];
// query to delete item
$deleteQuery = mysql_query("DELETE FROM table_name WHERE id = '$itemId' ");
//-----------THE MOST IMPORTANT PART. >>>
// redirect if delete is successfull.
if( $deleteQuery )
{
// reload the page to get the items minus the deleted one...
// let's say your sript name is delete.php
header("Location:delete.php");
}
}
?>
</code>

Setting the color of an HTML element using an index and Jquery

I am designing a web application for handling various requests to a management team. I have these requests display in tables grouped by the type of request. Initially every request is given a red button since by default requests have not been completed. I am trying to figure out how I can change the color of a specific request's button once it has been marked as completed. Below is my Jquery code:
<script>
<?php
if(isset($_SESSION['index']) and $_SESSION['complete'] == 'internal'){
echo "var index = '{$_SESSION['index']}';";
unset($_SESSION['index']);
unset($_SESSION['complete']);
echo "$( '.complete:eq(index)' ).css('background','green')";
}
elseif(isset($_SESSION['index']) and $_SESSION['complete'] == 'client'){
echo "var index = '{$_SESSION['index']}';";
unset($_SESSION['index']);
unset($_SESSION['complete']);
echo "$( '.client_comp:eq(index)' ).css('background','green')";
}
?>
</script>
By pressing a button you are sent to a page that displays all of the relevant request information. This is done by using another bit of jquery code to store the index of that class of button in a PHP session variable and then using that index to determine which request to load from the database. This page has a complete button that returns to the page with the tables and passes the index and the type of request that was completed back to that page. What my above code is attempting to do is set the color of that specific button using it's type and index. At this point in time everything works as expected except for the color change. I have searched and not been able to find a problem like this. Any help would be greatly appreciated.
I don't understand why you need js variable.
Can you try this.
<script>
<?php
if(isset($_SESSION['index']) && $_SESSION['complete'] == 'internal'){
echo "$( '.complete:eq(".$_SESSION['index'].")' ).css('background','green')";
}
elseif(isset($_SESSION['index']) && $_SESSION['complete'] == 'client'){
echo "$( '.client_comp:eq(".$_SESSION['index'].")' ).css('background','green')";
}
unset($_SESSION['index'],$_SESSION['complete']);
?>
</script>

how to get current selected from <select> and on every change in selected

i was trying to make a dynamic where the selected option was supposed to be caught in a variable for php as i would use it as a condition to be put in a where clause for mysql. and when a user selects another option the of another tag would change
<form method="GET" action="">
<select name="docSpec" id="docSpec">
<?php
$docSpecQuery = "select DISTINCT specialty from doctors"; // i was going to put a where condition here so i could only project names of the doctor with the selected specialty.
$docquery = "select doctorName from doctors";
$docSpec = mysqli_query($conn,$docSpecQuery);
$docresult = mysqli_query($conn,$docquery);
//this php block is for my options, i used a loop
while ($row = mysqli_fetch_row($docSpec))
{
echo "<option value='$row[0]'>$row[0]</option>";
}
unset($row);
?>
</select>
<script type="text/javascript">
$('#docSpec').on("change",function(){
var option = $("option:selected",this).val();
alert(option);
});
</script>
</form>
i hope i was clear enough i will be waiting if you want to clarify some things in my code.
tell me if you need another parts of my code. please i need help
PHP is executed on the server, which means that by the time you print the <select> you run the jQuery code you can't affect the mysql query directly. You can however move the query to another script, and target it with an ajax call that returns the select and options or, ideally, the dataset so you can create it programmatically.
Your php script will do the same as it does right now but fetch the value from the url for the conditional query. For instance, you could have this php at mysite.com/select.php and pass the variable gynecologist like so mysite.com/select.php?spec=gynecologist then read it with $_GET['spec'] and use it in the query.
In your javascript, you'll get that html by calling something like:
$('#docSpec').on("change",function(){
$.get( "mysite.com/select.php?spec="+$(this).find("option:selected"),
function( data ) {
//data contains the output for the php file, update the dom
//with it or whatever
});
});

PHP multiple records insert

I am attempting to reword my issue.
I have a datatable that can return thousands of records, each with multiple columns. There is a checkbox in the first column that, once the user checks it, they then click a button, and the CONTAINER_NUMBER that is associated with the row is sent to a modal window to be used in a form.
Here is the code for the checkbox:
echo "<tr><td><input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\" name=\"checkMr[]\" /></td>";
This is the javascript that retrieves the CONTAINER_NUMBER and sends it to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
});
$(".modal-body .containerNumber").val( selectedID );
});
});
</script>
This is the section of the modal window that displays the CONTAINER_NUMBER:
<div class="modal-body">
<form action="" method="POST" id="serviceModalForm" name="serviceModalForm">
<input type="text" name="containerNumber" id="containerNumber" class="containerNumber">
Here is the section of PHP that takes the id="containerNumber" and converts it to a PHP variable. After that, there is an INSERT statement that inserts the containerNumber into a database table:
<?php
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$container = mysql_real_escapse_string(stripslashes($container));
$sql = "INSERT INTO myTable (container_num) VALUES ('$container')";
if(mysql_query($sql)){
echo "Insert complete";
}
else {
echo "Insert was not completed";
}
?>
This code is fine. It works good. It does what it's supposed to do...for when the user checks ONE checkbox. It DOES NOT work when the user checks multiple checkboxes.
Basically, from what I've been researching is that I need to separate the records from the variable $container, as there can be multiple containers in that variable, which is why the query does not work when there are more than one container numbers selected.
I need to be able to separate the container numbers and store them in an array or something. The query will read each record separately and generate multiple INSERT statements for each record.
I've tried several times to create an array and get the sql statement to recognize it, but have been unsuccessful. I'm not sure if I'm placing the array in the right place. I'm not sure if this has to be done in the javascript before the container gets sent to the modal window.
I know I need to utilize a FOREACH loop to go through the array, but like I said, I'm not sure where the array needs to go in my code.
Please help. I know I need to learn PDO or MYSQLI. I will be sure to utilize PDO or MYSQLI on my next application. Until then, please help me with this issue.
Thank you, and sorry for so much wording.
Your containerNumber will be posted as a converted string from a js array. Something like id1, id2, id3[...]
In your php code, convert the $container back to an array ($containerArray = explode(",", $container)) and construct the sql dynamically to add all the rows in a single query so that the statment becomes something like
INSERT INTO myTable (container_num) VALUES ('$containerArray[0]'), ('$containerArray[1]')[...]

Categories

Resources