I used jQuery's .append() to add new li elements to a ul on success in an AJAX call. The problem is, whenever I refresh the page, the newly appended list items disappear.
I've read this has to do with refreshing the original page, and that some options are to use cookies (PHP or jQuery). I also saw something about localStorage. I'm not using HTML5, if that matters.
What is the best way to go about this? If I use PHP, can I embed the script inside of jQuery? Is there a more elegant way of going about this?
Thanks
Edit: included code
AJAX
$.ajax ({
type: 'post',
url: '/classes/resources/addResource.php',
data: {
recName: $('#recName').val(),
recURL: $('#recURL').val()
},
success: function(data) {
if (data === 'added') {
var h3ID = $('#categoryList option:selected').val();
var title = $('#recName').val();
var url = $('#recURL').val();
var newListItem = '<li>' + title + '</li>';
$('ul#' + h3ID).append(newListItem);
$('span#resError').fadeIn(400).text('Resource added successfully. Add another?');
}
else
$('span#resError').fadeIn(400).text('There was an error adding this resource');
}
});
HTML
<h3 class="category" id="1">
Category 1
</h3>
<ul id="1">
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
</ul>
When I add List item 5 and so on, I want those new list items to remain upon refreshing the page.
If you build your page dynamically using ajax / javascript, you need to store the current state so that you can build it exactly the same way when the page is reloaded.
There are several ways to do that like sessions (server-side) or cookies / localStorage if the information you need to build the page is stored on the client side.
If you are not using html5 but you are using ajax to build the page, using sessions and doing everything server-side is probably the easiest option. Just store the current / updated state of the page every time an ajax request is made.
An additional consideration is how long the information has to persist. If you use the standard php session mechanism, your session / state will be lost pretty fast (about an hour without reloading / refreshing I think with the default settings).
Related
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
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
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
I have following code in my php page. These are two tabs Inbox and sInbox. When user clicks on them it refreshes whole page to go to other tab. Is there a way to make these tabs so that when user click on one of the tab there is no page refresh? When answering please provide full code example as i am a beginner.
<ul id="topTabs">
<li class="selected"> Inbox </li>
<li> sInbox </li>
</ul>
One of the simplest ways would be using jQuery UI tabs. You can find a nice detailed beginner-friendly tutorial here.
I wouldn't say that you need ajax to do this. Ajax is only needed when you want to load content of these tabs dynamically.
Do realize your tab-switching you can use jQuery or simply the style-property "display:block" resp. "display:none".
It's very hard to provide some code for your question (because you need to change your page structure) but as a hint, you need to use jQuery ajax or php ajax update panel (if there is something like this - I know there is one for ASP.NET) to refresh some parts of your page (instead of whole).
In the earlier case (jQuery) your links will not be redirection links and will have a click action associated to them which requests for page update using ajax.
see the link for examples of using ajax using jQuery.
You can do it easly using ajax:
$(document).ready(function() {
$("#topTabs li").click(function() {
var mode = $(this).find("a").attr("href");
$.ajax({
url: 'contentprovider.php',
data: {mode:mode},
success: function(data){
$('#tab1').html(data);
}
});
});
});
Where tab1 is the ID of the element wich may receive the content from contentprovider.php
More info on jQuery Ajax at jQuery Page.
gl
Paulo Bueno.
In order to show you what I want to do you just have to visit gmail. When you click on the inbox, the url refreshes to this ?tab=mm#inbox and the only part of the page that refreshes is the big part where your e-mails are which google calls div.l.m . How is that possible? Are they using cache a lot or they are using a javascript command I'm not aware of?
What I want to do is, I have a page with two different tabs.
<div id="navcontainer">
<ul id="navlist">
<li id="active">Products</li>
<li><a id="prreq" onclick="show()" >Requests</a></li>
</ul>
</div>
<div class="container"></div>
When users go on eg. cart.php they are going to the first tab. When users click on the second tab a js function is triggered which calls the file cart.php?rq=r and the results are shown in the container div. (I know that at the moment I have post)
function show(){
var prstr= ".container";
var data= {
rq: "r"
};
$.ajax({
type: 'POST',
url: "cart.php",
data: data,
success: function(data1)
{
$(prstr).html(data1);
}
});
}
What I want is when the user refreshes the page to still be in the cart.php?rq=r and not having to click on the tab again.
I'd appreciate any help. if you need any more information please let me know
Thank you in advance.
They are simply accessing the hash component of the url via location.hash. When the hash changes, they must have some logic that determines which part of the page to refresh.