jQuery Autocomplete doesn't work with custom object. - php

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});
}
});
});

Related

How to append json from php to a listview?

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.

Use JS variables and serialize for AJAX request

I'd like to have the following code in my AJAX request:
function ajax_post( form_info ){
var request = $.ajax({
url: "ajax_handler.php",
type: "POST",
data: {data : form_info},
});
};
I'd like to serialize all of the elements in my clicked event to pass directly to the AJAX function because I'm doing processing on the PHP side. Say I have the following on click function:
$('.open-popup').on("click", function() {
var clicked_id = $(this).attr('id');
var contest_id = $('#contest-id').val();
var contest_type = $('#contest_type').val();
//serialize everything to a data_to_pass variable
ajax_post( data_to_pass );
});
How could I serialize the clicked_id, contest_id and contest_type into a single variable to pass to my AJAX processing function as a single string of data?
This is how you can do it:
var data_to_pass = {
clicked_id: clicked_id,
contest_id: contest_id,
contest_type: contest_type
}
JS:
$('.open-popup').on("click", function() {
var clicked_id = $(this).attr('id');
var contest_id = $('#contest-id').val();
var contest_type = $('#contest_type').val();
var data_to_pass = {
clicked_id: clicked_id,
contest_id: contest_id,
contest_type: contest_type
};
ajax_post( data_to_pass );
});
AJAX:
function ajax_post( form_info ){
var data = JSON.stringify(form_info);
var request = $.ajax({
url: "ajax_handler.php",
type: "POST",
data: {data : data},
});
};
You can create FormData for that and append all the required values with .append() function.
Like this,
$('.open-popup').on("click", function() {
var clicked_id = $(this).attr('id');
var contest_id = $('#contest-id').val();
var contest_type = $('#contest_type').val();
//serialize everything to a data_to_pass variable
var fd = new FormData();
fd.append( 'clicked_id', clicked_id);
fd.append( 'contest_id', contest_id);
fd.append( 'contest_type', contest_type);
ajax_post(fd);
});
And AJAX function would look something like this,
function ajax_post( form_data ){
var request = $.ajax({
url: "ajax_handler.php",
type: "POST",
data: form_data,
});
};
And access the data in PHP using $_POST['clicked_id'] and so on...
jQuery's ajax accepts objects as data; it takes care of the serialization for you. So you can simply do
ajax_post({
clicked_id:$(this).attr('id'),
contest_id:$('#contest-id').val(),
contest_type: $('#contest_type').val()
});
If you want to do so, try using a form element and inputs (it can be hidden fields if it isn't a user submitted form) in your HTML code, and serialize it, so you can transmit the whole 'block of information' at one time with Ajax.
Look at rfunduk's answer at this question.

jQuery, ajax multiple checkboxes into $_POST array

I'm trying to send $_POST data to another page to add sessions for a simple shopping cart.
I have a multiple forms within a PHP while loop each with multiple checkboxes, everything works apart from the checkboxes.
My question is how do I change this piece of code to change "item_extras" into an array?
if(this.checked) item_extras = $(this).val();
I have tried the following but, this just creates one line with all the values instead of another row within the array. If this is too confusing I could create a sample if it helps.
if(this.checked) item_extras += $(this).val();
$('form[id^="add_item_form"]').on('submit', function(){
//alert("On Click Works");
event.preventDefault();
addItem($(this));
});
function addItem(ele) {
//alert("I'm in the addItem Function");
var item_id = ele.parent().parent().find("input[name=item_id]").val(); // get item id
var item_name = ele.parent().parent().find("input[name=item_name]").val(); // get item name
var item_options = ele.parent().parent().find('#options').val(); // get selected option
var item_extras = "";
$item_extras = ele.parent().parent().find('input[name^="extra"]'); // find all extras
$item_extras.each(function() {
if(this.checked) item_extras = $(this).val(); // how do i make this into an array???
});
alert("BEFORE AJAX");
var dataString = 'item_id=' + item_id + '&item_name=' + item_name + '&item_options=' + item_options + '&item_extras[]=' + item_extras;
alert(dataString);
$.ajax({
type: "POST",
cache: false,
url: "includes/cart.php",
data: dataString,
success: function () {
$.ajax({
url: 'includes/cart.php',
success: function(data) {
$('#cart').html(data);
alert("AJAX SUCCESS");
}
});
}
});
return false;
}
you can use serialize method. Form.serialize()
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
var data = $(this).serialize();
});

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/

Using PHP instead of JSON in jQuery instant search script

I have a Google Instant style search script written in jQuery which pulls results from the JSON BingAPI. How can I make my script pull content from a PHP script rather than the BingAPI?
Here is my code:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var keyword=encodeURIComponent(search);
var yt_url='http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&Appid=642636B8B26344A69F5FA5C22A629A163752DC6B&query='+keyword+'&sources=web';
window.location.hash=keyword;
$.ajax({
type:"GET",
url:yt_url,
dataType:"jsonp",
success:function(response){
$("#result").html('');
if(response.SearchResponse.Web.Results.length){
$.each(response.SearchResponse.Web.Results, function(i,data){
var title=data.Title;
var dis=data.Description;
var url=data.Url;
var final="<div class='webresult'><div class='title'><a href='"+url+"'>"+title+"</a></div><div class='desc'>"+dis+"</div><div class='url'>"+url+"</div></div>";
$("#result").append(final);
});
}
}
});
});
});
Replace this:
var yt_url='http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&Appid=642636B8B26344A69F5FA5C22A629A163752DC6B&query='+keyword+'&sources=web';
With your json suggest url
var yt_url='http://yourwebsite/json.php?query='+keyword;

Categories