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>
Related
I entered checkbox values into the database using the code below. When a user wants to view the checked boxes at a later time, how would I pull the data out of the database and re-check the checkboxes that were originally checked and submitted?
From the code below the data gets entered like this: DATA1|DATA2|DATA3|
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
checkbox_value += $(this).val() + "|";
}
});
Now how to I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
Here is how I'm getting other data and re-displaying it from normal input text boxes:
$.ajax({
url: 'ajax/example/example.php',
data: "findval="+carrier+"&column="+column,
dataType: 'json',
success: function(data)
{
var auto_id = data['id'];
var auto_name = data['name'];
var auto_address = data['address'];
var auto_trailer_types = data['trailer_types'];
$('#output_autocomplete_forms').html("<form id='example' class='form-horizontal'><input type='hidden' name='auto_id' id='auto_id' class='form-control' value="+auto_id+">......<div class='form-group'>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA1'>DATA1</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA2'>DATA2</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA3'>DATA3</label></div>
var auto_trailer_types = data['trailer_types'];
Now how do I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
So, I am guessing that the string stored in the database is something like 0|0|1|0, and you need to restore the checkboxes to that state.
As has been said, you can use AJAX for that. First, you need a trigger to launch the AJAX routine -- a button click, usually:
<button id="mybutt">Update Checkboxes</button>
Your AJAX routine will look something like this:
var rowID = $(this).closest('tr').attr('id');
alert(rowID); //this datum must allow you to identify the row in the database
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'id=' +rowID,
success: function(recd){
var arrCB = recd.split('|');
for (var n=0; n<arrCB.length; n++){
var z = n+1;
$('#cb'+ z).val( arrCB[n] );
}
}
});
another_php_file.php:
<?php
$id = $_POST['id'];
$pseudo_query = "SELECT `field_name` FROM `table_name` WHERE `id` = '$id' ";
echo $pseudo_query_result;
The pseudo_query_result that you echo should be your original 0|0|1|0. The PHP echo sends that datum back to the jQuery AJAX routine's success function. Important: the received data is not available outside that success function. You must do what you want with that data inside the success function, as shown in above example.
In above code, .split() was used to turn the 0|0|1|0 string into an array, and then we use a for loop (or even just manually code each checkbox update individually).
Use ajax to resolve this issue. But before try to encode your php query response in JSON
$.ajax({
url: "test.php" //Your request URI
}).done(function(data) {
//data (you can name it whatever you want) is the data that you get from your request.
//eg. if(data.checkbock){ //do something }
});
More informations here
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() = '';
});
});
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.
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
Im using Ajax to send values to a PHP script which writes some value to a database:
$.ajax({
type: "POST",
data: "action=vote_down&id="+$(this).attr("id"),
url: "vote.php",
success: function(msg) {
$("span#votes_count"+the_id).fadeOut();
$("span#votes_count"+the_id).html(msg);
$("span#votes_count"+the_id).fadeIn();
}
});
As you can probably tell from the action=vote_down the script is for a voting script.
Im already preventing the user from voting more than once by logging there vote against there username and ID in vote.php and if there username and ID is already in the DB against the same post then I dont add the vote to the DB.
I personally think that querying the database on each page load to check if the user has already voted could be quite intensive, there are many places to vote on a single page.
So instead i'll show the user the voting option, but when they vote I want to some how return a value from vote.php to say they have already voted.
Any ideas for the best approach to this?
Use JSON
If this is your file to show the voting form:
<div id='voteform-div'>
<form id='voteform'>
Your form elements and a submit button here.
</form>
</div>
Your JS code look like this:
jQuery('#voteform').live('submit',function(event) {
$.ajax({
url: 'vote.php',
type: 'POST',
data: "action=vote_down&id="+$(this).attr("id"),
dataType: 'json',
success: function( messages) {
for(var id in messages) {
jQuery('#' + id).html(messages[id]);
}
}
});
return false;
});
your vote.php should be something like this:
// Get data from $_POST array.
if( Already voted ) {
// It will replace the id='voteform-div' DIV with error message
$arr = array ( "voteform-div" => "you have already voted." );
} else {
// Store vote in database
// It will replace the id='voteform-div' DIV with confirmation message
$arr = array ( "voteform-div" => "Yor vote is submitted. Thanks" );
}
echo json_encode( $arr ); // encode array to json format
For more detail on this look at this question.
This should put you in the right direction...
http://forum.jquery.com/topic/jquery-ajax-and-php-variables
I would parse back a boolean false if they have posted already, or the id of the vote if they were successful (for styling / adding the html message).