I am new to json n php..
using code below to fetch data for radio button check box and text box with json . It is working fine but I donno how to populate data in select box in the same way .
function get_input_value(name, rval) {
//console.log(name + ' && ' + rval);
var i = 0;
var chk = $('input[name="' + name + '"]');
while (i < chk.length) {
//console.log($(chk[i]));
if ($(chk[i]).val() == rval) {
//console.log('loopvalue => ' + i);
$(chk[i]).prop('checked', true);
}
i++;
}
}
function loadJson (table, id) {
$.get("json-object.php", {'table': table, 'id':id}, function (data) {
console.log(data);
$.each(data, function (k, v) {
if ($('input[name="'+k+'"]').is('input[type="text"]')) {
$('input[name="'+k+'"]').val(v);
}
if ($('select[name="'+k+'"]').is('input[type="radio')) {
get_input_value(k,v);
}
if ($('input[name="'+k+'"]').is('input[type="checkbox"]')) {
get_input_value(k,v);
}
console.log(k+' ==> '+v);
});
}, 'json');
}
Your code is just setting value of text boxes and auto select certain checkboxes based on the PHP output.
To have it auto set the proper item in drop down lists as well you need to change this wrong code:
if ($('select[name="'+k+'"]').is('input[type="radio')) {
get_input_value(k,v);
}
To this:
$('select[name="'+k+'"]').val(v);
(No point to check type of <select> since it got none)
Related
I am trying to get all objects that are in a json string via $.getJSON and it works but I am having trouble showing them all (it only is showing the last object). I know its because its overwriting each entry via .$each but I've no clue on how to fix this, as I tried to append it but that just kept displaying each of the entries multiple times (I have it set to update every 5 seconds, to see if there are more entries available). Anyway, here is the code I have in place (both jQuery and PHP)
jQuery Code -
$(function() {
function buildOnlineFriendList() {
$.getJSON("/members/friends/get-friends-online")
.done(function(msg) {
if (jQuery.isEmptyObject(msg)) {
$('#friends-online').html("No friends are online.");
} else {
$.each(msg, function(key, value) {
// how to display each friend online without overwriting each one to only display the last. :/
$('#friends-online').html("" + value.name + "<br>");
});
}
}).fail(function(msg) {
$('#friends-online').html(msg.message);
});
}
setInterval(function() {
buildOnlineFriendList();
}, 5000);
buildOnlineFriendList();
});
PHP code -
public function getFriendsOnline()
{
$query = $this->connection->execute("SELECT members.username AS friend_username, friends_online.user_id AS fo_id FROM friends_online, friends, members
WHERE friends_online.user_id = friends.friend_id AND members.id = friends.friend_id AND friends.user_id = " . $this->getUserId()['id']);
if ($query->count() > 0) {
// get the id/username of the friend(s) online
foreach ($query as $values) {
$friends_online[] = array('id' => $values['fo_id'], 'name' => $values['friend_username']);
}
return $friends_online;
} else {
throw new FriendsException("No friends are online.");
}
}
Any help would be appreciated.
Thanks!
(I can try and provide more information if my question is unclear)
You already know it's overwriting the values when writing using $.each. The issue is it's writing the HTML for the friends-online element each loop. All you need to do is to set this value in a variable and update the variable in each iteration. Then after the loop is done, set the HTML for the element. I've modified your function to:
function buildOnlineFriendList() {
$.getJSON("/members/friends/get-friends-online")
.done(function(msg) {
// create a variable to hold the html string
var html = "";
if (jQuery.isEmptyObject(msg)) {
$('#friends-online').html("No friends are online.");
} else {
$.each(msg, function(key, value) {
// set the value of the html here
html += "" + value.name + "<br>";
});
// set the html here, after the loop.
$('#friends-online').html(html);
}
}).fail(function(msg) {
$('#friends-online').html(msg.message);
});
}
$("#friends-online")
.append(
$("<a>")
.attr("href", "/members/chat/" + value.id)
.attr("class", "chat-with")
)
.append($("<br>"));
Try replace this:
$('#friends-online').html("" + value.name + "<br>");
With this:
$('#friends-online').append("" + value.name + "<br>");
The .html() method will overwrite all existing HTML within the selected element.
The .append() method will add the content on to the end of the existing HTML
Try replacing $('#friends-online').html(... with $('#friends-online').append(.... At the moment this line is resetting the HTML of #friends-online over and over, whereas using append will add each new user to the element.
You will need to also add $('#friends-online').empty() as the first line of your timer, i.e.
setInterval(function() {
$('#friends-online').empty();
buildOnlineFriendList();
}, 5000);
Or in the function itself, i.e.
function buildOnlineFriendList() {
$('#friends-online').empty();
$.getJSON("/members/friends/get-friends-online") ...
I am trying to save tag in database table every time Html::DropDownList option is changed. On debug session it redirects me on ErrorHandler.php but no error is shown.
my jQuery:
var ddList = $('.dd-list');
var tagList = $('.tag-container');
ddList.on('change', function () {
var tagHolder = document.createElement('div');
tagHolder.setAttribute('class', 'tag-holder');
var selected = $('.dd-list option:selected').text();
tagHolder.setAttribute('id', selected);
if(tagList.find('div').length > 2){
alert('You can have most 3 tags!');
return false;
};
if(tagList.find('#'+selected).length){
return false;
}else{
tagHolder.append(selected);
tagList.append(tagHolder);
$.ajax({
method : 'GET',
dataType : 'text',
url : '../post/save-tag?tag=' + selected,
success : function (data) {
alert("Tag saved: " + data);
}
});
}
});
actionSaveTag :
public function actionSaveTag($tag)
{
return \Yii::$app->db->createCommand('INSERT INTO tags(tag_name)
VALUES (' . $tag . ')');
}
I tried also VALUES ($tag) without single quotes but same result.
How should i make it? Appreciating all advices!
I am trying to serialize value of form elements, where my combox is dynamicall added after user click.
I'm getting value from static combobox bt nt from dynamic combobox.
my code:
<script>
//submit data
$(function (a) {
$("form").submit(function (event) {
console.log($(this).serializeArray());
event.preventDefault();
});
});
// populate entree item to select menu
function populate() {
// only declare the variables once
var json = <?php echo $json; ?>, obj, option = ' ', i;
for (var i = 0; i < json.length; i++) {
obj = json[i];
option += '<option value="' + obj.id + '">' + $.trim(obj.title) + '</option>';
}
return option;
}
//add more select box when addmore click
$(function (b) {
var i = 0;
$("a#addmore").click(function () {
i++;
$("p#entree").append('<select name="entree' + i + '">' + populate() + '<select><br>');
});
});
</script>
i got the value when i put my form outside the table. I dnt know why table is blocking the process to get value.
My ajax call goes and enters a record into a database (it's the first part of a form recording data) so I need it to return the id from the database entry.
Problem is, it's firing twice, so it's making 2 database entries each time.
I tried using a $count and while($count>0) in my php code to make sure that wasn't looping - and I didn't think it was, so the problem lies in my jQuery.
I tried putting the preventDefault on my submit button click function and that didn't work either.
Here's my code:
$(document).ready(function(){
$('#wpgstep1').one('click',function(){
// validate form fields are all filled in
var budget=$('#budget').val();
if(budget=='')
{
$('#budgeterror').show();
}
var yellowpages=$('#ads-yellowpages').val();
var flyers=$('#ads-flyers').val();
var brochures=$('#ads-brochures').val();
var radiotv=$('#ads-radiotv').val();
var none=$('#ads-none').val();
var other=$('ads-other').val();
var otherstatement=$('ads-other-statement').val();
var cust_id=$('#cust_id').val();
if(other !='')
{
if(otherstatement==='')
{
$('#adsothererror').show();
}
}
else
{
otherin='0';
}
if(yellowpages==="on")
{
yellowpagesin='1';
}
else{
yellowpagesin='0';
}
if(flyers==="on")
{
flyersin='1';
}
else
{
flyersin='0';
}
if(brochures==="on")
{
brochuresin='1'
}
else
{
brochuresin='0';
}
if(radiotv==="on")
{
radiotvin='1';
}
else
{
radiotvin='0';
}
if(none==="on")
{
nonein='1'
}
else
{
nonein='0';
}
var dataString='cust_id=' + cust_id + '&step=1&budget=' + budget + '&yellowpages='+yellowpagesin + '&flyers=' + flyersin + '&brochures=' + brochuresin + '&radiotv='+ radiotvin + '&none='+ nonein + '&other=' + otherstatement;
$.ajax({
type: "POST",
url: "submitwpg.php",
data: dataString,
dataType:'json',
success: function(data)
{
alert(data);
var i="";
var p=eval (data);
for (i in p)
{
$('#wpgpart2').append('<input type=hidden name=wpgid value=' + p[i] + '>');
}
$('#wpgform1').hide();
$('#wpgform2').show();
}
});
return false;
});
});
Make a global var
var form_submitting = false;
Above your ajax call
if(form_submitting == false){
form_submitting = true;
//your ajax call
}
In your success function of your ajax call
form_submitting = false;
if your submit button is inside of a form, it may be possible that your ajax function is executing and then your form is posting regularly. You could try turning your
<input type='submit' />
into
<button type='button' onclick='validateAndAjaxFunction(); return false;'></button>
I am really confused how i managed these things.Please look at the attached image.See the right panel area.
Starting from first, package name is coming from last page; let's say page1.php. Now assume this attached image is page2.php.I am able to grab the selected checkbox values from left hand side and it is posting on right hand side.See i have checked the video checkbox.I have used jquery for that.
Problem 1 if i refresh the page values disappear except package value.I want the all checkbox value from right panel whatever user checked and post it to page3.php for further usage.I dont think jquery will do.I used the ajax post but cant able to grab values from below code.kindly help him regarding this.
Image link http://s7.postimage.org/3zbf1ucwb/image.jpg
function refreshPrices() {
var beg=<?php echo isset($beg) ? $beg : 0 ?>;
var inte=<?php echo isset($int) ? $int : 0 ?>;
var advn=<?php echo isset($adv) ? $adv : 0 ?>;
var currentTotalValue = 0;
currentTotalValue = currentTotalValue + beg + inte + advn;
$("#results div").each(function() {
if (!isNaN(parseInt($(this).find("span").text().substring(1)))) {
currentTotalValue += parseInt($(this).find("span").text().substring(1));
}
});
$("#totalValue").text("$" + currentTotalValue)
}
$(document).ready(function() {
$('#1').click(function() {
//var row = $(this);
if (($(this).attr('checked')) == 'checked') {
$('#result').append("-PDF Document <html><span style=float:right>$100</span></html>");
}
else {
$('#result').text("");
}
refreshPrices()
});
$('#2').click(function() {
if (($(this).attr('checked')) == 'checked') {
$('#result2').append("-Video <html><span style=float:right>$200</span></html> ");
}
else {
$('#result2').text("");
}
refreshPrices()
});
});
$(this).attr('checked') returns true or false, not 'checked', so you need to do :
if ( $(this).prop(':checked') ) { --- }
or just
if ( this.checked ) {
$('#result').append("-PDF Document <html><span style=float:right>$100</span></html>");
}
Also, you should'nt be using just a number as an ID, change it to #a1 etc. and you do realize that <html> tags are the start and end of the document, and appending them to an element inside the DOM does really seem like a great idea.