ajax form submission - ajax

I am using a cakephp form. I have a dropdown select box. If dropdown value changes then the form should submit.Is there any method similar to form submission like this.form.submit for ajax forms. Any help?

If jquery is okay for you you can do
$('#myDropdown').change(function() {
$(this).closest('form').submit();
});
if you want ajax replace line 2 as follows
var myForm = $(this).closest('form');
$.post(myForm.attr('action'), myForm.serialize(), function(data)
{
/*do something on success*/
}

If you use jQuery you could use the .serialize() method and AJAXify a form like this:
$(function() {
$('#myform').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
// TODO: process the results
}
});
return false;
});
});
Another possibility is to use the excellent jQuery form plugin.

You can use dropdown elemnts onChange event
Example
$('.target').change(function() {
alert('Handler for .change() called.');
});

Related

Ajax function call not working second time

Need help to resolve ajax call issue
In my view page ( working on codeigniter), there is a dropdown and a div
section. Based on dropdown value, data will get change in div section. I am
using ajax call ( to call method in controller) to upload data in div tag on
dropdown change event. Ajax call working fine on first change event of
dropdown but when i select value for second time in dropdown, ajax function
call is not working ( second select and so on).
My code is:
VIEW PAGE =>
$(document).ready(function() {
$("body").on('change','#assettype_id',function(e){ // "assettype_id" is
dropdown id
//e.preventDefault();
var categoryval = $('#assettype_id :selected').val();
$.ajax({
type: 'POST',
cache: false,
url: 'http://my_path/index.php/assetcontroller/assignpc/'+ categoryval, // Based on "categoryval" data will change in div tag
dataType: 'html',
success: function(data) {
$( "#result" ).load( "http://my_path/index.php/assetcontroller/assignpc/"+ categoryval); // "result" is div tag id
$( "#result" ).html(categoryval);
},
});
return false;
});
});
Why ajax call is not working in dropdown 'second time' change event?
You need to wrap the .on('change') event into a function, so it can be called anytime later.
That's because once you have added new html output through Ajax, this html doesn't yet know about your change event!
So the function my_change_event() needs to be re-called, once your Ajax output has been added to DOM with your $( "#result" ).load()
something like this:
$(document).ready(function() {
my_change_event();
});
function my_change_event(){
$( "#assettype_id" ).on( "change", function() {
$.ajax({
type: 'POST',
cache: false,
url: your_url,
success: function(data) {
// do something with data
// html output
my_change_event();
}
});
}

Check Form Before Submit Use Ajax Django

I use Ajax to send data from form to server. But I want to check data in form before Submit by Ajax:
<form id='#id_form' onsubmit='return checkInputSubmit();' >
...
</form>
In Ajax:
$('#id_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: $('#id_form').serialize(), // serializes the form's elements.
success: function(data) {
if(data.result == true) {
//My code
}
else {
//My code
}
}
});
});
But checkInputSubmit() can't prevent submit from Ajax. You can explain for me and give me solution to check data in form before Submit by Ajax.
Thanks.
in the $('#id_form').submit(function(e) event, you can check/edit/return... any thing you want before call Ajax. Within Ajax, i think it won't work and don't good. (we just check ajax result, not input)
#Blurp, I found the solution by use your help.
$('#id_form').validate({
submitHandler: function(form) {
e.preventDefault();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: $('#id_form').serialize(), // serializes the form's elements.
success: function(data) {
if(data.result == true) {
//My code
}
else {
//My code
}
}
});
}
});

AJAX avoid repeated code

I'm using Symfony2.1 with Doctrine2.1
I'd like to use AJAX for many features on my site , editing a title , rate an article , create an entity on the fly , etc.
My question is simple :
Do I need to create a JQuery function for each functionnality , like this :
$('#specific-functionality').bind('click', function(e){
var element = $(this);
e.preventDefault();
// the call
$.ajax({
url: element.attr('href'),
cache: false,
dataType: 'json',
success: function(data){
// some custom stuff : remove a loader , show some value, change some css
}
});
});
It sounds very heavy to me, so I was wondering if there's any framework on JS side, or a specific method I can use to avoid this. I was thinking about regrouping items by type of response (html_content , boolean, integer) but maybe something already exists to handle it nicely !
From what I understand, you are asking for lighter version of JQuery ajax method. There are direct get/post methods instead of using ajax.
$.get(element.attr('href'), {'id': '123'},
function(data) {
alert(data);
}
);
To configure error function
$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
var msg = jQuery.parseJSON(XMLHttpRequest.responseText);
alert(msg.Message);
});
Also, you can pass callback function to do any synchronous operations like
function LoadData(cb)
{
$.get(element.attr('href'), { 'test': test }, cb);
}
And call
LoadData(function(data) {
alert(data);
otherstatements;
});
For progress bar, you use JQuery ajaxStart and ajaxStop functions instead of manually hiding and showing it. Note, it gets fired for every JQuery AJAX operation on the page.
$('#progress')
.ajaxStart(function () {
//disable the submit button
$(this).show();
})
.ajaxStop(function () {
//enable the button
$(this).hide();
});
Instead of $('#specific-functionality').bind('click', function(e){, try this:
$(".ajax").click(function(){
var url = $(this).attr("href") ;
var target = $(this).attr("data-target") ;
if (target=="undefined"){
alert("You forgot the target");
return false ;
}
$.ajax(....
And in html
<a class="ajax" href="..." data-target="#some_id">click here </a>
I think it is the simplest solution. If you want some link to work via ajax, just give it class "ajax" and put data-target to where it should output results. All custom stuff could be placed in these data-something properties.

can you do a jquery mobile popup on ajax response event?

Was hoping to use the popup and I am pretty sure I am trying to use it incorrectly. Any ideas on how this should work? Can you use the popup in this manner?
<script>
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
function onError(data, status)
{
data = $.trim(data);
//$("#notification").text(data);
$("#notification").popup(data); }
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#callAjaxForm").serialize();
$.ajax({
type: "POST",
url: "sendmsg.php",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
I'm assuming you are trying to use the JQM popup widget, first your missing the closing } from your onError function. Second to use the popup widget you can first set the data
$("#myPopupContent").text(data)
Then to display you use the open method
$("#myPopup").popup("open")

Updating a dropdown via knockout and ajax

I am trying to update a dropdown using knockout and data retrieved via an ajax call. The ajax call is triggered by clicking on a refresh link.
The dropdown is successfully populated when the page is first rendered. However, clicking refresh results in clearing the dropdown instead of repopulating with new data.
Html:
<select data-bind="options: pages, optionsText: 'Name', optionsCaption: 'Select a page...'"></select>
<a id="refreshpage">Refresh</a>
Script:
var initialData = "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]";
var viewModel = {
pages : ko.mapping.fromJS(initialData)
};
ko.applyBindings(viewModel);
$('#refreshpage').click(function() {
$.ajax({
url: "#Url.Action("GetPageList", "FbWizard")",
type: "GET",
dataType: "json",
contentType: "application/json charset=utf-8",
processData: false,
success: function(data) {
if (data.Success) {
ko.mapping.updateFromJS(data.Data);
} else {
displayErrors(form, data.Errors);
}
}
});
});
Data from ajax call:
{
"Success": true,
"Data": "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]"
}
What am I doing wrong?
The problem you have is that you are not telling the mapping plugin what to target. How is it suppose to know that the data you are passing is supposed to be mapped to the pages collection.
Here is a simplified version of your code that tells the mapping what target.
BTW The initialData and ajax result were the same so you wouldn't have noticed a change if it had worked.
http://jsfiddle.net/madcapnmckay/gkLgZ/
var initialData = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}];
var json = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"}];
var viewModel = function() {
var self = this;
this.pages = ko.mapping.fromJS(initialData);
this.refresh = function () {
ko.mapping.fromJS(json, self.pages);
};
};
ko.applyBindings(new viewModel());
I removed the jquery click binding. Is there any reason you need to use a jquery click bind instead of a Knockout binding? It's not recommended to mix the two if possible, it dilutes the separation of concerns that KO is so good at enforcing.
Hope this helps.

Resources