This is a follow up to a previous question. I am using the jQuery Validation plugin on the UI Acordion. After successful validation on the client and server side, the next accordion should open. I am using AJAX because I would like to add the submitted values above the accordion as each step of the form is completed. If I use $.ajaxSubmit, the PHP appears to work properly, but the next accordion does not open as it should. If I use $.ajax, everything works properly on the jQuery side (the first accordion closes and the next one opens), but the PHP does not appear to communicate properly with the client.
Any ideas on what I'm doing wrong?
[Note: I have edited the above post for clarification]
$(document).ready(function(){
$("#applicant-form").validate({
errorPlacement: function(error,element) {
return true;
},
rules: {
"firstName": {
required: true,
minlength: 1
}
},
submitHandler: function(form) {
$.ajax({
error: function() {alert("doh!");},
success: function(e) {
var acc = $("#accordion"),
index = acc.accordion('option','active'),
total = acc.children('div').length,
nxt = index + 1;
acc.accordion('activate', nxt);
}
});
return false;
}
});
$f <--- form object
$acc <-- accordion object
if($f->isSubmitted()){
$f->update();
$acc->js()->accordion('activate',next)->execute();
}
Please show some demo of the validation examples of JQuery PHP forms ...
There
In Agile Toolkit would be something like this
$f <--- form object
$acc <-- accordion object
if($f->isSubmitted()){
$f->update();
$acc->js()->accordion('activate',next)->execute();
}
Related
I have an application that I'm writing that, in one aspect of it, you click on a checkmark to complete a task, a popup window is displayed (using bootstrap), you enter your hours, and then that is sent to a PHP page to update the database. I'm using FF (firebug) to view the post. It's coming up red but not giving me an error. The only thing I'm doing is echoing out "sup" on the PHP page, and it's still showing errors, and I can't figure out why.
This is my initial click function:
$('.complete').on('click', function(event) {
var id = $(this).attr('data-id');
var tr = $(this).parent().parent();
var span = $(tr).children('td.task-name');
var r = (confirm('Are you sure you want to complete this task?'));
if (r){
addHours(id);
} else {
return false;
} // end else
});
That works fine, and it fires my next function which actually fires the bootstrap modal:
function addHours(id) {
var url = 'load/hours.php?id='+id;
$.get(url, function(data) {
$('<div class="modal hide fade in" id="completeTask">' + data + '</div>').modal()
.on('shown', function() {
pendingTask(id);
}); // end callback
}).success(function() {
$('input:text:visible:first').focus();
});
} // end function
This is also working, and the modal is displayed just fine. However, whenever I post the form to my logic page, it fails for no reason. This is the function to post the form to the logic page:
function pendingTask(id) {
$('.addHours').on('click', function(event) {
var formData = $('form#CompleteTask').serializeObject();
$.ajax({
url:'logic/complete-with-hours.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
if (data.status == 'error') {
$(this).attr('checked', false);
//location.reload();
} // end if
else {
$(this).attr('checked', true);
//location.reload();
} // end else
},
dataType: 'json'
});
}); // end click
} // end function
When this is fired, I see this in my Firebug console:
I know this is a lot of information, but I wanted to provide as much information as I could. Every other post function in the application is working fine. It's just this one. Any help would be appreciated.
Thanks in advance.
The jQuery.ajax data parameter takes a simple object of key value pairs. The problem could be that the object created by serializeObject() is too complex. If that's the case, you could either process the formData object to simplify it or try data: JSON.stringify(formData)
Does serializeObject() even exist in jQuery? is that a function you wrote yourself? Can you use jQuery functions like serialize() or serializeArray() to serialize the form data and see how it goes.
Usually the red indicates a 404 response error. We can't tell in this screen shot. Check your php code by directly calling the requested page and getting a proper response.
Also make sure your dataType is application/json which is the proper mime type header (though I don't think this is causing the error). You also should only have dataType once (you have it again at the bottom)
I figured it out. I changed the post type from the structure I entered above to a standard post:
$("#CompleteTask").validate({
submitHandler: function(form) {
var hours = $('#hours').val();
$.post('logic/complete-with-hours.php', {'hours': hours, 'id':id},
function(data){
if (data.status == 'success') {
$(checkmark).attr('checked', false);
$('.message').html(data.message).addClass('success').show();
} // end if
if (data.status == 'error') {
$('.message').html(data.message).addClass('error').show();
} // end else
},
"json"
); //end POST
} // end submit handler
}); // end validate
That seemed to do the trick
I am using some ajax to call a php file that returns some html (an image and couple of buttons) and then place the contents of this into a div. The trouble is that I want to be able to use the id of one of the buttons that is returned from the php to hook up an event handler. The output of the source if I do view source in browser simply shows the div that the html is injected into and not the html:
<div class="displaysomething"></div>
My AJAX is as follows:
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
}
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
}
});
};
PHP - Ultimately returns a button amongst other stuff. This is what I need to hook up to the event handler, based on its id.
echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>';
If I simply put a button on the page without injecting it using AJAX into the div my button hookup code works great.
Does anybody have any ideas?
Thanks
In jQuery, the .click(... method of adding an event handler will only add the event to existing elements. New elements added later are no included.
You can use the jQuery on method of event binding to include elements added later.
$("body").on("click", "#stop-service", function(e){
e.preventDefault();
runHDIMService();
});
I have created a simple example on JSFiddle.
The problem is that
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e) // this doesn't exists yet
{
e.preventDefault();
runHDIMService();
});
This should work:
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
// so after you attached the div from ajax call just register your event
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
});
};
I am useing modal window of native joomla codes. I am displaying a form wihchi is used to send mail from one user to another. The php,css and js codes are in tmpl file (by using JDocument) of view and js is like that;
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#sendMail").click(function(){
if(document.formvalidator.isValid(this.form)){
$j("#mailSending").css("display","inline-block");
$j.ajax({
type: \'POST\',
url: \'index.php?option=mycomponent&tmpl=component&view=members\',
data: $j("form#mailForm").serialize(),
success: function(data,xhr,status){
$j("#mailSending").css("display","none");
$j("#mailMsg").css("display","inline-block");
setTimeout(function(){window.parent.SqueezeBox.close()},1000);
alert(status);
}
});
}else{
$j("#mailMsg").text("'.JText::_('OFFER_EMPTY_FIELDS').'").css("display","inline-block").delay(1000).fadeOut("slow");
}
});
});';
I am tracing the xhr with firebug when I triger the click function to loading icon is shown and task within the controller file is executed. Php file ends like that;
$send =& $mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ' . $send->getMessage();
} else {
echo 'Mail sent';
}
exit();
While the php function process ends the content within the modal window is changes with Mail Sent. But I want to hide the loading .gif and show a message. But the code don't do that. Any idea ?
Code to send a form with ajax and insert its returned values into a div
jQuery(function($) {
$("form[name='srchForm']").submit(function(){
$.get($(this).action, $(this).serialize() + "&tmpl=component&limitstart=0", function(data){
$m =$('#main');
$m.html(data).delay(10);
});
return false;
});
});
It is funny I love Ricardo's use of jquery instead of this "$j(document).ready(function(){})" but the point is I figured that the button which is used to trigger the ajax is not to set a type of button it has button tag but doesn't have attribute. I think it tries both ajax and normal submit process and it conficts.
Thanks for your helps and sorry for my stupit mistake.
I am working with AJAX with prototype and PHP. It is working for me but I need some small changes. Following is my running code for AJAX request:
JS/Prototype:
function ajaxRequest(url) {
new Ajax.Request( url, {
method: 'get',
onSuccess: function( transport ) {
// get json response
var json = transport.responseText.evalJSON( true );
alert(json);
},
onFailure: function() {
alert('Error with AJAX request.');
}
});
return false;
}
HTML:
<a href='javascript:ajaxRequest("/testajax/ajaxresponse");'>Testing AJAX</a>
Question:
Now I want to change my link like this:
<a href='/testajax/ajaxresponse' class='AjaxLink'>Testing AJAX</a>
So prototype function should capture click event of class='AjaxLink' links and then get href part of clicked link and proceed. How can I change my above prototype function for such kind of links.
Thanks
If you have Prototype 1.7 then this way is available:
document.on('click', 'a.AjaxLink', ajaxRequest.curry('/testajax/ajaxresponse'));
Otherwise you'll have to rely on good old Event.observe:
$$('a.AjaxLink').invoke('observe', 'click',
ajaxRequest.curry('/testajax/ajaxresponse'));
Just re-read the question and I see you want to use the href attribute. Jan Pfiefer was very close.
document.on('click', 'a.AjaxLink', function(event, element) {
return ajaxRequest(element.href);
});
This wont work. Why do you want such a link? If a link is specified in this way any click on it will follow its href and change location of actual document. Only way to prevent such a behavior then is by adding onclick again or in $(document).ready bind onclick handler, and manualy cancel the event.
UPDATE
However to bind onclick event on all links with AjaxLink class,execute request and cancel the event:
$(document).ready(function(){
$('.AjaxLink').click(
function(e){
ajaxRequest(this.href);
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
);
});
This will work:
$$('a.AjaxLink').each(function(element) {
element.observe('click', function(e) {
var element = e.element()
Event.stop(e)
alert(element.href)
});
})
I have form with Tinymce. I am saving text writen in tinyMce using ajax call.
when I press the save button it does not save the latest value which i entered in tinymce.
i.e. when i load the page, default value in the field is "aaaa". I update it to "bbb" and press the save button. but it saved the value "aaaa". Now I change the value from "bbb" to "ccc" and press the save button now it save the previous value "bbb" not "ccc". so it is keep saving the one step old value. I don't know why?
Here is the saveAction which I am calling on Save button using ajax
public function saveAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
var_dump ($_REQUEST);
if($this->getRequest()->isPost())
{
$data=$this->_getParam('content');
var_dump($_REQUEST); // var dump shows the old value each time i press the save button
}
here is my form
here is ajax script
$('#frm').submit(function() {
var options = {
target: '#response',
beforeSubmit: showRequest,
success: showResponse,
url: '/admin/index/save'
};
$(this).ajaxSubmit(options);
return false;
});
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
}
function showResponse(responseText, statusText, xhr, $form) {
}
Try to do the following on button click before you anything else:
tinymce.activeEditor.save();
This will set the actual editor content to the textarea in the background.
Hi i searched alot about this then from tiny mce site i found this onkeyup event that can be added in the script code in head.
// Adds an observer to the onKeyUp event using tinyMCE.init
tinyMCE.init({
...
setup : function(ed) {
ed.onKeyUp.add(function(ed, e) {
console.debug('Key up event: ' + e.keyCode);
});
}
});
I replaced some parts like below
tinyMCE.init({
...
setup : function(ed) {
ed.onKeyUp.add(function(ed) {
tinymce.activeEditor.save();
});
}
});
so now whenever i change something in any tinymce textarea on my page the current text is saved and ajax get the current value.
I got my problem solved.
I am just a starter in ajax and JavaScript having a desire to achieve perfection.
I hope this helps others as well :)
Just remember me in your prayers.
Happy coding :)
tinyMCE.activeEditor.save();
(caps letters for MCE)