I have two pages with 3 tabs each. One page for viewing and another for editing.
When I click the tab 2 from view page and press Edit button, I want to be redirected to tab 2 in Edit page. Similarly, for other tabs as well. Tab 1 from view takes me to tab 1 in Edit, and tab 3 from view takes me to tab 3 in Edit.
So what I want to do is, get the active tab from the 3 tabs, fetch the href value, store the href value such that I can use it as php variable (or any other way) in the same page and pass it on to the button link to redirect correctly.
I am using Bootstrap and Codeigniter.
To fetch the href from the active tab; I found this:
$('.nav-tabs .active > a').attr('href')
This will give me the concerned href name like tab1, tab2, tab3:
<li class="active">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
I have a line in my PHP code like:
Edit
How do I achieve this?
You'll have to change your link a little bit, like this:
<a id="EditLink" href="<?= site_url('backend/edit/'. $uid) ?>">Edit</a>
And add this when you click on the tab, where :
var tabValue = $(".nav-tabs .active > a").attr("href");
var url = $("#EditLink").attr("href");
$("#EditLink").attr("href", AppendToUrl(url, "tab", tabValue));
With the function AppendToUrl:
function AppendToUrl(url, key, value) {
var regex = /\?/i;
if (regex.test(url)) {
return url + "&" + key + "=" + value;
} else {
return url + "?" + key + "=" + value;
}
}
You cannot. Active tab is client side, PHP is server side. You can eventually use javascript to send AJAX query:
$.ajax({
method: "POST",
url: "some.php",
data: { active_tab_id: jquery_function_returning_id() }
})
.done(function( url ) {
$("#id_of_element_u_want_inject_href").attr("href", url)
});
Some.php:
<?php
$data = $_POST['data'];
echo site_url('backend/edit/'. $uid . $data['active_tab_id']);
session_start();
$_SESSION['variable']=$data['active_tab_id'];
?>
You should be able to access data in session.
Best would be full javascript solution :)
Handle this in JS by passing the uid down instead of the selected tab up.
Something like this.
var uid = <?PHP echo $uid; ?>;
function getHref() {
var selTab = $('.nav-tabs .active > a').attr('href');
var retHref = 'backend/edit/' + uid + selTab;
return retHref
}
May need a PHP script to shiv this into site_url() whatever that does, but thats easy enough.
You should achieve this wit javasvript...
When click on a tab get its id and then set required href for any element ...
Related
I've built a CMS that uses bootstrap Modals within div areas so that when the user clicks on the div where they want to insert content, a modal comes up with a tinyMCE text editor area where they can put images or text. Once they have, they hit the save button in the modal which closes the modal and shows the preview of what they just did.
Also, when they hit the save button, I perform an AJAX request that calls an addPanel.php script in order to insert a record for that panel, panel type and content.
THis works perfectly except for the fact that if they click on the modal again and do this all over to edit their content, it just saves another panel.
I need to slightly modify what I"m doing now to either:
Get the ID of the panel that was created on the last ajax request and now perform a mysql update on the record for the content (as the panel ID and panel type will remain the same)
Keep the current process but set the last panel's 'active' column in mysql to '0' (not as big a fan of this approach but will accept it).
Basically, what I have works but if the user clicks on the modal anymore after the first time, I would be updating instead of inserting.
Here is the mysql being performed in addPanel.php:
$content = $_POST['page_content'];
$addContent = "
INSERT INTO content(content)
VALUES('$content');
";
if ($mysqlConn->query($addContent) === TRUE) {
$cont_id = $mysqlConn->insert_id;
$data['last_insert_id'] = $cont_id;
echo json_encode($data);
} else {
echo "Error: " . $addContent . "<br>" . $mysqlConn->error;
}
$panelID = $_POST['panel_type'];
$pageID = $_POST['page_id'];
$addPanel = "
INSERT INTO panels(panel_type_id, page_id, cont_id)
VALUES ('$panelID', '$pageID', '$cont_id');
";
if ($mysqlConn->query($addPanel) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $addPanel . "<br>" . $mysqlConn->error;
}
And the script/AJAX to show an example of what I'm doing currently for a panel:
<script type="text/javascript">
$("#leftHalfForm").submit(function(e){
var leftContentVar = tinymce.get("leftHalfTextArea").getContent();
$(".leftContent").html(leftContentVar);
$("#leftHalfPageContent").val(leftContentVar);
// jQuery.noConflict();
var string = $('#leftHalfForm').serialize() + '&page_id=' + page_id;
console.log(string);
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "addPanel.php",
data: string,
cache: false,
success: function(response){
console.log(JSON.stringify(response));
console.log(string);
$('#leftFiftyModal').modal('hide');
$('.modal-backdrop').remove();
}
});
return false;
});
I have a page single-colur.html and it can take a variety of set query strings as can be seen below:
single-colur.html?id=1
single-colur.html?id=2
single-colur.html?id=3
single-colur.html?id=4
The id above is referenced to a colour table which has the following columns:
id
name
content
When people come to single-colur.html and they request a specific ID, I'd like to get the respective ID from the URL and send an AJAX request to a PHP page which will get the corresponding row from my table based on the ID that is provided, this is currently implemented.
My question is: Is it possible that if someone goes to single-colur.html?id=1 then all the data is fetched and displayed in a new URL based on the name field which is referenced by the ID e.g. single-colur.html?id=1 points you to a dynamically created file called red.html and it shows the data from the colour table for this ID?
My restriction is that I must create the new file dynamically and it cannot be done statically.
EDIT
Currently i have two pages .
1)archive-colour.html
2)single-colour.html
in archive-colour.html
<div>
Red
Green
Blue
</div>
in single-colur.html?id=anynumber
<div class="result">
</div>
In single-colur.html i am doing ajax and fetch details from database using requested id and display in class result .
This is the current process . But what i need is
in single-colur.html?id=anynumber
i have to replace the current page url with colour-name.html
and show the details . [BUT the thing is there is no colour-name.html page in server . ie there is no red.html, green.html,blue.html in server . It have to be virtually created by jquery . ]
Use Ajax :
$.ajax({
url: "my-colours.html",
type: "get", //send it through get method
data: {
id: //<Your id here >
},
success: function(response) {
window.location.href = '/' + response.color + '.html' ;
},
error: function() {
//Do Something to handle error
}
});
I suppose this is what you're looking for. Here a dynamic link will be created by ajax and you can give a dynamic value to Id each time.
So you use
window.location = window.location.hostname + "here put the returned from ajax" + ".html";
Explain
window.location.hostname
returns the website url
This example is as complete as it can be in this environment.
Load on click via ajax
Set content
Set virtual url
$( 'a.virtual' ).click( function( e ) {
var link = $(this);
console.log( "Loading: " + link.attr('href') );
$.ajax({
url: link.attr('href'),
type: "get",
success: function(response) {
// parse json or howerver data get transferred
var result = parseJSON(response);
var content = result['content'];
var virtual_url = result['url'];
// set content
$('#content').html( content );
// set virtual url
window.history.pushState([], 'Title', virtual_url);
}
});
// do not follow the link!
e.preventDefault();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a class="virtual" href="my-colours.html?id=1">Link A</a></li>
<li><a class="virtual" href="my-colours.html?id=2">Link B</a></li>
<li><a class="virtual" href="my-colours.html?id=3">Link C</a></li>
<li><a class="virtual" href="my-colours.html?id=4">Link D</a></li>
<ul>
<br/>
Content delivered via ajax:<br/>
<div id='content'>
</div>
For several days, I cannot figure out how to design a solution for the following issue: I have a lot of items (around 1300) stored in database, each has its own "id", some "name" and a third property "enabled".
I would like to show on the same page to the user links to (all) the dialogs. Dialogs then shall show the "name" and allow the user to select OK/Cancel (i.e. enable/no action). (Changing of "enable" is made through a file some_file.php, which is already working properly and is not subject of this question.)
I have found similar questions like this or this but any of them so not need to pass variables between php and javascript like my dialogs.
I am not able to solve the problems stated below in comments:
javascript:
$(function(){
$('#dialog').dialog({
autoOpen: false,
width: 600,
modal: true,
buttons: {
'Cancel': function() {
$(this).dialog('close');
},
'OK': function() {
$.ajax({
url: 'some_file.php',
type: 'POST',
data: 'item_id=' + id,// here I need to pass variable, i.e. $line["id"] from the php loop
});
$(this).dialog('close');
}
}
});
$('.link_dialog').click(function(){
$('#dialog').dialog('open');
return false;
});
});`
html + php:
<?
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// not sure here how to pass the "text" to some javascript function
if ($line["name"]=="") {
text = "Number ".$line["id"]." does not have any name.";
} else {
text = "The name of number ".$line["id"]." is ".$line["name"];
}
}
?>
<a href='#' class='link_dialog'>Dialog 1</a>
<a href='#' class='link_dialog'>Dialog 2</a>
<a href='#' class='link_dialog'>Dialog 3</a>
<div id='dialog' title='Name' style='display: none;'>
// not sure here how to extract the "text" from javascript function created above
</div>
jsfiddle demo (of course, not working)
If somebody sees the point, I would really appreciate your help. You can update my jsfiddle.
In PHP:
<?
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($line["name"]=="") {
$text[$line["id"]] = "Number ".$line["id"]." does not have any name.";
} else {
$text[$line["id"]] = "The name of number ".$line["id"]." is ".$line["name"];
}
}
/***
* Give each link unique ID (I've used 'dialog-n')
* Advantage to creating link dynamically:
* (what if the number of dialogs changes in the future?)
* Also suggest that you wrap these in a div
*/
$num_links = count($text);
for($i = 1; $i <= $num_links; $i++) {
echo "<a href='#' id='dialog-$i' class='link_dialog'>Dialog $i</a>";
}
HTML:
<div id='dialog' title='Name' style='display: none;'>
</div>
In Javascript:
var DIALOG_TEXT = <?php echo json_encode($text); ?>; //Pass text via JSON
$('.link_dialog').click(function() {
var link = this;
//Get link ID
var link_id = link.attr('id').split('-'); //Split string into array separated by the dash
link_id = link_id[2]; //Second array element should be the ID number
var msg_text = DIALOG_TEXT[link_id]; //Retrieve associated text
//Insert text into dialog div
$('#dialog').text(msg_text); //Use .html() if you need to insert html
$('#dialog').dialog({
buttons: {
"Cancel": function() {
$(this).dialog('close');
},
"OK": function() {
$.ajax({
url: 'some_file.php',
type: 'POST',
data: 'item_id=' + link_id, //Use link id number extracted above
});
$(this).dialog('close');
}
}
});
return false;
});
I have not tested the above, you will probably have to modify for your needs.
OPTION 2:
If you intend to have the dialog content generated dynamically (e.g. only when the user clicks the link), you can do the below
jQuery('#dialog').load('content_generator.php?item_id=**[your id]**').dialog('open');
where 'content_generator.php' takes the given id and outputs the appropriate text, which ".load()" inserts into the dialog.
Option 2 is based on the answer given by Sam here
What you are trying to do is called dynamic content loading. My last example does this by inserting the necessary data (as JSON) and generating the content directly on the page.
This next method may not be suitable for what you are trying to do, but may be useful later.
Instead of retrieving the data and generating the content on the page itself, we use an external page to provide content for us. This reduces server load by only providing the needed content, and can increase user interactivity (because the page doesn't have to load up all the information before it gets displayed to the user). See [here][1] for further information about AJAX.
Advantages: Separating the content generation from the page a user accesses. What if you need to show the same/similar content elsewhere on the website? This method allows you to reuse the code for multiple use cases.
You can even combine this with the previous method. Just use a separate PHP file to generate your dialog content and links en masse (rather than per click as shown below), which gets called and loaded in on $(document).ready()
Per click example:
Generate the content per click
A separate PHP file - dialog_text_generator.php:
<?
//DON'T ACTUALLY DO THIS. ALWAYS SANITIZE DATA AND AVOID USING mysql_ prefixed
//functions (use mysqli or PDO).
//This is just to illustrate getting data from the DB
$item_id = $_REQUEST['item_id'];
$query = "SELECT * FROM `stuff` WHERE item_id = $item_id";
$query_results = mysql_query($query, $db_connection);
$num_matches = count($query_results);
$text = array();
for($i = 0; $i < $num_matches; $i++) {
$current_item = $query_results[$i];
//Print out content
//replace 'name' with whatever field your DB table uses to store the item name
if($current_item['name'] == '') {
echo "<p>Number $item_id does not have any name.</p>";
} else {
echo "<p>The name of number ".$item_id." is ".$current_item['name']."</p>";
}
}
?>
Javascript in your main page:
<script>
$('.link_dialog').click(function() {
//On user clicking the link
var link = this;
//Get link ID
var link_id = link.attr('id').split('-'); //Split string into array separated by the dash
link_id = link_id[2]; //Second array element should be the ID number
//autoOpen set to false so this doesn't open yet, we're just defining the buttons here
$('#dialog').dialog({
autoOpen: false,
buttons: {
"Cancel": function() {
$(this).dialog('close');
},
"OK": function() {
$.ajax({
url: 'some_file.php',
type: 'POST',
data: 'item_id=' + link_id, //Use link id number extracted above
});
$(this).dialog('close');
}
}
});
//Load content from PHP file into dialog div and open the dialog
//Obviously use the actual path to dialog_text_generator.php
jQuery('#dialog').load('dialog_text_generator.php?item_id='+link_id).dialog('open');
return false;
});
</script>
I'm using jQuery UI tabs loading an external form in the tabs. The form is set to submit when the checkbox in the form is clicked on. The form is submitted using ajax. What I'm searching an answer for, is to refresh the tab content after submitting the form, but I haven't had any luck finding the answer.
$(function() {
$("#tabs").tabs({
cache: true,
beforeLoad: function( event, ui ) {
ui.jqXHR.error(function() {
ui.panel.html("Can't load content. Please call support.");
});
if(!($.data(ui.tab[0], "cache.tabs"))) {
return $(ui.panel).html("<div align='center'><img src='images/loader.gif'><p><strong>Loading...</strong></p></div>");
}
}
}); });
The tabs are generated using PHP loading variables from a DB:
<div id="tabs">
<ul>
<?php
$sql = mysql_query("SELECT username, name FROM members ORDER BY username") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
echo "<li><a href='tasks.php?user=" . $row['username'] . "'>" . $row['name'] . "</a></li>\n";
}
?>
</ul>
</div>
The form is in the file tasks.php and the submit script is:
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "update-task.php",
data: $("#form1").serialize()
}); });
It works perfect. When clicking on checkboxes with the class ".checkbox", the form is submitted and the database is updated. But I would like to have the text in the tab to have a different color and the list resorted so that the checked items are moved to the bottom when the form is submitted (I planned to do this on the serverside using PHP). For this I need the content in the tab to be refreshed, but I don't know how. Best guess is to add this in the ajax form submit:
success: function() {
// Something that refreshes tab content
}
But I have no clue to what to do. Any ideas?
/Carl
Try this:
success: function() {
var tabId = $("#tabs").tabs("option", "active");
$("#tabs").tabs("option", "active", tabId);
}
Can't use the refresh method?
$( "#tabs" ).tabs( "refresh" );
http://api.jqueryui.com/tabs/#method-refresh
That said, I'm not sure why you need to refresh in order to change font colors. Seems like you'd just do that directly in your success function:
success: function() {
$('.my-selector').css('color', 'orange');
}
Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>