I'm developing a webpage that creates a form with a number of select tags dynamically by means of some javascript/jquery code. When submitting the form a php file (form_submit.php) must process the submitted form fields. Furthermore I use Netbeans 7.4 for php debugging.
My problem: when I select some values in the form and submit the form the debugger shows empty submitted values (e.g., default values "NOSELECTION" for no selection) within form_submit.php instead of the selected values. The console within the submit function in the code below does show the selected submitted values (and therefore also confirms that the built html form with the select tags is correct).
I do not assume this a is a bug in Netbeans, so where do I go wrong? I suspect there is a bug in the jquery submit function below, but I cant's see it...
Javascript code:
//main function document ready
$(document).ready(function(){
//only part of code here to build the form with a number of <select>'s
ecorp_eproductoptions = '<select id="selected_eproductid'+ff+'" class="eprodtype" name="selected_eproductid'+ff+'">';
ff++;
ecorp_eproductoptions += '<option selected="selected" value="NOSELECTION" > Koppel uw product </option>';
for(var k=0; k< Staticvars.ecorp_nrofeproducts;k++){
ecorp_eproductoptions += '<option value="'+ Staticvars.suppliername[i] +'_'+Staticvars.agreementid[i] +'_'+ supplier_eproductid +'_'+ Staticvars.ecorp_eproductid[k] +'"> '+ Staticvars.ecorp_eproductname[k] +' </option>';
}//for var k
ecorp_eproductoptions += '</select>';
form += '<td> '+ ecorp_eproductoptions +' </td></tr>';
//etc...
//FUNCTION Submit()
$("#myForm").submit(function(){
console.log('SUBMITTED FORM: '+ $( this ).serialize() ); //shows values for select tags!
$.ajax({
type: "POST",
url: "form_submit.php",
data: $("#myForm").serialize(),
dataType: "json",
success: function(msg){
if(msg.statusgeneral == 'success'){
}
else
{
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
return false;
});//$("#myForm").submit()
}); //$(document).ready
HTML code:
<form id="myForm" name="myForm" action="" method="post">
<div id="wrapper"></div> <!--anchor point for adding set of product form fields -->
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
<input type="submit" name="submitForm" value="Bevestig">
</form>
I'm new to jQuery too, but I think the problem is the fact that your $.ajax call is running asynchronously which allows the submit event handler to continue on and return false before your form sends the values...just a newbie guess. :)
Have you tried adding async: false to your $.ajax call?
i dont know why happens that, but please try this
$("#myForm").submit(function(){
var dataAjax = $( this ).serialize();
console.log('SUBMITTED FORM: '+ dataAjax ); //shows values for select tags!
$.ajax({
type: "POST",
url: "form_submit.php",
data: dataAjax,
dataType: "json",
success: function(msg){
if(msg.statusgeneral == 'success'){
}
else
{
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
return false;
});//$("#myForm").submit()
Related
I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,
`
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>`
Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/
use the name of the inputs as key of $_POST array to get their values.
if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; }
if(isset($_POST['notes'])) { $notes = $_POST['notes']; }
You should send your data after form submitted, something like this
:
$(".comment_form form").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
you can assign event after insert your form.
// handling with the promise
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
// your ajax call
});;
Hi I am using JQuery Form validator to validate a form, and using knockout js to call a function using a button, What I want is that when the button is clicked the the knockout js function should be called, and also at the same time check if all the fields are validated if not, it should just do nothing till all the fields are validated.
Link for the jquery validator form http://www.formvalidator.net/#advanced_programmatically
Here is a field and the button that calls the function.
<input type="text" name="birthday" data-validation="date" data-validation-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" data-validation-help="You must be more than 20 years old" class="form-control" value="<?php if (isset($user['Birthday'])) {echo $user['Birthday'];} ?>">
<div data-bind="ifnot: (loggedIn() == 'true')">
<button data-bind="click : openUpTwoStepAuth " type="submit" id="openUpTwoStepAuth" class="btn registerbtn">
<?php echo lang("register_continue_btn"); ?>
</button>
</div>
And here is the knockout js function that tries to call the validation as soon as the button is clicked, but in my case it does not check the validation and goes on with the ajax call.
self.openUpTwoStepAuth = function(){
$('#openUpTwoStepAuth').validate(function(valid, elem) {
if(!valid){
return;
}
});
self.emailtokenconfirmation(false);
self.tokenError(null);
self.showTwoStepAuth();
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/sendEmailForTwoStepAuth/',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({customerEmail : self.customerEmail()})
})
.done(function(data) {
if(data.success){
self.emailtokenconfirmation(true);
}else{
self.tokenError(data.result);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error code thrown: " + errorThrown);
})
.always(function(data){
});
}
It works fine if its just a normal button calling the submit function with this piece of code
<script>
$.validate({
modules : 'toggleDisabled',
disabledFormFilter : 'form.toggle-disabled',
showErrorDialogs : false
});
</script>
but for me I want to call a js function and at the same time check the validation of the field.
This seems to be already answered here
Knockout + Jquery Validate
Use submitHandler in validate to call your view model function on successful validation.
I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)
I have a php function that loops thru matches in a database, inside the loop, there is a form that gets returned to the page where the function is called:
while($row=mysql_fetch_array($get_unconfirmed))
{
echo "<form name='confirm_appointment' method='post' class='confirm_appointment'>";
echo "<input type='hidden' name='app_id' value='$appointment_id'>";
echo "<input type='hidden' name='clinic_id' value='$clinic_id'>";
echo "<td><input type='submit' class='update_appointment_button' value='$appointment_id'></td>";
echo "</form>";
}
Then I have jQuery to submit the form:
$( document ).ready(function() {
$(".update_appointment_button").click(function(){
var url = "ajax/update_appointment_status.php";
$.ajax({
type: "POST",
url: url,
data: $(".confirm_appointment").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
But the issue is, the way its set up, no matter what row I push "submit" for - I always get the values from the last row (form).
So I know the issue, I am not telling jQuery to get the values from the form with the button thats pushed. I need to somehow use .this maybe, but just cant seem to figure out the correct syntax.
Any help would be appricated!
You can access its parent form like this
data: $(this).closest(".confirm_appointment").serialize(),
or something like this
data: $this.parent().parent().serialize(),
Another way: replace the button click event by the form submit event.
$(document).ready(function () {
$('.confirm_appointment').submit(function (e) {
e.preventDefault();
var url = "ajax/update_appointment_status.php";
var serialized = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: serialized,
success: function (data) {
alert(data); // show response from the php script.
}
});
});
});
JSFiddle demo
I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});