One code to turn all forms into AJAX forms? - javascript

So I use the following code to manipulate my 'login' form so that it submits it, to the url of action="" and the data responded goes into id specified by target="". The submit method is specified by method=""
I like this. It's neat. But I was wondering if there was a way of having a script that meant that all forms were submitted through Jquery, without having to re-write this code for every form every time. That's just messy.
Much appreciated!
<script type="text/javascript">
$(document).ready(function(){
$("#login").submit(function(){
var thistarget = this.target;
$(thistarget).html('Submitting...');
jQuery.ajax({
data: $(this).serialize(),
url: this.action,
type: this.method,
error: function() {
$(thistarget).html("Form failed to submit");
},
success: function(results) {
$(thistarget).html(results);
}
})
return false;
}
);
});
</script>

Sure, just replace "#login" with "form". It will then affect all forms that currently exist on the page (but not future forms).
$("#login").submit(function(){...
For future forms AND current forms, you would need event delegation.
$(document).on("submit","form",function(){...

If I were you I'd use the $.post method of Jquery. http://api.jquery.com/jQuery.post/
But answering your question and as Kevin B said: change #login by form

Related

Pass data from one page to another using Javascript works but page doesn't load

I have a page where there's a table with a button and when I click the button I store the value in a JS variable in order to send it to another page using post.
I get the values on the other page but after that the page does not load.
this is the button code to send the variable:
<script>
function ObtenerDatosFila(oButton)
{
var dgvVerGrupos = document.getElementById('dtBasicExample');
$.ajax({
url: 'FormularioAMGrupo.php',
type: 'post',
data:
{
Modificar:'Modificar',
IDGrupo:dgvVerGrupos.rows[oButton.parentNode.parentNode.rowIndex].cells[0].innerHTML,
},
dataType: 'json',
success:function(){}
});
return false;
}
</script>
</script>
Is there another easier a way to do this other than using post method?
You could make a one page site, no need to send the data around.
You'll have to change your structure a bit and change your ajax functions to a generic 'ShowPage(id)' function to achieve this.
If you are interested and need any help just say so.
button's page:
<script>
function ObtenerDatosFila(oButton)
{
var dgvVerGrupos = document.getElementById('dtBasicExample');
localStorage.setItem("CodigoGrupo",dgvVerGrupos.rows[oButton.parentNode.parentNode.rowIndex].cells[0].innerHTML);
localStorage.setItem("Modificar",'Modificar');
location.href ="FormularioAMGrupo.php";
}
</script>
2nd page:
<script type="text/javascript">
window.onload = alert(localStorage.getItem("CodigoGrupo"));
</script>

AJAX call to run PHP script within JavaScript

I am trying to run a PHP script as soon as Submit button is clicked. I wanted to do an AJAX call as i dint want to refresh the page after the button is clicked. But the below code is not responding upon click.
I have saved the login.php in the same location as my project. Any help or input is appreciated!
<input type="button" class="button" value="submit" />
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$.ajax({
type: "GET",
url: "C:\wamp\www\ElitePass\login.php"
})
alert("done successully")
});
});
</script>
The issue is that you are not targeting your button correctly.
$("button") this selector is looking for an element of type "button". Naturally there is none. To target elements by their class names, append dot to selector:
$(".button").click(....)
Having said that, your code will still not work as you expect it to. Browser security restrictions will prevent loading of files directly from your file system. You need to load stuff via web server. Especially PHP files.
You can call success like :
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$.ajax({
type: "GET",
url: "C:\wamp\www\ElitePass\login.php",
success: function() {
alert("done successully");
}
})
});
});
</script>

how to run javascript code that included through ajax process

I have a php page which has lot's of code of html and javascript inside it.Ihe other page use ajax to send an id to the first page and get the results and put it inside a div element. Now I want to run those returned codes which contains javascript and html codes.
How should that be done?
This is my ajax request to the first page:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "showing.php",
data: "s_id="+s_id+"&submit=true",
success: function(msg){
str=$.trim(msg)
document.getElementById('tabs-2').innerHTML = str;
document.getElementById("ui-id-2").click();
}
})
I think event delegation can solve your problem.
Like below:
Use $.on(). Instead of registering events on the element you register on a parent which will not be removed
Ex:
$('#tabs-2').on('click', '#ui-id-2', function(){
//do something
})

Is it possible to update jquery tab set

I have a jquery tab set:
<div id="tabs">
<ul>
<li>Mileage Log</li>
<li>Trips</li>
</ul>
<div id="tabs-1">something</div>
<div-id="tabs-2">something</div>
</div>
My content on my tabs fires some javascript code that posts form data (I included that code). The problem is that I would like the tab element to refresh so any new content can be shown. Is there a built-in way to refresh the tabs using the "success:" option. I am currently using "location.reload();" but it just refreshes the whole page. Not ideal.
Thanks.
My Javascript
<script>
$(document).ready(function () {
//Submit form to add record.
$('#addmileage').submit(function (e)
{
e.preventDefault();
$.ajax({
data: $('#addmileage').serialize(),
type:'POST',
url:'actionpages/add_trip.cfm?ticketid=<cfoutput>#url.ticketid#</cfoutput>',
success: function(){
$('.success').fadeIn(200).show();
location.reload();
$('.error').fadeOut(200).hide();
}
});
});
$('.deleteMileageForm').submit(function (e)
{
e.preventDefault();
$.ajax({
data: $(this).serialize(), // **** modified this line ****
type:'POST',
url:'actionpages/delete_trip.cfm',
success: function () {
$('.successTab2').fadeIn(200).show();
location.reload();
$('.errorTab2', $row).fadeOut(200).hide();
}
});
});
});
</script>
The only way I think you could achieve this, is to have the server-side functions you're calling in AJAX, return a block of HTML which you could inject into the of the tab you want to reload. And if you're going to do that, you'll need to put the functions in a CFC instead of the CFM page you're calling now.
So, you would generate the way you're doing now to build the initial page, but save the generated HTML as a string and then return it to the jQuery AJAX call.
As just a really bare-bones example:
$('.deleteMileageForm').submit(function (e)
{
e.preventDefault();
$.ajax({
data: $(this).serialize(), // **** modified this line ****
type:'post',
dataType: 'json',
url:'actionpages/actions.cfc?method=deleteTrip&returnformat=json',
success: function (result) {
$('.successTab2').fadeIn(200).show();
$('.errorTab2', $row).fadeOut(200).hide();
$('#tab2').html(result);
}
});
Then on the server you'll need an actions.cfc with remotely accessible functions:
<component>
<cffunction name="deleteTrip" access="remote">
<cfset newHTML = "<h1>This is new HTML!</h1>">
<cfreturn newHTML>
</cffunction>
</component>
I've put everything into JSON format, just because I always use JSON. :)
Not sure how familiar you are with CFCs, returnformats, etc. But hopefully this is a push in the right direction.
You need to refresh the tabs in the success function using DOM Manipulation. It may be the case, that your scripts like actionpages/delete_trip.cfm have to return new information which you need to refresh the tabs (for example in the JSON format).
Some notes:
The function location.reload(); may reload the page from the browser cache. Use location.reload(true); if you do not want this behavior.
$('.successTab2').fadeIn(200) should be enough (.show() is not needed). You also do not need the .hide() function.

How to wait for form to load before applying form functions?

I have a checkout-button on my site wich dynamicly loads the form where the user can fill in his/her personal details.
The form has an id of #order. After the form is loaded it must call the .submit function from the jquery-form plugin.
When i first made this it did not work so i put my minimal debug skills to use (placing alert's, i know not the best method ;-)). Suddenly it worked when i put an alert between the loading of the form and the .submit call.
I figured it had something to do with the form not being completely loaded before calling the .submit. But after a quick search i found that the .html function is synchronous so any code
executed after the .html() call will definitely occur after the html
is set.
Can someone please help me with this problem?
$('.checkout').live('click', function(event) {
event.preventDefault();
$.get('/gva/templates/gva/form.html', function(data){
$('#blog').html(data);
});
alert('with this alert it works, without it doesn't');
var options = {
target: '#response',
beforeSubmit: validate,
success: showResponse
};
$('#order').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
$('.checkout').live('click', function(event) {
event.preventDefault();
$.get('/gva/templates/gva/form.html', function(data){
$('#blog').html(data);
var options = {
target: '#response',
beforeSubmit: validate,
success: showResponse
};
$('#order').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
});
The alert caused a delay which ensured the DOM had been updated by the time the next bits of your code fired. I've put them in the proper handler so that they fire at the proper time.

Categories

Resources