Linking PHP into Mootools on select - php

How would I fill in the boxes of my form if I select one of the values from the dropdown menu (The dropdown is got from the DB) Somehow in my javascript I need to connect to functions as there is to different tables involved with the form fields.
Question
Do I need to set the fields using $field name?
if(document.id('LoadExtension') && document.id('ExtensionResponse')) { // id of select box
var sel = document.id('LoadExtension'); // ser select box as var.
sel.addEvent('change', function(chg) { // add change event to select box.
if(sel.getSelected().get('value') != '') { // on change if selected value is not empty.
new Request.HTML({
url : 'http://domain.co.nz/index.php?extension='+ sel.getSelected().get('value'),
onRequest: function() {
},
onComplete: function(r1, r2, html, js) {
document.id('ExtensionResponse').set('html', html);
}
}).send();
}
});
}
The above code was set up to get from another document in the url: box but I would like to do it in one page.

for your code:
http://www.jsfiddle.net/dimitar/TXHYg/4/
(function() {
// anon closure for scope purposes of local vars.
// cache selectors used repeatedly into local vars.
var sel = document.id('LoadExtension'), resp = document.id('ExtensionResponse');
// if they are in the dom...
if (sel && resp) {
// ... then attach event listener.
sel.addEvent('change', function(event) {
// this == sel.
var value = this.get("value"); // cache getter.
if (value === '') {
return false; // do nothing if not selected/
}
// otherwise, it will run the request
new Request.HTML({
method: "get", // or post.
data: {
extension: value // etc etc, can add more object properties and values
},
url: 'http://domain.co.nz/index.php',
onComplete: function(r1, r2, html, js) {
resp.set('html', html);
}
}).send();
});
} // end if
})(); // end closure.
you should really look at some tutorials and examples and the documentation for Request and Request.HTML/JSON/JSONP
an example, similar to yours that works for jsfiddle through its echo testing service (slightly different data object that simulates the response)
http://www.jsfiddle.net/dimitar/TXHYg/3/

instead of document.id('ExtensionResponse') you can write $('ExtensionResponse')
an if you only update a content of a element you can use the update parameter from Request.HTML.
new Request.HTML({
url : 'http://domain.co.nz/index.php',
data: 'extension='+ sel.getSelected().get('value'),
update: $('ExtensionResponse')
}).send();

#medrod;
That's right about the $(), but using the latest version of mootools + making sure Jess stays library safe, document.id() is a much safer option for compatibility.
you need to build the rest of your form, and populate it, with in the result of the ajax request.
eg: http://domain.co.nz/index.php?extension=
start your first HTML form with only the drop down, then your ajax'd script will build and populate the rest of the form.

Related

Codeigniter 3 application: update MySQL table column and the corresponding view through Ajax

I am working on a Register and Login application with CodeIgniter 3 and Twitter Bootstrap.
I have a "users" MySQL table and a corresponding "users.php" view that renders the "users" table in an HTML format, like the image below illustrates:
The "Actions" column in the Bootstrap table has, on each row, an "Enable" or "Disable" button, depending on the state of he user. The code for this part of the view is:
// Status column
<td>
<?php if ($user->active == 1) {
echo '<span class="text-success">' . 'Enabled' . '</span>';
} else {
echo '<span class="text-danger">' . 'Disabled' . '</span>';
}
?>
</td>
// Enable/Disable buttons
<?php if ($user->active == 1) { ?>
<span class="glyphicon glyphicon-ban-circle"></span> Disable
<?php } else { ?>
<span class="glyphicon glyphicon-ok"></span> Enable
<?php } ?>
I activate/deactivate users without page refresh, via AJAX:
$('.state-change').on('click', function(evt) {
evt.preventDefault();
var id = $(this).data('id');
var role = $(this).data('role');
if (role == "activate") {
var stateUrl = 'users/activate/';
} else {
var stateUrl = 'users/deactivate/';
}
$.ajax({
url: stateUrl + id,
method: 'GET',
dataType: 'php',
success: function(){
console.log(id);
console.log(role);
}
});
});
The problem is that the data regarding the state of the user does not come back to the view and the columns "Status" and "Actions" do not render correctly.
I wish I didn't have to update the view "statically" from the success callback, with jQuery's html() method or something similar.
function(){
console.log(id);
console.log(role);
//change columns html here
}
What shall I do to update the view "dynamically"?
The above answers are adequate - you must use JavaScript given your scenario. It seems the trouble lies in making the leap from dynamic web pages to dynamic HTML.
Read the last line of the summary here:
https://en.wikipedia.org/wiki/Dynamic_HTML
You will need to use javascript to modify your table after you get the data back. Since you're already using jQuery, you have tools to make that pretty simple.
Your problem can be broken into two steps: Identify the right part of the page to update, and then modify the cells of interest.
Identifying the right cells is simplified because the mouse event passed to your function includes a reference to the thing that was clicked.
To make finding the right parts of the table easier, it's good to give each <td> a class:
// Status column
<td class="status-column">
// your php status stuff from above
</td>
// Button column
<td class="activate-column">
// your php button-drawing stuff from above
</td>
Now it will be easy to find what you're looking for to modify.
Here's your ajax call with a few additions to redraw the cells in question:
$('.state-change').on('click', function(evt) {
evt.preventDefault();
var id = $(this).data('id');
var role = $(this).data('role');
if (role == "activate") {
var stateUrl = 'users/activate/';
} else {
var stateUrl = 'users/deactivate/';
}
$.ajax({
url: stateUrl + id,
method: 'GET',
dataType: 'php',
success: function(){
console.log(id);
console.log(role);
// find the row that is the parent of the clicked button - http://api.jquery.com/parent/
var row = evt.target.parent('tr');
// use the class of the table cell to identify it. http://api.jquery.com/find/
var statusCell = row.find('.status-column').first();
// now put in the new status. http://api.jquery.com/html/
if (role == "activate") {
statusCell.html('<span class="text-success">Enabled</span>');
} else {
statusCell.html('<span class="text-danger">Disabled</span>');
}
}
});
});
I'll leave the button column for you to practice with :).
Edit: you can also manipulate the DOM with non-jQuery methods that are perhaps more to your liking. This is what jQuery is doing under the hood anyway.
You can read more about them at MDN.
// build the new DOM node
var newStatusCellContent = document.createElement('span');
newStatusCellContent.setAttribute('class', role == 'activate' ? 'text-enabled' : 'text-danger');
newStatusCellContent.textContent = role == 'activate' ? 'Enabled' : 'Disabled';
// get the parent <td> node from the jQuery object
var statusCell = row.find('.status-column').get(0);
// swap the old contents for the new
var oldChild = statusCell.childNodes[0]
statusCell.replaceNode(newStatusCellContent, oldChild);
Careful study of the documentation at the above link will probably reveal ways to make that more efficient for your particular case. Keep in mind that this is the same thing the jQuery html() method does — or Angular or any other — and that while it keeps you away from HTML, it doesn't really improve your code in this case. I really hate HTML, but it's the tool we're given.
Note that php also has DOM libraries; if you wanted, you could use those to build your original page as well, and be done with HTML forever. But I don't recommend it except in certain cases.

select2 to add new tags with confirmation box

In Select2 I have basic tagging functionality working. The tagging system is works in an insert project page, where I can tag projects with certain predefined tags that are stored in a database and called by AJAX, and also in an update project page where the same mechanism is at play with the addition of bringing up currently stored tags in the tag field.
I want it so that if no tag currently exists, the user will receive a confirmation box that asks whether or not they want to add a new tag, and by hitting ok that tag will then be stored in the database. There should also be a sort of buffer time of a few seconds for Select2 to catch up with looking up the tags otherwise it might create duplicates?
I have read something here that shows how to do the jquery part, albeit its incomplete for my purposes. Can anyone shed light into how I might do this? I am not looking for complete answers, but merely guidance.
Have a look at this question: How do I fire a new ajax on select2 new /remove tag event?
In your case, using your fiddle, you can use something like:
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
// A new tag was added
// Prompt the user
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
// User clicked OK
console.log("Sending the tag to the server");
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
} else {
// User clicked Cancel
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
Draft fiddle here.

this is regarding Jquery/JS, if i change element's HTML - will i be able to perform other Jquery/JS action on it

I have a a script that on click do a ajax call connect to the database get imagename and set the image name inside an < -img - > with the right path also it adds a hidden checkbox after it and then echo it.
i then take the ajax message returned and put it as div's HTML. my question is will i be able to preform more action on the inserted content..
The main goal is to be able to click on the image as if it were a checkbox(this part is already sorted for me) however no matter what i try i cant have a .click function works..
Here is the code.
This is the PHP part that echos the images.
if($_POST['updateIgallery'] == 'ajax'){
global $wpdb;
$table_name= $wpdb->prefix . "table_T";
$imagecounter = 1;
$toecho = '';
$currentselected = $wpdb->get_row("query");
preg_match_all('/\/(.+?\..+?)\//',$currentselected ['image_gal'],$preresualts); // images are stored with /image/.
foreach ($preresualts[1] as $imagename){
$toecho .= '
<img rel="no" id="JustantestID" class="JustaTestClass" src="'.site_url().'/wp-content/plugins/wp-ecommerce-extender/images/uploads/'.$imagename.'">
<input name="DoorIMGtoDeleteIDcheck'.$imagecounter.'" style="display:none;" name="DoorIMGtoDelete['.$imagecounter.']" value="/'.$imagename.'/" type="checkbox">
';
$imagecounter++;
}
echo $toecho;
}
This is the ajax part that send and receive and insert the HTML to the div:
$.ajax({
type: "POST",
url: "/wp-content/plugins/wp-ecommerce-extender/DB_Functions.php",
data: { updateIgallery: "ajax", CurrentDoorIDnum: $('#dooridforgallery').val()}
}).success(function(insertID) {
$("#ImgGalleryID").html(insertID);
});
This so far works what i am having trouble with is the following:
$("#JustantestID").click(function() {
//DoorImageGallery($(this).attr('id')); // the function i will use if the alert actually works
alert("kahdaskjdj");
return true;
});
I hope the question and the code is understandable.
Thanks in advanced.
When you replace element's html, all the elements inside it are removed and gone. That means the event handlers attached to them are removed as well.
You could try attaching an event handler to a higher level element that is static and permanent on your page. Without more info I am going to use document:
$(document).on( "click", "#yaniv", function() {
alert("kahdaskjdj");
});
$('img.JustaTestClass').bind('click', function() {
var checkbox = $(this).siblings('input[type=checkbox]');
if (!checkbox.is(':checked')) checkbox.attr('checked', true);
else checkbox.attr('checked', false);
});
Since the elements are dynamically inserted into the DOM with ajax, you have to delegate events to a parent element that actually exists when binding the click handler, which in this case looks to be #ImgGalleryID
$('#ImgGalleryID').on('click', '#yaniv', function() {
DoorImageGallery(this.id);
alert("kahdaskjdj");
});

How to check for contents of a loaded div tag using jquery load?

I'm working with jqueries address change event and am hitting a roadblock when a user copies and pastes a URL in the browser. I need to fist load a portion of the page that contains a form. I could do this after every pagination call but it seems really ineffecient.
Here is my current code block:
$.address.change(function(e) {
var urlAux = e.value.split('=');
var page = urlAux[0];
var start = urlAux[1];
if (page == "/visits") {
$.address.title("Profile Views");
if (start) {
$('#start').val(start);
// ***** If a user has copied and pasted this URL with a start value then I first need to load visits.php in the main div tag. Is it possible to see if this is loaded or not?
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
}
else {
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () { });
}
}
My attempted work around was this:
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
There must be a better way...this is realoading the same portion of the page (visits.php) with every pagination event. Is there a better way to load URLs and not have them trigger an address change?
Using paul's work around from his comments, but instead of Regex'ing html content in the visits.php form this solution will look for data() attached to #mainID.
Paul's work around notes:
After a bit more hacking I came up with this solution that seems to do
the trick. I'm not sure how good it is but it seems to do the trick. I
now get the main div id and do a regex match on a unique string in the
form. If I don't see it I load the form and then load the results. Not
sure if this is good practice or not but it seems to solve my issue.
Methodology to use .data() instead of a regex search of visits.php's html:
/*check if we're missing visits.php by looking for data() flag*/
if( !($("#main").data()["hasVisitsPhp"]) ){
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
/* we've loaded visits.php, set the data flag on #main*/
$('#main').data("hasVisitsPhp","loaded");
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
}
try window.location.hash instead. Changing the whole href can/will trigger a whole-page reload, while changing just the hash by itself should at most cause the page to scroll.

Submit Value With Javascript

I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}

Categories