jQuery toggle with different attributes and apply ajax - php

I am using this jQuery plugin for making toggle, but I have an issue that when I make multiple toggles that have same ids and class so in that case I am not able to identify particular toggle for applying auto load ajax on changing value.
I would to ask that how I make same toggle with this same plugin but different ids or class or name so I make ajax function like when I click toggle it will update in PHP without submitting submit button.
The plugin I am using is this one
The code I am using is this:
HTML
<p>Default: <span class="easyswitch"></span></p>
<p>Checked: <span class="easyswitch" data-default="1"></span></p>
SCRIPT
<script>
$('.easyswitch').easyswitch();
</script>
AJAX
$('MY_CLASS_NAME').change(function(){
var mode= $(this).prop('checked');
$.ajax({
type:'POST',
dataType:'JSON',
url:'test.php',
data:'mode='+mode,
success:function(data)
{
$("body").html('Operation Saved');
}
});

You can not handle easyswitch's change event. you need to create click event of it, and from it you can get the status of current toggle.
$('.easyswitch').easyswitch();
$('.easyswitch').click(function () {
var mode = $(this).hasClass('on');
toogleStatus(mode);
});
// for all controlls.
$(".easyswitch").each(function() {
var mode = $(this).hasClass('on');
toogleStatus(mode);
});
function toogleStatus(mode)
{
if (!mode) {
alert('checked')
}
else {
alert('unchecked')
}
}

Try using callback option
$('.easyswitch').easyswitch({
callback: function(val, ele) {
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'test.php',
data: { mode: val },
success: function(data) {
$("body").html('Operation Saved');
}
});
}
});

Related

function loads only on change, i would it to load on document load

My knowledge of this is very limited, but I figured that the problem that I have is in this function. What it does is that it displays some options to be selected in an item post. From what I see it only loads when a category is changed. Because of that when you edit this post, this function will not display unless you change category to another one and then revert back to the one you want. I would like it to display every time, except for those categories that are in the if statement.
Please assist....
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function(){
if($(optgroups).children("option:selected").length){
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function(data) {
if(data) {
$("#condition-container").html(data);
}
}
});
}
});
});
You just need to trigger your change event on document load. So under you on change function put this code
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function () {
if ($(optgroups).children("option:selected").length) {
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function (data) {
if (data) {
$("#condition-container").html(data);
}
}
});
}
});
});
//Trigger change
$(document).ready(function () {
$("#catId").trigger("change");
});
hi I assume you want the function fired on document load and on change, but for that you will need to use 2 triggers.
1) you allready have the on change trigger
2) use the $(document).ready() (https://learn.jquery.com/using-jquery-core/document-ready/) wrapper for onload.
There is possibly a much more gracefull solution, but I'm no JS expert so this will only get you to a working, although not the pretiest state

AJAX Load PHP Response

How can I load data from my PHP response via ajax into a panel?
My PHP outputs correctly and I can see a table in the response, but I can;t get it to build the data on my webpage.
Here is my jquery/ajax so far. It passed the value to PHP correctly and PHP builds the table via its echo, but what am I missing for AJAX to display the table?
PHP:
<?php
foreach ($lines as $value) {
echo "<input name='data[]' value='$value'><br/>";
}
?>
JQUERY:
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
$('#panel').load(result);
}
})
return false;
});
});
The answer to this was two fold.
I was attempting to append to my main div, which apparently can't happen. I created a new empty div and was able to load the results there.
Beyond that, the comments to change .load(results) to .html(results) were needed.
The correct jquery code is below.
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
console.log(result);
$('#test').html(result);
}
})
return false;
});
});
move your function from:
$.ajax({...,success: function(){...}});
to
$.ajax({..}).done(function(){...});
if it doesn't work, try to add async:false into the ajax object...
$.ajax({...,async:false}).done(function(){...});
Hope it helps... =}

Issue with using a value in JQuery/Javascript

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

Get only part of the message and reload only one div

this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');

How to request page content by clicking a div with jQuery mobile?

I am trying to fetch data form a callback page (php) and load it into a html div with jQuery mobile. This should happen if a user clicks on another div.
What I actually got is
$.('#home-button').bind('vclick', function( e ) {
$.get('homeCallback.php',function(data){
$('#displayContent').append(data).trigger('create');
},'html');
});
Where #home-button is the div that should trigger the event and #displayContent the div where the content should be put in.
The request should be able to pass some parameters, too. Like homeCallback.php?param=1 but it could also use the post method.
The callback does not have to be html only, it could also be possible that the callback php script provides JSON data or anything.
I am not a JS crack so I have problems solving this issue. Thanks for your help!
Edit:
So I found a solution on my own:
$(document).ready(function() {
$.ajaxSetup ({
cache: false
});
var ajaxLoader = '<img src="images/ajax-loader.gif" alt="loading.." />';
var loadUrl = "homeCallback.php";
$('#home-button1').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option1',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
$('#home-button2').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option2',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
});
And this is what homeCallback.php simply does..
<?php
if( isset($_GET["option1"] ))
echo "option1";
if( isset($_GET["option2"] ))
echo "option2";
So far.
$.('#home-button').bind('click', function() {
$.ajax({
url: "homeCallback.php",
type: "POST",
data: ({param: 1, param2: 2}),
success: function(html){
$("#displayContent").html(html);
}
});
});

Categories