Checking change in form field before executing AJAX - php

I have a form on my view page.. whenever form populate on the page ..it is filled with old values ... I mean input box and check-box have old values ... and then I am posting form through ajax..after posting if values successfully saved into database I am showing the message that information updated successfully or vice versa...so the problem is now that if for example user do not change anything,the form values are same in the text-boxes then when user pressed save button i don't want to show him that information has updated as he didn't do anything .. I want to ask if that possible in java script ...or should i have to query into the database and check that whether values are same or not? and the other thing that if it can be possible that button remains disable until he do some changes in any of the form field...
I am not writing the whole code just the javascript part
$("#submit").click(function(e){
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password-check').val();
var oldpassword = $('#oldpassword').val();
var timezone = $('#UserinfoTimezone').val();
var alternate_email = $('#alternate_email').val();
//var newsletter = $('#newsletter').val();
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
password: $('#password-check').val(),
oldpassword: $('#oldpassword').val(),
timezone: $('#UserinfoTimezone').val(),
alternate_email: $('#alternate_email').val(),
};
$.ajax({
type:"POST",
data:form_data,
url:"https:/localhost/settings/",
success : function(data) {
alert("successfully data saved"):
}
});

You can save the values while you would have populated the fields in the form... Otherwise you can use a flag variable which can be given a value in .change() function of each field and that value can be checked on submit of the form.. But I guess the first option will be more efficient as the flag will be set even if the user edits the field and enters the same value again...

You can save the old values in the JavaScript and compare them against the current values in the submit handler. If nothing changed, don't POST.
And yes, you can also have the save button disabled initially and attach onChange handlers to the form fields that enable the save button when the contents of those fields change.

On ajax submit copy input values to some attribute, so you know last sent data.
$('#form input').each(function() {
$(this).data('last-ajax-value', $(this).val());
});
When invoking second ajax submit you can check if these values match and make some decision.
var someValueDiffers = false;
$('#form input').each(function() {
if($(this).data('last-ajax-value') != $(this).val())
someValueDiffers = true;
});
if(someValueDiffers)
// Form changed
else
// Form is the same

On the page load you can get all the input element values and hold them in seperate global variables. When you submit the form check the current input values with old one that you have saved. If any one is not equal, user has changed the form and you can submit it.
var init_name = "";
var submit_flag = false;
$(document).ready( function () {
var init_name = $('#name').val();
$("#submit").click(function(e){
var name = $('#name').val();
if(name == init_name) {
// user has not changed
submit_flag = false;
} else {
submit_flag = true;
}
if(submit_flag) {
// call the ajax
}
})
})

One simple way to achieve that. Diseable the submit button. Eneable it if a change is made on the page.

After submit the ajax values you need to clear the input field values.
Place this code instead of your success:
...
success: function(data){
alert("successfully data saved"):
$('#myformid').find('input:text, input:password, input:file, select, textarea').val('');
$('#myformid').find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}

You can unset the input values when page gets loaded.
$(document).ready(function(){
$("input").each(function(){
$(this).val() = '';
});
});

Related

PHP/MySQL How to send result back to form?

So I got this form which lets the user enter up to 10 item IDs and then check for the status or apply changes right away. If the user clicks check status the item IDs will be sent to another PHP.
What is the easiest way to send the result back to the form and display it in the red area?
if ($_POST['action'] == 'Check Status/Shelf') {
$itemids = "$itemID1, $itemID2, $itemID3, $itemID4, $itemID5, $itemID6, $itemID7, $itemID8, $itemID9, $itemID10";
while ($row = mysql_fetch_array($all)) {
$hyllplacering = $row['Hyllplacering'] . "";
$all = mysql_query("SELECT Hyllplacering, itemID FROM booking WHERE itemID IN ('$itemids')");
}
}
If you don't want to use Ajax, then save the details into a $_SESSION[] and upon submission the form is posted and then the details can be populated into SESSION and displayed back out to the form upon reloading, but it's a bit of a fiddle for not much return.
And use MySqli or PDO.
For that you have to use ajax
Give id to Apply Changes & Check Status/Self button
<script type="text/javascript">
$(document).ready(function(){
$('#apply').click(function() {
var id1 = $('#id1').val();
var id2 = $('#id2').val();
//same for all your 10 field
var cstring = "id1="+id1+"&id2="+id2 // etc;
$.ajax({
type: "POST",
url: "your file url to do database opration & fetch detail back to here",
data: cstring,
cache: false,
success: function(result) {
$('.resultdata').html(result)
}
});
});
});
</script>
<div class="resultdata"></div>

Submit value of a checkbox via jquery/ajax to php and insert into db

I tried to find help via the search function on here but all the answers given to similar problems were too elaborate for me to understand, i.e. the example code was too complex for me to extract the parts which could have been relevant for my problem :(
I have a html form which sends userinput on a specific row in a datatable via an ajax-request to a php file, where the input gets inserted into my sqldb.
I have no problem sending the textinput entered by a user and also transferring additional infos like the specific row they were on, or the network account of the user. But i now want to add a checkbox, so the users can choose whether their comment is private or public. However i somehow cannot transmit the value from the checkbox, there is no error but also no checkboxdata inserted into the db.
Do i have to handle checkboxes differently than textareas? I'd be very grateful for help!
My code looks as follows:
Html:
function insertTextarea() {
var boardInfo = $( "<form id='boardComment'><textarea rows='2' cols='30'>Notizen? Fragen? Kommentare?</textarea>Privat:<input type='checkbox' name='privatcheckbox' value='private'><input type='submit' value='Submit'><input type='reset' value='Cancel'></form>");
$( this ).parent().append(boardInfo);
$("tbody img").hide();
$("#boardComment").on( "submit", function( event ) {
event.preventDefault();
var change_id = {};
change_id['id'] = $(this).parent().attr("id");
change_id['comment'] = $(this).find("textarea").val();
change_id['privatecheckbox'] = $(this).find("checkbox").val();
if( $(this).find("textarea").val() ) {
$.ajax({
type: "POST",
url: "boardinfo.php",
cache: false,
data: change_id,
success: function( response2 ) {
alert("Your comment has been saved!");
$("tbody img").show();
$("#" + change_id['id']).find("form").remove();
}
});
};
});
and this is the php part:
$id = mysql_real_escape_string($_POST['id']);
$comment = mysql_real_escape_string($_POST['comment']);
$privatecheckbox = mysql_real_escape_string($_POST['privatecheckbox']);
$sql="INSERT INTO cerberus_board_info (BOARD_INFO_COMMENTS, BOARD_INFO_USER, BOARD_INFO_CHANGE_ID, BOARD_INFO_ENTRY_CHANNEL, BOARD_INFO_PRIVACY_LEVEL) VALUES ('$comment', '$ldapdata', '$id', 'Portal', '$privatecheckbox')";
The following line:
change_id['privatecheckbox'] = $(this).find("checkbox").val();
Searches for a element with the tagname checkbox. Such an element doesn't exist, I believe you are trying to search for an <input> element with a type of checkbox.
The following should work for you:
change_id['privatecheckbox'] = $(this).find("input[type=checkbox]").val();
Or even better, the :checkbox pseudo selector:
change_id['privatecheckbox'] = $(this).find(":checkbox").val();
On a final note: Why shouldn't I use mysql_* functions in PHP?

form submitting in jquery tab

I started using jquery and jquery-ui. I am facing a problem trying to submit a form that is inside a tab. Once i hit 'submit', the page refresh itself, the tabs are gone, and the url is changed to the tab's function url. the submit button is working, and i get the desired result. However, it is not on the same page as the tabs.
Does anyone have any idea on how to keep the page from refreshing?
example of my problem:
I have a page called 'index.php' with 3 different tabs. one of the tabs is called 'submit form' where there I have a form using POST method, it is taking its source from 'form.php'. once i hit the 'submit' button, the page refreshes, the url changes from 'www.example.com' to 'www.example.com/form.php', i get the result there, but the page is "plain", means that its not under a tab, just a normal page.
I hope I explained myself correctly.
Thanks!
EDIT:
here is my submission code:
$submit = $_POST['submit'];
$name= $_POST['name'];
if($submit){
echo 'submitted <br><br>';
echo "hello $name";
}
Capture the form submission in jQuery and then stop it with preventDefault();
$(function(){
$('#formID').on('submit', function(e){
e.preventDefault();
var formSrc = $(this).attr('action');
var formMethod = $(this).attr('method');
var formData = $(this).serialize();
$.ajax({
url: formSrc,
type: formMethod,
data: formData,
success: function(data){
//work with returned data from requested file
alert(data);
}
});
});
});
EDIT:
i should add that I chose to use on(); as opposed to the default submit(). This is because the form may or may not be available at DOM.ready.
In answer to your 2nd question: "what if I wanned to run this information returned through a php code in the same tab, how could I do that?"
Have your php script return values as JSON like:
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
echo json_encode($row);
Then you can have javascript do whatever you wish with the returned values, such as -
$.ajax({
url: 'sc_getData.php?id=' + ID,
type:'GET'
})
.done(function(myData) { // data = array returned from ajax
myData = JSON.parse(myData);
for (var i in tFields){
thisSourceField = sFields[i];
thisTargetField = tFields[i];
targetID = '#' + thisTargetField;
thisValue = myData[thisSourceField];
$(targetID).val( thisValue );
console.log(targetID + ': ' + thisValue);
}
})
I've setup arrays for Target and Source Fields. The source field arrays match the field names returned by the php script while the target field arrays will match the form field id's to be filled with the returned values.

jQuery get values from selected checkboxes

First problem is that I do not know how to get the values of SPECIFC checkboxes when they are checked.
I need a function that will get the value of the selected checkboxes by checkbox ID or Name.
This is the code I have so far:
$("#doStatus").click(function(){
var Tuitting = $('textarea#tuitting').val();
var F = $('input#Fb').val(); //checkboxes with ID Fb
var T = $('input#Tw').val(); //checkboxes with ID Tw
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", { tuitting: Tuitting, f: F, t: T });
window.setTimeout('location.reload()', 1000);
return false;
});
Now the second problem is that both var F and var T may contain MORE than one values in an array..
Obviously when I use the ajax get functions the multiple values for both var F and var T are not
passed at all. What is the problem..?
How do I pass multiple values in an array that will be then runed by the foreach on the doStatusBox.php page?
Please help me.
$("#doStatus").click(function() {
var Tuitting = $('textarea#tuitting').val();
var F = $('input[name="fb"] :selected').val();
//You can give the name of checkbox and get the values of selected checkbox
return false;
});
I'm answering based on an assumption: you need checked checkboxes to pass them via GET method to your doStatusBox.php script.
However, why would you go trough the trouble of finding which checkbox is checked if you can simply use the serialize() method and let jQuery do the job for you?
$("#doStatus").click(function()
{
var serialized = $("#someFormHere").serialize()
// or, if you have your form elements within a div or another element
var serialized = $("#elementID :input").serialize();
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", serialized);
window.setTimeout('location.reload()', 1000);
return false;
});
However, is "#doStatus" a submit button submitting the form or something else? If it submits the form, bind the submit event to the form, not click event to the button submitting it.

How to pass dynamic id text box value to another page without refreshing with jquery and php

$('.btncomment').click(function () {
var id = $(this).attr('id');
$.post('SaveTopicInformation.php', {
tid: commentform.(topic_ + id).value,
topicdetail: commentform.(topicdetail_ + id).value,
userid: commentform.(user_ + id).value
});
});
I have to pass the 3 text box value to another page. First of all, I display the all the record from database. then, I have comment link for each row. I like to give comment and save the comment for eache record. I use by jquery and php. please help me out. I can't finger out how to pass dynamic text box's value by bynamic name.
You cannot access object fields like that. You need to use the array subscript syntax:
$.post('SaveTopicInformation.php', {
tid: commentform['topic_' + id].value,
topicdetail: commentform['topicdetail_' + id].value,
userid: commentform['user_' + id].value
});
Actually, since you are using jQuery, using .val() on a jQuery object wrapping the form element would be much nicer.
Try this code sample. What it does is listen for your submit button to be pressed, then it grabs all of the content from a certain form, and submits it to a server:
//Listen for the submit button to be clicked
$('.btncomment').click(function () {
$.ajax({
'url' : 'SaveTopicInformation.php', //Processor URL
'type' : 'POST', //Send as POST-data
'data' : $('.myForm').serialize(); //Send the entire form
'success' : function(data) { //What to do when the form is submitted
if (data == 'success') {
alert('Form submitted!');
}
}
});
});
Hope that helps,
spryno724

Categories