Posting a sub-form with jQuery - php

I'll start off by saying I'm new to jQuery but I am really enjoying it. I'm also new to stackoverflow and really loving it!!
The problem:
I've created a sub-form with jQuery so that a user may add, then select this information from a dropdown list if it is not already available. I'm unable to POST this data with .ajax(), so that the user can continue to fill out other information on the main form without having to start over.
Sub-Form:
$(function() {
$("#add").live('click', function(event) {
$(this).addClass("selected").parent().append('<div class="messagepop"><p id="close"><img src="img/close.png"></p></img><form id="addgroup" method="POST" action="add_group.php"><p><label for="group">New Group Description:</label><input type="text" size="30" name="grouping" id="grouping" /></p><p><label for="asset_type">Asset Type:</label><select name="asset" id="asset" ><option>Building</option><option>Equipment</option></select></p><p><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></form><div id="result"></div></div>');
$(".messagepop").show()
$("#group").focus();
return false;
});
$("#close").live('click', function() {
$(".messagepop").hide();
$("#add").removeClass("selected");
return false;
});
});
And here is where I'm attempting to process it:
$(function () {
$('#addgroup').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
I've even attempted to create a simple alert instead of processing the information and this also does not work. Instead the form sumbits and refreshes the page as normal. Can anyone help me understand what I am missing or doing wrong? Thank you!
New attempt:
$("#add").live('click', function(event) {
var form = $("<form>").html("<input type='submit' value='Submit'/>").submit(function(){
$.post("add_group.php", {grouping: "Building, asset: "STUFF"});
$(".newgroup").append(form);
return false;
});
Final code
$(function() {
var id = 1
$("#add").live('click', function(event){
if($(".addgroup,").length == 0){
$("#test").append('<div class="addgroup"><label for="newGroup">New Group:</label><input type="text" class="newgroup" id="' + ++id + '" /><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></div>');
$("#add").attr("src","img/add_close.png");
}else{
$("#add").attr("src","img/add.png");
$(".addgroup").remove();}
return false;
});
});
$(function(){
$(".group_submit").live('click',function(event){
$.ajax({
type: "POST",
url: "add_group.php",
data: {new_group: $(".newgroup").val(), asset: $("#group option:selected").text()},
success: function(){}
});
$(".addgroup").remove();
$('#subgroup').load('group.php', {'asset': $("#group option:selected").text()});
return false;
});
});

If the form is submitting and refreshing as normal, the jquery isn't kicking in (the refresh means it's posting the form normally).
I for some reason (maybe others haven't) found that $(document).ready(function() { works much better than $(function() { ...
Also, the groups that you're adding should have a definitive id:
on #add click, count up a counter (form++) and add that to the id (#addGroup_+form) and then target that straight away in the function that added it:
$("#group").focus();
$("#addGroup_"+form).submit(function() {

try using .live()
$(function () {
$('#addgroup').live('submit',function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
and make sure addgroup has no duplicate id... you may use it as class if it has to be duplicated...

Related

jQuery toggle with different attributes and apply ajax

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');
}
});
}
});

Post variable before redirect?

I am currently building on a CMS. I want to send a page-id or site-id to the next page on redirect. I tried doing it using the jQuery POST function:
$(document).ready(function(){
$('.sender').on('click','a',function(){
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: { siteid:siteid },
success: function(response){
console.log('check');
},
error: function(){
console.log('error');
}
});
});
});
But because the request is sent at the same time as the redirect, it does not seems to work.
Because I am using the apache rewrite_engine to redirect stuff, I cannot use GET.
Apart from session_variables, what are my options?
I want to keep it safe, so I don't want much info to be visible/available!
To achieve this you need to wait for the AJAX request to complete before the page is redirected. Try this:
$(document).ready(function(){
$('.sender').on('click', 'a', function(e){
e.preventDefault(); // stop the default redirect
var url = $(this).attr('href');
var n = url.indexOf('#') + 1;
var siteid = url.substr(n, url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: {
siteid: siteid
},
success: function(response){
console.log('check');
window.location.assign(url); // redirect once the AJAX has successfully completed
},
error: function(){
console.log('error');
}
});
});
});
I'm not sure to clearly understand why you need but I think this can answer your problem.
If what you need is to transfert informations using a real POST method, just create an hidden form with method="POST" and fill it on click event.
<script type="text/javascript">
$(document).ready(function(){
$('.sender').on('click','a',function(event){
event.preventDefault();
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$('input[name="siteid"]').val(siteid);
$('#redirectForm').submit();
});
});
</script>
<form id="redirectForm" action="pages.php" method="POST">
<input type="hidden" name="siteid" value=""/>
</form>

Refreshing div without reloading not working

I'm "fighting" with this for hours now, I hope you could help me with the solution. So I've got a basic form with an empty div that will be then filled:
<form method='post' action='/shoutek.php'>
<input type='text' id='shout_tresc' name='shout_tresc' class='shout_tresc' />
<input type='submit' id='dodaj' value='Dodaj' />
</form>
<div class='shoutboxtresc' id='shout'></div>
<span class='loader'>Please wait...</span>
The shoutek.php contains the queries to do after submission of the form and functions to populate the div.
Here goes my jquery:
$(function() {
$(\"#dodaj\").click(function() {
// getting the values that user typed
var shout_tresc = $(\"#shout_tresc\").val();
// forming the queryString
var data = 'shout_tresc='+ shout_tresc;
// ajax call
$.ajax({
type: \"POST\",
url: \"shoutek.php\",
data: data,
success: function(html){ // this happen after we get result
$(\"#shout\").toggle(500, function(){
$('.loader').show();
$(this).html(html).toggle(500);
$(\"#shout_tresc\").val(\"\");
$('.loader').hide();
});
return false;
}
});
});
});
The problem in that is that it directs me to shoutek.php, so it does not refresh the div in ajax.
As you can see, I used return false; - i also tried the event.preventDefault(); function - it did not help. What is the problem and how to get rid of it? Will be glad if you could provide me with some solutions.
EDIT
Guys, what I came up with actually worked, but let me know if that's a correct solution and will not cause problems in the future. From the previous code (see Luceous' answer) i deleted
$(function() {
(and of course it's closing tags) and I completely got rid of the:
<form method='post' action='/shoutek.php'>
Leaving the input "formless". Please let me know if it is a good solution - it works after all.
$(function() {
$("#dodaj").click(function(e) {
// prevents form submission
e.preventDefault();
// getting the values that user typed
var shout_tresc = $("#shout_tresc").val();
// forming the queryString
var data = 'shout_tresc='+ shout_tresc;
// ajax call
$.ajax({
type: "POST",
url: "shoutek.php",
data: data,
success: function(html){ // this happen after we get result
$("#shout").toggle(500, function(){
$('.loader').show();
$(this).html(html).toggle(500);
$("#shout_tresc").val("");
$('.loader').hide();
});
return false;
}
});
});
});
For readability I removed your escapes. You've missed the preventDefault which prevents the form from being submitted.
You need to prevent the default action on submit button click:
$("#dodaj").click(function(event) {
event.preventDefault();
// your code
}

HTML : Enable Multiple Submission without refreshing

I want to enhance my tool's page where as soon use click a button. Request goes to server and depending upon return type (fail/pass) i change color of button. No Refresh/page reload
Page has multiple buttons : some what like below.
Name 9-11 - 11-2 2-5
Resource1 - Button - Button - Button
Resource2 - Button - Button - Button
Resource1 - Button - Button - Button
I am a c++ programmer so you might feel i asked a simple question
Here's a sample of jQuery Ajax posting a Form. Personally, I'm unfamiliar with PHP but Ajax is the same no matter what. You just need to post to something that can return Success = true or false. This POST happens asynchronously so you don't get a page refresh unless you do something specific in the success: section.
$("document").ready(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: yourUrlHere,
dataType: "json",
cache: false,
type: 'POST',
data: $(this).serialize(),
success: function (result) {
if(result.Success) {
// do nothing
}
}
});
}
return false;
});
});
Of course you don't have to be doing a POST either, it could be a GET
type: 'GET',
And if you don't need to pass any data just leave data: section out. But if you want to specify the data you can with data: { paramName: yourValue },
The cache: false, line can be left out if you want to cache the page. Seeing as how you aren't going to show any changes you can remove that line. jQuery appends a unique value to the Url so as to keep it from caching. Specifying type: "json", or whatever your specific type is, is always a good idea but not necessary.
Try using the $.post or $.get functions in jquery
$.post("url",$("#myform").serialize());
Adding a callback function as Fabrício Matté suggested
$.post("url",$("#myform").serialize(),function(data){alert(data);$("#myform").hide()//?Do something with the returned data here});
Here you go. You will find an example of a form, a button a the necessary ajax processing php page. Try it out and let us know how it goes:
<form action="" method="post" name="my_form" id="my_form">
<input type="submit" name="my_button" id="my_button" value="Submit">
</form>
<script type="text/javascript">
$("document").ready(function () {
$('#my_form').submit(function () {
$.ajax({
url: "ajaxpage.php",
dataType: "json",
type: "POST",
data: $(this).serialize(),
success: function (result)
{
//THere was an error
if(result.error)
{
//So apply 'red' color to button
$("#my_button").addClass('red');
}
else
{
//there was no error. So apply 'green' color
$("#my_button").addClass('green');
}
}
});
return false;
});
});
</script>
<?php
//ajaxpage.php
//Do your processing here
if ( $processed )
{
$error = false;
}
else
{
$error = true;
}
print json_encode(array('error' => $error));
die();
?>

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