form submitting in jquery tab - php

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.

Related

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?

Checking change in form field before executing AJAX

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

ajax $_POST data then redirect to new page

I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.

Fetching id from database of submitted data

So I am submitting data to the database. Each data sent contains an id that is auto incremented. With ajax or PHP (I am very much new to this, and trying to learn I'm sure it's ajax along with some php) I need to fetch the id of the data that was submitted.
The idea is, after the form is submitted, the user gets the link back to the submitted page. Example:
Quote was submitted! [link] Click to go to the link or go back.
The link will look like this: http://example.com/quote-192
I pretty much have everything else set, I just don't know how I'll get the id and add it to the link.
Here is the PHP that processes the form:
require('inc/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
//echo $quotes . "Added to database";
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
Oh, and the data is being sent with ajax:
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
var like = $('.quote-wrap span iframe');
$('.inner').prepend('<div class="quote-wrap group">' + like + '<div class="quote"><p>' + quoteVal+ '</p></div></div>');
// console.log("success");
});
return false;
});
So how would I get the id for each quote and add it to the page after the form has been submitted?
In you php:
echo mysql_insert_id($result)
Then in your jquery ajax:
$.ajax({
type:'post',
url:'url.php',
data:querystring,
success:function(data){
var id = parseInt(data);
}
]);
this will return the inserted ID as an integer value that you can work with in javascript
Have the PHP print the ID as a response to the request:
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
// Print the id of last insert as a response
echo mysql_insert_id();
jQuery, test code to alert what was echoed by the PHP as a test
// add data as a param to the function to have access to the PHP response
$.post("add.php", $(this).serialize(), function(data) {
alert(data);
});
With this php-function. You can call after inserting.
int mysql_insert_id ([ resource $Verbindungs-Kennung ] )
mysql_insert_id

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