How to use checkbox value asdata parameter in ajax - javascript

I need to reload a page when clicking in a submit button. What the new page should show depends on the checkboxes selected previously to the reloading.
My problem is that, when I click "submit", $("button").click(function()... takes the correct values but $(document).ready(function ()... takes always the values true (which are selected as default).
How can I save those values before the reloading so that I can use them on $(document).ready(function ()...? Can I send them as data parameter
$(document).ready(function() {
var selectedCheckboxes = new Array();
$.ajax({
url: 'getNewForm.php?accion=value1',
data: 'selectedCheckboxes',
dataType: 'json',
error: function() {
alert("ERROR");
},
success: function(res) {
//Do something
}
}
});
$("button").click(function() {
var selectedCheckboxes = new Array();
selectedCheckboxes[0] = document.getElementById("checkbox1").checked;
selectedCheckboxes[1] = document.getElementById("checkbox1").checked;
});
});
Note: I did var selectedCheckboxes twice trying to get different results, donĀ“t know where I should do it.

You have several problems here:
You have a syntax error in your code sample. Make sure the code you post to StackOverflow compiles and runs without syntax errors (assuming you're not asking why a particular code snippet is generating syntax errors :) ).
The data attribute of your AJAX request is incorrectly specified as the literal string 'selectedCheckboxes', which means that your browser will send the literal string "selectedCheckboxes" as the payload to your server.
In addition, as you correctly surmise, you don't correctly handle the initialization of selectedCheckboxes. Variables initialized with var in JS are scoped to the containing function, which means the selectedCheckboxes declaration inside your click() handler are never going to be seen outside it.
Also, you're getting the value of "checkbox1" twice; you probably want to get something named "checkbox2" or similar. Related: If you are just serializing the only inputs in the form, use jquery's serialize() method so you have less code.
If you're really reloading the entire page anyway, don't use an AJAX request to do it? Using AJAX for form submissions is common when you do not want to reload the entire page (see below), but for your stated use case, it adds complexity you don't need. Just have a simple form with checkboxes and a submit button, and let the browser do it's default action.
Here's an example of using AJAX to submit a form behind the scenes, without reloading the entire page:
http://jsfiddle.net/Palpatim/rLeGv/
Given the HTML:
<form id="checkboxForm">
<input type="checkbox" name="check" value="check1" checked="checked" id="ch1"/>
<label for="ch1">check1</label>
<br/>
<input type="checkbox" name="check" value="check2" checked="checked" id="ch2" />
<label for="ch2">check2</label>
<br/>
<button>Click me</button>
</form>
This JS will submit a form when the button is clicked:
$(document).ready(function() {
$("button").click(function() {
$.ajax({
url: 'getNewForm.php?accion=value1',
data: $('#checkboxForm').serialize(),
dataType: 'json',
error: function() {
alert("ERROR");
},
success: function(res) {
alert("SUCCESS");
}
});
});
});
As far as loading a new page with the previous selections, you will have to maintain the state somehow. Your options include passing the state back from the server, storing the selections in the browser's local storage, or a cookie. I'd suggest passing the state back from the server, but your use case is a bit unclear.

Related

How to prevent repeatative submit while using ajax or javascript?

I have a controller in c# and inside the controller there is a save method. The save method saves/updates data that is submitted by submit button click and javascript. The problem is, if you click on the button multiple time, it should only process the very first click and rest of them should be identified as duplicate submit and should be discarded by controller. How to do this in c# mvc web application?
Disable the button after it's clicked. So it can just be clicked once.
Simple way
when button clicked disabled it then actived again after you got response result from ajax! u can also add loader that make ur web look so cool!
<button id="btnSend" onClick="send()">submit</button>
<script>
btnSend=document.getElementById("btnSend");
function send(){
btnSend.disabled=true;
//set disabled button here
$.ajax({ type: "GET",
url: "http://www.google.de",
async: false,
success : function(text)
{
btnSend.disabled=false;
//set active to button
// add your code here
},
fail : function(text)
{
btnSend.disabled=false;
//set active to button
// add your code here
}
});
}
</script>
I would also disable the button on the client side. But you could also check if the submitted data is different from the stored data. If no changes were made you could just return without further saving logic.
Should it be possible to just save the data once? Maybe a redirect to a different view after saving could be a possible solution in special cases.

ajax records in a selector

I do not really know what terminology to call this but its just that am stock with my school assignment. This is what I want to do
I have a code like this
<information user_number_random="12345678" />. Now I want to periodically/dynamically change the user_number_random values by making ajax call to php file eg. user.php each time page is being refreshed.
<?php
$u_id=rand(0000,9999);
echo $u_id;
?>
below is my ajax call
<script>
$(document).ready(function(){
$('#btn').click(function(){
$.ajax({
type : 'POST',
url : 'user.php',
data : $(this).serialize(),
success : function(data)
{
$("#record").html(data);
}
});
});
});
</script>
below is how am trying to get the ajax record values passed to user_number_random but its not showing anything. can someone help me fix that. Thanks
<information user_number_random="record" />
Possible solution:
<information user_number_random="record" />
<script>
$(function() {
$('#btn').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'user.php',
success: function(data) {
$("information").attr("user_number_random", data);
}
});
});
});
</script>
Explanation:
$('#btn').click(function(e) {
e.preventDefault();
The click event passes in an "event object" to to event handler function, which we receive as e. Normally, when you click on a link, the browser loads the URL provided in the href attribute of the link, or simply reloads the page if an empty href is given. To prevent this default action, we call e.preventDefault on the event object. This way the page won't reload when you click the link.
I removed the data: $(this).serialize() property from your AJAX call, because you don't seem to need it in this case. You can use the data property to pass custom data attributes in the POST request to user.php. Any parameters you pass in there are made available in the $_POST array in your PHP code. Since you don't access $_POST in this case, you don't need to pass in any data attributes. And besides, $(this).serialize() only works when submitting forms, which is not the case here.
$("information").attr("user_number_random", data);
Since the HTML element you want to change is an <information> element, the jQuery selector needed to be adjusted accordingly. To set an attribute on an element, you can use element.attr("attribute_name", "new_value").

How to stay on same position after submitting an html form?

I have a simple html form:
<form action="addToCart" method="post"><br><br>
<input name="productId"
value="${product.id}" type="hidden"> <input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>"
type="submit">
</form>
Every time I click on "submit", it brings me straight back to top which creates a poor user experience because the user would have to scroll back down where he was browsing the products... Can I do this without using a script?
-Every time I click on "submit", it brings me straight back to top.
Yes that is what default functionality when submitting forms, it always repaints the dom so it causes a jump and page's top position is rendered.
-which creates a poor user experience because the user would have to scroll back down where he was browsing the products
To make a good user experience you can use ajax for this functionality, as you tagged jQuery in your question then you can try with jquery ajax:
$('form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"text",
success:function(data){
alert(data); // you can alert the success message.
},
error:function(err){
console.log(err);
}
});
});
I have used a dataType:"text", just assuming if you are going to echo "Added in the cart."; kind of message from the php.
Ajax is your best bet if you want to achieve what you want
$('.submit').on('click',function(event){
event.preventDefault(); //this is important else page will get submitted
$.ajax({
url:'where you want to process data',
dataType:'html',
data: your form data as json or whatever type
success: function(result){
//here you can update any thing on the frontside
}
});
});
Since you're using onclick attribute on your button, you have to change type attribute from submit to button. That way you can get your addedCart() method to fire. Then handle form submission inside that method (if your submit handler isn't already there).
<input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>" type="button">
Script:
function addedCart(){
// ... your method on click
// $.ajax({...});
};
If you're not using jQuery, you can handle form submission with XMLHttpRequest :
How to make an AJAX call without jQuery?

form needs to be submitted twice before sending updated data

so basic outline...
I have 'posts' pulled from the database and displayed like so:
<div class="blogtest">
<form action="process/updatepost.php" class="updatepost" method="post">
<input type="button" class='.$editenabled.' value="Edit">
<input type="submit" class="saveupdatebutton" value="Save">
<input type="hidden" class="postid" name="postid" value="'.$postID.'">
<div class="text">
<div class="buildtext">'.$text.'</div>
<div class="editor"><textarea name="ckeditor"id="ckeditor" class="ckeditor">'.$text.'</textarea></div>
</div>
</form>
</div>
Once the edit button is clicked, the buildtext class hides and the ckeditor is shown. Same for the edit and save button.
When save is clicked, a ajax call is made and then the data is updated. This works perfectly fine... however it only works perfectly fine if there is only 1 blog post on that page.
Here is the ajax for reference:
$(document).ready(function(){
$(".updatepost").submit(function(){
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var $ckEditor = $targetForm.find('.ckeditor'),
blogpost = $ckEditor.val();
// Validation
if (blogpost == '') {
check = false;
$ckEditor.after('<div class="error">Text Is Required</div>');
}
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$targetForm.find(".error").remove();
else
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});
So, if there is 2 blog posts on the page and i edit the 2nd (last) post, on clicking save the post is updated correctly.
However if i edit any other then it takes two submits for the data to be sent.
I checked on firebug and it shows that on the first click, the old value is sent, and then on the 2nd the new one.
Where am i going wrong?
Eventually (once working) the post will be refreshed on the success of the ajax call but for now its obviously vital that the user only has to click save once.
Thanks for any help! Any more code needed and ill post it here.
Craig :)
EDIT: After making ckeditor just a normal textarea it works fine. Must be ckeditor not updating as i know it doesnt litrally work as a textarea as such. Maybe ill have to use another rich editor...
I had a similar problem. Just to share my experience in case anyone ends up here with the same issue. The CKEditor wasn't updating the target textarea on the first click on the submit button and since I had data validation on the text area thankfully made me aware that the textarea wasn't being populated on the first submit. To overcome this I add this bit of code:
$('#accept-button').click(function (event) {
for (var i in CKEDITOR.instances) {
CKEDITOR.instances[i].updateElement();
}
}
As far as I can see from the integration guide, CKEditor most probably uses its own onsubmit event to actually send data back to the textarea. This would mean that those 2 events might fire up reversed order, first retrieving the old text from your code and only then updating the textarea.
You can always try and retrieve CKEditor's content using the following syntax:
var editor_data = CKEDITOR.instances.yourInstance.getData();
Also, are you using the jQuery adapter with CKEditor?
EDIT: the problem seems to be having same IDs on multiple textareas, all being called "ckeditor". This would result in unexpected behaviour across browsers, since ID must be always unique to a page.

database query via javascript & servlet

I am trying to do a simple query for info from a database through an html page. I've got all the backend stuff working fine, but I'm having trouble on the client side. I currently have a form where the user submits their ID# to get some info on their case.
But with my current setup, it returns an entirely new page and I just want to read in a text string, process it and update the content on the current html page without opening up a new one and replacing the old one. How can this be done?
Here's my code so far:
function showInfo() { } // I want to make the request here instead
<form name="register" action="http://localhost:8080/testapp/authenticate" method="get">
<p><label for="badge">ID #:</label>
<input id="badge" name="ID" type="text" pattern="[0-9]{6}"
placeholder="xxxxxx">
<button id="checkButton" type="submit" onClick="showInfo()">Enter</button>
</p>
</form>
My guess is that you're actually submitting the form, which is posting back to the server. What you will want to do is cancel the form from submitting and submit it using AJAX (which is what I believe you want?).
To do so, your showInfo() function should do one of these three things (I can never remember which one)
return false;
cancel the event, something like e.preventDefault()
stop the propagation, something like e.stopPropagation()
Once you've successfully prevented the form from hard-submitting, you can then do what you'd like by submitting your data via AJAX and manipulating your response however you'd like.
1st - Jason is absolutely right that what you want for this situation is AJAX, below is an example in motion.
2nd - You should be using a Javascript library such as jQuery, which might look intimidating (as it did for me at first), but it is really easy and completely worth the small effort to get it going.
3rd - With jQuery, your application tidbits should look something like this, using the example you provided:
HTML -
<p>
<label for="badge">ID #:</label>
<input id="badge" name="ID" type="text" pattern="[0-9]{6}"
placeholder="xxxxxx">
// Please note that I removed the onClick section from the line below.
<button id="checkButton" type="button">Enter</button>
</p>
JQUERY -
// The default function you described to take information and display it.
function showInfo(data) {
// Insert your function here, probably using JSON as the Content Type
}
// This is the key AJAX function, using jQuery, that takes your info and gets a
// response from the server side, the sends it to the function above in order for it
// to be displayed on the page.
function processIdInfoCheck() {
$.ajax({
type: 'post',
url: '/http://localhost:8080/testapp/authenticate',
data: {
'id': $('#badge').val();
},
dataType: 'json',
success: displayIdInfoReturn,
error: function () {
alert("There was an error processing your request, please try again");
}
});
}
// When the page loads, the code below will trigger, and bind your button click
// with the action you want, namely triggering the AJAX function above
(function ($) {
$('#checkButton').bind('click', processIdInfoCheck);
})(jQuery);
Just remember, AJAX takes some effort to get the desired effect, but when you look at page load times, request numbers, etc... It is totally worth it. Please let me know if this was helpful and if you need any specifics.

Categories

Resources