How to dynamically generate a link with query - javascript

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.

Related

Pass javaScript variable to php or workaround for just php

I'm trying to get a JavaScript variable to php without refreshing the page or submitting the form. I think my problem is that php is on the server side. I have a button that's set in a php echo...
<input type='button' value='Edit' name='editbtn' onmouseup='reply_click(this.id)' onclick='edit()' id = '" . $row['id'] . "'
This button works correctly. I didn't provide all the code surrounding it, just the part in question. I can inspect the button element in the browser and the "id" shows the correct id number.
Next I'm using some test JavaScript in an effort to get the id to php with having to refresh the page or submit the form.
echo "<script type='text/javascript'>
function reply_click(clicked_id){
var selid = clicked_id;
alert(selid);
document.writeln(selid);
} </script>";
This code works. I get the correct id to show in an alert or document.writeln. The problem comes when I try to set this to a php variable like this...
$testid = "<script type='text/javascript'>document.writeln(selid);</script>";
echo $testid;
$testid returns nothing.
Is there a way to do this or is there a workaround using only php? I need to do this without submitting the form or refreshing the page. Is that possible? The end goal is to create another MySQL statement using that id value. For example: SELECT * FROM table WHERE id = the $testid from JavaScript.
Thank you!

Bootstrap Modal - How to provide data from php (database)

This is probably very simple, but am learning PHP, Javascript as I go. I find it easier to learn using real examples than the contrived examples given online.
I am creating an attendance register page, based on selecting a class, then all members of that class ordered by Surname and Firstname.
The table row has it's id set, by PHP, as the record's mem_id, and contains just forename+" "+surname, and some checkboxes.
All this is working fine, but now I have been asked to add a link so that clicking on it brings up a modal containing related data for the person selected. The extra data is already in the $a_fetch array.
Have added a glyphicon link for every row and clicking it displays a modal alright, and by having a javascript function I know I can get the row index and row id
<tbody>
<?php
while($g_fetch = $a_query->fetch_array()) {
$checked = array();
$memid = $g_fetch['mem_id'];
$name = $g_fetch['firstname'].' '.$g_fetch['lastname'];
$attendences = explode(",",$g_fetch['attend']);
for ($x = 0; $x <= 12; $x++) {
if ($attendences[$x]!="0") {
$checked[$x] = 'checked = "checked"';
}
else $checked[$x] = '';
}
echo "<tr id='".$memid."'>";
echo "<td>".$name."</td>";
echo "<td align='center'><div id='".$memid."' class='glyphicon glyphicon-info-sign' onclick='getId(this.id)' style='cursor:pointer' data-toggle='modal' data-target='#ModalCentre'></div>";
for ($y = 0; $y <= 12; $y++) {
echo '<td align="center"><input type="checkbox" value = "" '.$checked[$y].'></td>';
}
}
unset($checked);
unset($attendences);
?>
</tbody>
</table>
I am at a loss as how to proceed - is it even possible to pass data to the modal to display related data?
If it is would I need to run a new query (SELECT), or as the row is the same index as the data in the $A_fetch, and the row id has the correct mem_id is it possible to get the data from the existing $a_fetch array using either of those, or would I need to run a new SELECT?
Many thanks
There are multiple ways to provide data to the modal - and (in my opinion) it depends on how much data you need to pass to your modal and how many rows you have.
I want to describe you two ways:
Light+Easier Solution
If you don't want to display a lot of data and you have just a few rows.
The idea is to add the data directly to each div.glyphicon (as data attributes) and then use it in the modal
In your foreach add it to your model like that:
<div id='".$memid."' class='glyphicon glyphicon-info-sign' onclick='getId(this.id)' style='cursor:pointer' data-toggle='modal' data-target='#ModalCentre' data-link='".$g_fetch['additional_link'] ."' data-moreInfo='".$g_fetch['moreInfo']."'></div>
You haven't posted the modal's HTML or your JS code, but you wrote you are using bootstrap, so stick to
https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content
and fetch/set the relevant data (related clicked glyphicon) as it's described.
More complex solution
For more data / more rows. The additional data is not provided in the inital loaded HTML page - Therefore not all data needs to be loaded in the beginning.
Instead the additional data is loaded via ajax when clicking on one row.
For that you need to provide an additional endpoint (php) which provides the modal content for one row.
Check out second answer in Bootstrap 3 - How to load content in modal body via AJAX?
Basically you have a php file (e.g. getAdditionalData.php)
In this file you access the mem_id via GET
$mem_id = $_GET['mem_id'];
fetch the additional data from database
and print/render out the modal content (full html like in the second answer)
And in JS (inital page) you load the modal content onClick (fetched from php with provided mem_id as parameter)
var clicked = $(e.relatedTarget);
$(this).find(".modal-body").load("%PATH%/getAdditionalData.php?mem_id="+clicked.attr("id"));
I hope it will help you solving your problem and if you need additional infos just let me know. There are more ways to archive your goal but I think this 2 possibilities are enough in the beginning :-)

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>

Set_value fallback in code igniter to obtain integer from URL address

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

How to create a textbox that display message when mouseover?

I have a sql query that obtain a string called description from the database
Also , i have a table that contain a mail list
I would like for each mail list name, when the mouse over it, it display a text block that contain the description
Are there any plugin , or how to do that? Thank you.
I use a jQuery plug-in called TipTip, which is very simple to implement.
The PHP(for the query). You can use whatever, this is an example.
<?php
$q = 'your sql query'
$query = mysql_query($query)
while($row = mysql_fetch_array($query)){
?>
<div class="email-list-name-<?=$row['id']?>"> <?=$row['email-list-name']?> </div>
<div class='description-for-email' style='display:none;'><?=$row['description']?></div>
<?php } ?>
The jQuery:
$(function(){
$('div[id^="email-list-name"]').click(function(){
$('.description-for-email').hide(); //hide all message displays
$(this).next('.description-for-email').show(); //show the next description for our email we clicked
});
});
You didn't really provide any other information, so I just threw together a general example.
You can use the title attribute of html for that or make use of tooltip . You can easily find an example of tooltip. But if you trying to fetch the data from your db on the run time..i would say thats a bad idea

Categories

Resources