Send dynamic HTML list with PHP to server - php

I have two simple HTML lists. The first one contains a bunch of entries, the second one is initially empty. The common list structure is the following:
<ul id="project-offer-list" class="connectedSortable">
<li class="ui-state-default">
<div>
<!-- formatting -->
</div>
</li>
<li class="ui-state-default">
<div>
<!-- formatting -->
</div>
The user can select some entries from the first list by dragging them to the second one. By doing so he can give a preference by sorting the elements within the second list.
The drag-drop-mechanism is realized by JQuery:
<script>
$(function() {
$("#project-offer-list, #project-selection-list").sortable({
connectWith: ".connectedSortable"
}).disableSelection();
});
</script>
I want to send both the selected elements (those in the second list) and their order to a remote server with PHP. Whenever the user clicks the "Save" button, the current selection should be sent.
How can I achieve this? I would need to assign an id to each list element and somehow read the second list and its order. It is crucial that possible changes in the HTML code made by JQuery are considered.
Thanks

You Need to convert the data of the second list into json object, assign the id to each element, use the same id which you have in your database as it would be more easy to update and perform options on existing data,
var items = [];
$('ul#list_id').find("li").each(function() {
var $this = $(this);
var item = { id: $(this).attr('data-id'), title: $(this).text() };
items.push(item);
});
You will get something like this, and use an ajax to send this to your remote server
[
{"id":"1","title":"School-management"},
{"id":"2","title":"library-management"},
{"id":"3","title":"billing_software"}
]

Related

.on('click') with wildcard not not delegating as expected

Will try to keep this simple so its not too much reading
I have a simple page with the following ...
$divid = 'append_here_$x;
$clickme = 'click_$x';
<div id='$clickme'>Click Me</div>
<div id='$divid'></div>
Then , I have a separate php file that builds content in a while loop generating a unique id for each div.
while ...
$imgid = 'imgid_$z' ...
<div id='$imgid'>This was appended</div>
Finally, I have this just for testing and keeping things short
$( "[id^='imgid_']").on( "click", function() {
alert('you clicked me');
});
This above works fine for the most part. If you were to click on click me, it will do ajax call and a post against the file with the while loop in it, return data and append it inside the append_here_ div. The problem is the new appended data that also has an id so yo can click will not respond to the simple click.
The way you link the click event to the elements of the page will not work for elements added later.
You are linking the event to the elements present by the time you define the click events, but if you add items later, they won't have the event on them. You could do:
$(document).on('click', '[id^="imgid_"]', function() {
alert('you clicked me');
});
That way, the event will be on the document, which is present at the startup, and everytime you click, it will check the selector (second parameter), so the new elements will respond to the click.

jquery sortable pass array to php

I have a jQuery sortable list. Ultimately what I want is a simple php array of list id's. I'm trying to take the id and position in the array and add it to a database. I would like a user to be able to change the order of the list as long as they want, and when they are satisfied with the order, click a button to submit.
I have seen many examples of sortable lists that update every time an item position is switched, but that is not what I want.
This is simplified. The id's will be dynamically generated with php.
<body>
<form>
<ul id="sortable-1">
<li id="order1">Item 1</li>
<li id="order2">Item 2</li>
<li id="order3">Item 3</li>
<li id="order4">Item 4</li>
<li id="order5">Item 5</li>
</ul>
<input type="button" value="Submit" onclick="go">
</form>
</body>
jQuery that will make the list sortable and also post every time the order is changed, not what I want. I need a separate function called go with the ajax. Also, is .sortable('toArray').toString() what I want intead of ("serialize")? It seems to make a simple array of id values.
$(function(){
$("#sortable-1").sortable({
update: function(event, ui){
var operationOrder = $(this).sortable('toArray').toString();
$ajax({
data: operationOrder,
type: 'POST',
url: 'order.php'
});
}
});
});
The php, which would hold an array of id values:
$order = array();
$string = $_POST['data'];
$order = explode(",", $string);
Thanks for any help. It may be simplistic for experienced programmers but I've been working on it for days...
In order to receive data array with $_POST['data'] you need to send array as value for key data. Also note you shouldn't have to stringify the array. jQuery will properly form encode it for you.
$ajax({
data:{data: operationOrder},// don't need to stringify this array
type: 'POST',
url: 'order.php'
});
Now to verify, learn how to inspect ajax requests in browser console network tab and you will see exactly what is sent. Browser console (F12) is always where you start when debugging ajax

JS: Changing this function to handle a link click

Following the example here Very Simple jQuery and PHP Ajax Request – Ready to use code
I've been successful in creating a drop down list that passes the value to an external PHP script and returns the HTML output back to a "div" on the same page and it works great.
What I want to do now is post values when I click on link instead of building a drop down list. So ...if I created this link:
Route Number 2
I want "2" passed to that external PHP script and the content changed on the " div " as it currently works with the dropdown. I don't know how to change the javascript to handle this or what "foo.php" really needs to be.
Here's the current javascript from that example:
<script type="text/javascript">
$(document).ready(function() {
$('#route_number').click(function() {
routenumber = $('#route_number').val();
$.post('api.php', { route_number : routenumber }, function(res) {
$("#mainlayer").html(res);
});
});
});
</script>
And here's what the dropdown portion of the HTML looks like:
<select name="route_number" id="route_number">
<option value="notchosen">Please Choose A Route</option>
<option value="2">Riverfront</option>
<option value="11">Magazine</option>
<option value="16">Claiborne</option>
</select>
<div id="mainlayer">
</div>
So, to be clear, instead of a dropdown that passes values, I want to create links that accomplish the same result.
Thanks in advance,
dan -
Create a class, capture its (meaning whatever link you clicked on) value, then post.
<a class="RouteNumber" href="foo.php?route_number=2">Route Number 2</a>
$(function(){
$('a.RouteNumber').on('click',function(event){
// prevent the browser's default action for clicking on a link
event.preventDefault();
// break href attribute into array, then parse desired value as int
var routenumber = $(this).attr('href').split('='),
rtnum = parseInt(routenumber[1]);
$.post('api.php',{route_number:rtnum},function(res){
$("#mainlayer").html(res);
});
});
});
If you don't need to parse the integer out of it (if a string is good enough), you don't need that second variable. You can just use routenumber[1] in the post data.
Just a heads up, I modified the jQuery to use the .on() syntax. .click() is shorthand for it, but I like using .on() just because it allows for less potential codewriting if you want to do more (like mouseenter/mouseleave, for example) because you can combine them into a single codeset.
I had hoped simply fixing #LifeInTheGrey's example would've sufficed, but there are some things I would've done differently that probably need some explaining.
Your HTML could look something like this:
<a class="route" href="foo.php?route_number=2" data-route="2">Route Number 2</a>
The JavaScript would look something like this:
$(function() {
var fill_div_with_response = function(res) {
$("#mainlayer").html(res);
};
var handle_error = function(res) {
alert('something went wrong!');
};
$(document.body).on('click', '.route', function(event) {
// prevent the browser's default action for clicking on a link
event.preventDefault();
// grab route number from data attribute
var route = $(this).data('route');
// make that post request
$.post('api.php', {route_number: route})
// handle the response
.done(fill_div_with_response)
// handle errors
.fail(handle_error);
});
});
The example uses delegated events. They're cheap to initialize and consume the least amount of memory.
The example handles errors. Most answers to questions like these neglect that. errors happen. Always. Make people aware of that. Surely throwing an alert() is not the thing you want to be doing, but it's still better than simply ignoring errors completely.
The example uses Deferreds (Promises) rather than callbacks, as this usually makes code much cleaner.
We're defining the callbacks fill_div_with_response() and handle_error() at the root closure to prevent redefining them on the next click. There's no need to feed the garbage collector.
The data attribute poses the optimal alternative to <option value="123"> in the way that it prevents you from having to parse the href attribute to extract that number from a string.
since you want to make a menu, I would modify your markup
<ul name="route_number" id="route_number">
<li value="2">Riverfront</li>
<li value="11">Magazine</li>
<li value="16">Claiborne</li>
</ul>
then simply process that list:
$('#route_number').find('li').click(function () {
var routenumber = $(this).attr('value');
$.post('api.php', {
route_number: routenumber
}, function (res) {
$("#mainlayer").html(res);
});
});
EDIT1: As an improvement (as you seem to be pretty new to this stuff) you could use the data with altered markup as such:
<ul name="route_number" id="route_number">
<li data-routenumber="2">Riverfront</li>
<li data-routenumber="11">Magazine</li>
<li data-routenumber="16">Claiborne</li>
</ul>
Then the code would be:
$('#route_number').find('li').click(function () {// add click event manager to each li
var routenumber = $(this).data('routenumber');// get routenumber of clicked
$.post('api.php', {
route_number: routenumber
}, function (res) {
$("#mainlayer").html(res);
});
});
Alternate code using .on() form
$('#route_number').on('click, 'li', function () {//click event manager for ul/li
var routenumber = $(this).data('routenumber');// get routenumber of clicked
$.post('api.php', {
route_number: routenumber
}, function (res) {
$("#mainlayer").html(res);
});
});
Note that this last form binds to the #route_number element so you could add more menu options during processing and they would still work. This is also better than attachment to the document as it is a more focused approach to the event attachment.
My understanding of your question is that the functionality you have is fine, and you just need to change the look to a piece of text from a dropdown. If so, good news! You can keep (almost) the same JavaScript.
Right now, your JavaScript is getting the value of your select box, sending it via AJAX, and using the returned value. The only change you need is to get the 'value' of the text clicked.
You don't want to use a link, since that's designed to take the user someplace. Instead you can use a span and format it to look like a link, or even a button if you want that kind of look.
You will also need to change $('#route_number').val();, probably to something passed by the click event. For example:
<span id="route1" class="routeSpan" onclick="sendVal(1)">Route 1 Name</span>
<span id="route2" class="routeSpan" onclick="sendVal(2)">Route 2 Name</span>
And your JavaScript:
function sendVal(routeVal) {
$.post('api.php',{route_number:routeVal},function(res){
$("#mainlayer").html(res);
});
}

jquery mobile page fluctuating on ajax reponce load

I am working with a mobile application in which
first page has
Html
<ul>
<li>121212</li>
<li>123233</li>
<li>232323</li>
<li>4323423</li>
<ul>
when user click on "li" then he/she entered on next page which will retrieve data related to selected "li" via Ajax.
this is almost going good..
But when Ajax response come page is fluctuating 2 times.
Means one time page loading, next time page totally white and then again showing page with Ajax response.
Why ???
J query
$("clickOnLi").click(function(){
var id= $(this).val(); //get the selected li value
$('.loadingGif').css({ 'display':'block' });
$("#ulShowContent").html(''); // to remove old inner HTML to show new result html
var dataString = 'selectedid='+id;
$.ajax({
type: "POST",
url: remoteUrl+"handler.php",
data : dataString,
cache: true,
success: function(response) {
if(response){
$('.loadingGif').css({ 'display':'none' });
$("#ulShowContent").html(response);
}
}
});
})
**and the result will show in this html**
<ul id="ulShowContent" data-role="listview">
<li class="comment chatsend">
<div class="comment-meta">
data 1
</div>
</li>
<li class="comment chatsend">
<div class="comment-meta">
data 2
</div>
</li>
</ul>
You will need to change how you deal a page change and AJAX call.
What I have understand from your question, after click on LI element, page change is initialized and AJAX call is sent to a PHP server.
You will need to change this logic. Page fluctuations are cause by AJAX call which is executed during the transition from one page to an another.
This can be fixed like this:
On a first page remove HREF attribute from a list element
Add a click event to every list element
AJAX call should be executed on click event, at a same time show your custom loader (or use a default one)
When server side data is retrieved you need to store it so it can be accessed from an another page. Here you will find my other ANSWER where you can find various methods of storing data during page transitions, or find it HERE, just search for a chapter called: Data/Parameters manipulation between page transitions (your best bet is a localstorage).
Initialize a page change with changePage function
During a pagebeforeshow event (page is not yet displayed) append new data to the new container
When second page is finally shown everything will be there and

Getting all list items of an unordered list in PHP

I have these tag cloud list
<ul #id = "tag-cloud-list">
<li class = "items">Music</li>
<li class = "items">Lion</li>
<li class = "items">Dwarf</li<
</ul>
That was generated by JQuery. The items here are tags that I will insert to the database. Now my question is it possible to get all <li> items inside the ul? and put them inside a PHP array? because each of these tags will be inserted in the database. if there's no way I can get a li items using php then how would Insert these list items into the database? because I needed them since it is tag to a certain item or post
You have to make an AJAX call:
var lis = new Array();
// Iterate through the <li> items
$("#tag-cloud-list").children("li").each(function()
{
lis.push($(this).text());
});
// Make AJAX call and set data to something like "Music::Lion::Dwarf"
$.ajax({
url: "dostuff.php",
type: "POST",
data: { items: lis.join("::") },
success: function() { alert("OK"); }
});
Then in the PHP script, use
$lis = $_POST['items'];
$liarray = explode("::", $lis);
to retrieve an array of the li items
You can't get these in PHP unless you send the data back to the server somehow. PHP executes on the server, if this is coming in via a jquery, then PHP knows nothing about it.
You will need to either use javascript to get all the information and send it back to the server, or you need to send the entire page HTML (somehow) back to the server to be looked at by PHP. I suggest the first option.
Edit: I am not flash-hot with javascript, just use some basic functions, but you could write an event into a <div> or where the data is coming into along. The function would find how many <li> there are in the <ul id="tag-cloud-list"> pop them into an array and send them to the PHP server, by a form or ajax query.
Sorry that I can't help much with the js code.
You need to get all items in the ul using .find() function from JQuery and make a POST with ajax and process the information

Categories