How to append json from php to a listview? - php

I loaded a json fuction from a php page and I append it to an UL, Which creates a list.When I delete a row, I reuse the same function to re-append the list; it works, but sometime I have to click twice before it removes theselected row.
Is there a way to simplify this process as i am new to jquery?
$(document).on('pageinit', '#two', function () {
var url="http://localhost/budget/items_list.php";
$.getJSON(url,function(result){
console.log(result);
$.each(result, function(i, field){
var budgeted_id=field.budgeted_id;
var name=field.name;
var budget_amount=field.budget_amount;
var trans_amount=field.trans_amount;
var balance=field.balance;
$("#listview").append('<li data-icon="delete">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
});
});
$(document).on("click",'.del',function(){
$("#listview").empty();
budgeted_id = (this.id);
$.post('delete_item.php',{postbudgeted_id:budgeted_id});
var url="http://localhost/budget/items_list.php";
$.getJSON(url,function(result){
console.log(result);
$.each(result, function(i, field){
var budgeted_id=field.budgeted_id;
var name=field.name;
var budget_amount=field.budget_amount;
var trans_amount=field.trans_amount;
var balance=field.balance;
$("#listview").append('<li data-icon="delete">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
})
})
});

IMHO, it isn't a bad idea to reuse the same function, you will be sure to get always the actual data you have on server-side.
From your description of the issue, I believe you just only need to chain the two ajax calls.
Here an example how to do that, adapted on the fly from jQuery documentation:
function createList(result){
$.each(result, function(i, field){
var budgeted_id=field.budgeted_id;
var name=field.name;
var budget_amount=field.budget_amount;
var trans_amount=field.trans_amount;
var balance=field.balance;
$("#listview").empty().append('<li data-icon="delete">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
});
}
function getListData(){
$.ajax({
url: "http://localhost/budget/items_list.php",
method: "GET",
dataType: "json",
success: function (result) {
createList(result);
}
});
}
$(document).on("pageinit", "#two", function () {
getListData();
});
$(document).on("click", ".del",function(){
var budgeted_id = (this.id);
var request = $.ajax({
url: "delete_item.php"
method: "POST",
data: {postbudgeted_id:budgeted_id}
});
var chained = request.then(function() {
getListData();
});
});
Please, note this is untested, but you got the idea. If there is an ajax error, your list will remain untouched, up to you to trap these errors and display in your web page a toaster notification.
If chaining the ajax calls won't work, maybe you should investigate your backend.

Related

jQuery Autocomplete doesn't work with custom object.

I'm sending an object from PHP that gets through perfectly, then I walk it with .each with jQuery, make a console.log and all seems fine, but when I assign the "com" object, it doesn't work...
Instead if I manually complete the com, by example, com=["dato1","dato2"], it works...
$(function() {
var URL= '../../controllers/region.controller.php';
var dataf= 'accion=getCom';
var com = new Array();
$.ajax({
url: URL,
type: 'POST',
data:dataf,
success:function(data){
var c = JSON.parse(data);
$.each(c, function(index, val) {
com.push(val.COM_NOM);
});
$( "#com_nom" ).autocomplete({source:com});
}
});
});

Unresponsive Fade-In Fade-Out in Jquery

I am implementing a twitter-style follow/unfollow functionality with the following jquery.
$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif" >');
$.ajax({
type: "POST",
url: "follow.php",
data: info,
success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#follow'+I).fadeOut(200).hide();
$('#remove'+I).fadeIn(200).show();
}
});
return false;
});
});
I have a similar unfollow function. However i have the following problem:
When I have N items {1,2..i.N} each with id = followi and I click on the follow button. I find that some of the items respond while others do not. I suspect it is a pure javascript issue...otherwise i figure none of the buttons would respond at all.
Is it a timing issue...all help is appreciated. Also i'd appreciate it if you could point me to a simpler method.
Thanks!
Well you are doing the UI update in your ajax success handler, so the reaction time for the UI updated is based on the speed of the Ajax response. And if the server doesn't return successfully, the UI update won't happen at all.
A simpler method with instant response:
$(function() {
$(document.body).delegate(".follow","click",function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif"/>');
$('#follow'+I).fadeOut(200); // act instantly since we assume it will go well
$('#remove'+I).fadeIn(200); // act instantly since we assume it will go well
$.ajax({
type: "POST",
url: "follow.php",
data: info,
complete: function(){ //always remove the loader no matter if it goes well or not
$("#loading").slideUp();
},
error: function() {
//handle error
$('#follow'+I).fadeIn(200); // correct mistake
$('#remove'+I).fadeOut(200); // correct mistake
}
});
return false;
});
});

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Event handler not wired after Ajax Update, new dom element (Internet Explorer)

Problem: New Inserted Dom elements aren't been wired correctly, function deletepost not firing. This happens only on IE and for new elements only added to DOM.
$(function(){
$('#postentry').submit(function() {
var tyu = $('#tittle_ent').val();
if(tyu.length <= 2)
{alert('Enter More Text!'); return false;}else
{
$.ajax({
type:'post',
url: '/posts_in.php',
dataType: "json",
data: $("#postentry").serialize(),
success:function(data){
var tittle = data[0];
var id= data[1];
$('<div></div>').attr('id','post'+id).addClass('boxee').html(tittle).prependTo('#boxer');
$('<img src="img/page-text-delete-icon.png" name="'+id+'">').attr({id:'postchk'+id,onclick: 'deletepost(this.name);'}).appendTo('#post'+id);
$('#tittle_ent').val('').focus();
}
});
return false;
}
});
});
Use jquery live
$(function(){
$("#boxer img").live("click", function(){
deletepost($(this).attr("name"));
});
$('#postentry').submit(function() {
var tyu = $('#tittle_ent').val();
if(tyu.length <= 2)
{alert('Enter More Text!'); return false;}else
{
$.ajax({
type:'post',
url: '/posts_in.php',
dataType: "json",
data: $("#postentry").serialize(),
success:function(data){
var tittle = data[0];
var id= data[1];
$('<div></div>').attr('id','post'+id).addClass('boxee').html(tittle).prependTo('#boxer');
$('<img src="img/page-text-delete-icon.png" name="'+id+'">').attr({id:'postchk'+id,onclick: 'deletepost(this.name);'}).appendTo('#post'+id);
$('#tittle_ent').val('').focus();
}
});
return false;
}
});
});
'onclick' is ancient/oldschool stuff, especially when using jquery. Try this variant instead:
$('<img src="img/page-text-delete-icon.png" name="'+id+'">')
.attr('id', 'postchk'+id)
.click(function () { deletepost(this.name); }) /// use .click() instead.
.appendTo('#post'+id);
Yeah , You must used jQuery live() function, the more detail example can be found here http://developerfaq.wordpress.com/2011/07/28/fire-event-on-dynamically-generated-dom-element-with-jquery/

jQuery Checkbox Submit

I'm looking to auto submit when a specific checkbox is checked.
I need it to pass to ajax.
Here is what I have so far:
$(document).ready(function () {
$("input[name=<?php echo("$newseo"); ?>]").click(function(){
var id=$(this).attr('id');
var favorite=$(this).val();
$.ajax({
type:'POST',
url:'check_favorite.php',
data:'id= ' + id + '&favorite='+favorite
});
}
});
});
But I just can't seem to get it to work,
Any help would be great, Thanks!
Here you go, this should do it. Your AJAX looks fine. I put together a JSFiddle to demonstrate.
$("input[name=TestCheck]:checked").live('click', function(e) {
var id=$(this).attr('id');
var favorite=$(this).val();
alert(id + " - " + favorite);
// Post here ...
$.ajax({
type:'POST',
url:'check_favorite.php',
data: {id: id, favorite: favorite}
});
});
JSFiddle : http://jsfiddle.net/4GQ6K/1/
I don't really like using obtrusive JavaScript and inputting PHP into JavaScript like that but there is no reason it shouldn't work.
$('#my_checkbox').change(function(){
if($(this).is(':checked'))
{
$('#my_form').submit();
}
});
Use your server side code[php] to set a id or a class to your specific checkbox. Then bind a click event to the given class name, e.g.
php code sets a class named .sCheckBx.
then on document.ready bind your event :
$(document).ready(function () {
$(".sCheckBx").click(function(){
var id=$(this).attr('id');
var favorite=$(this).val();
$.ajax({
type:'POST',
url:'check_favorite.php',
data:'id= ' + id + '&favorite='+favorite
});
}
});
});
Try this
$(document).ready(function () {
$("checkboxId").click(function(){
var $this = $(this);
if($this.is(":checked")){
var id=$this.attr('id');
var favorite=$this.val();
$.ajax({
type:'POST',
url:'check_favorite.php',
data:'id= ' + id + '&favorite='+favorite
});
}
}
});
});

Categories