CodeIgniter Javascript form submission - javascript

I would first want to say that I am very new to javascript and jQuery.
Its a very silly and simple problem I suppose, and I am aware there are plenty of questions on this, and I did try all of them. Though I cant seem to solve my problem.
I have an input field and a submit button. On clicking submit I would like to save the content of the input filed into the database, and continue to remain in the same page with content on page as is.
My Javascript code is as follows:
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').submit(function(e)
{
e.preventDefault();
var msg = $('#uname').val();
$.post("c_test/test_submit", {uname: msg}, function(r) {
console.log(r);
});
});
});
</script>
And my html code as follows ( I use codeigniter):
$this->load->helper('form');
echo form_open();
$data =array ('name'=>'uname','id'=>'uname');
echo form_input($data) . '<br />';
$data=array('name'=>'submit','id'=>'submit','value'=>'Submit');
echo form_submit($data);
echo form_close();
I would be very grateful if anyone could point out my stupidity. Thanks!

You are using
$('#submit').submit(function(e){ ... });
In this case submit is the button/input's id and it has no such an event like submit, instead you can use click event, like
$('#submit').click(function(e){ ... });
or
$('#submit').on('click', function(e){ ... });
Otherwise, you can change the following line
echo form_open();
to
echo form_open('c_test/test_submit', array('id' => 'myform'));
and instead of
$('#submit').click(function(e){ ... });
you can use
$('#myform').submit(function(e){
e.preventDefault();
var msg = $('#uname').val();
var url=$(this).attr('action');
$.post(url, {uname: msg}, function(r) {
console.log(r);
});
});
or
$('#myform').on('submit', function(e){
e.preventDefault();
var msg = $('#uname').val();
var url=$(this).attr('action');
$.post(url, {uname: msg}, function(r) {
console.log(r);
});
});

It seems like the element with an id of "submit" is the submit button for the form - <input type="submit">. However, the submit event is fired by the form, not the submit button, so your bound event handler won't fire.
Either move the "submit" id onto the form, or change the selector when binding the submit event handler:
$('form').submit(function(e) {
// handle submit event from the form
});

You have to do it like this:
<?php
$this->load->helper('form');
echo form_open('', array( 'id' => 'myform'));
..
and:
$('#myform').submit(function(e)
{
e.preventDefault();
var msg = $('#uname').val();
$.post("c_test/test_submit", {uname: msg}, function(r) {
console.log(r);
});
return false;
});
The submit event always goes to the form and not to the form button.

perhaps like this:
$data=array('name'=>'submit','id'=>'submit','value'=>'Submit','onsubmit'=>'return false;');
This will stop the form from posting which will in turn stop the page from refreshing. However, it will require that you submit the form via ajax.

Related

Is it posiible to use onClick function on my form submit button?

I store multiple data in a table for enquiry basis.. which is successfully stored in my table. but now i also want to store those same data in Booking basis.
So i used onClick function for storing enquiry data. and now i want to store booking data in table from form submit button.
here is my form submit button code:
<button type="submit" class="booking-btn" onclick="btn_booking_hour();" id="btn_booking_hour">Book Now</button>
Here is my form action:
<?php echo form_open('booking/'.$product->id); ?>
And here my function:
function btn_booking_hour()
{
var date = $('#datehour').val();
var renter_id = $("#ownerid").val();
var guests_quantity = $('#no_of_guests').val();
var property_id = $('#property_id').val();
var selectedIds="";
var selectedObject = document.getElementsByClassName('hour_slots_available slot_activated');
for(var i=0;i<selectedObject.length;i++)
selectedIds+=selectedObject[i].id+",";
if(selectedIds == ""){
alert("Please select Hour-Slot(s) before Booking");
}
else{
$.ajax({
type: 'POST',
dataType:'json',
url:baseURL+'site/rentals/ajaxhourshow',
data:{'selectedHours':selectedIds,'property_id':property_id,'date':date,'guests_quantity':guests_quantity,'renter_id':renter_id},
success: function(responce){
var myJSON = JSON.stringify(responce);
var packet = $.parseJSON(myJSON);
var prd_id=packet.property_id;
var hour_slots=packet.hour_slots;
window.location.href = baseURL+'booking/'+prd_id;
}
});
}
}
Please suggest me how can i submit a form with data within their onClick function. Thanks..
Not sure if you are using a form, if you are using it you can can use onsubmit handler and return the action. In that case you wont need onclick handler in the button
<form onsubmit = "return btn_booking_hour()">
// Rest of code
</form>
You can also do like this
$('#form').on('submit',function(e){
e.preventDefault();
// rest of the code
})
you can use this code
function btn_booking_hour(){
// your other code
document.getElementById('formid').submit();
// formid = form id
}
or also use jquery
function btn_booking_hour(){
// your other code
$('#formid').submit();
// formid = form id
}
i got your point so you can also use it
$(function() {
//hang on event of form with id=myform
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
rest of your code
});
});

JS Validate plugin prevent submit form

Hello this is my code i am trying to prevent form submit when button is clicked, and load ajax. but form continue to submits, I tried to add preventDefault, and onsubmit false parametar but no luck. Is there anyone to help me to fix this problem
$(function() {
$('#submitTest').click(function(e){
var form_test = $('#test_forma').serialize();
e.preventDefault;
jQuery.extend(jQuery.validator.messages, {
required: "Odgovor je obavezan",
});
$( "#test_forma" ).validate({
onsubmit: false,
submitHandler: function(form) {
form.preventDefault();
// e.preventDefault();
if(('#test_forma').valid()) {
$.ajax({
type: "POST",
url: " <?php echo base_url().'home/test';?> ",
data: {form_test:form_test},
beforeSend: function() {
// setting a timeout
$('#g_upozorenje').html('<img src="<?php echo base_url().'images/loading.gif';?>"/>');
},
success: function(response) {
$.each(response.answers, function(i, item){
// if(('#test_odgovori_' + i).val()) == response[i].IdPitanja)
if(response.answers[i].provera ==1) {
$('#test_odgovori_'+response.answers[i].Id).css('color','green');
} else {
$('#test_odgovori_'+response.answers[i].Id ).css('color','green');
$('.test_odgovori_'+response.answers[i].IdPitanja+':checked').next().css('color','red');
}
$('#procenat').html('Odgovorili ste tačno na '+response.result + '% pitanja')
$('#rezultati').dialog();
});
}
});
}
}
});
});
});
You need to use preventDefault as a method and D is uppercase
e.preventDefault();
http://api.jquery.com/event.preventdefault/
You've got to return false;.
Take a look at this example:
<form onsubmit="javascript:doSomething();return false;">
<input type="submit" value="click me">
</form>
Or look here.
e.preventDefault(); is written correctly with brackets, and I think they should be the first after the opening brackets. And try to fire the preventDefault on the form submit and not the click on the button. There are several possibilities to submit a form without pressing the button, you wouldn't handle now.
You need to stop the form from submitting, not preventing default action of the button.
Instead target the form's submit event:
$("form").submit(function (e) {
e.preventDefault(); // this will prevent from submitting the form.
...
Or even use jQuery's on event handler for better performance:
$("form").on('submit', function (e) {
e.preventDefault(); // this will prevent from submitting the form.
...

jquery ajax not submitting

I have this code:
<script>
$(document).ready(function() {
$("#edit-my-username").click(function() {
$("#my-username").html('<input type="text" id="new-username" value="<?php echo $my_username; ?>"> <button class="my-button small-btn" id="submit-my-username">Submit</button>');
});
$("#submit-my-username").click(function() {
var user = "<?php echo $userid; ?>";
var edit_field = "username";
var edit_content = $("#new-username").val();
if(edit_content !== ''){
$.ajax({
type: "POST",
url: "edit-user.php",
data: {user: user, field: edit_field, content: edit_content},
cache: false,
success: function(html){
$("#my-username").html(html);
}
});
}return false;
});
});
</script>
I can't figure out why it doesn't submit. Firebug see's no XHR when the button is clicked. I'm not exactly confident with JS/jQ.. where am I going wrong?
Since you are dynamically adding #submit-my-username the click handler is not binded on page load.
$("#submit-my-username").click(function() {
Change the click handler to following
$("body").on( "click", "#submit-my-username", function() {
When you add html via javascript, in your case jquery, the click event (and any other trigger events) do not works.
You have to use on event, or live event, but the last one is deprecated.
For example:
$("#submit-my-username").live('click'. function()
$("#submit-my-username").on('click', function()
When page load,jquery ready funciton executed.The section 'Submit' does not exist,so '$("#submit-my-username").click(function() {}' script not works.
I think you should add onclick event in 'Submit' distinctly.
such as :
<button class="my-button small-btn" id="submit-my-username" onclick='func()'>Submit</button>
In your case, you should use .live() method, however it is now deprecated. instead of that you can use .on()
$("#my-username").on('click', '#submit-my-username', function(event) {}
Sorry for mis-interpreting your question.Below code can be user to submit form using jquery.
$("form").submit(function(){
//your code
});
Hope this is the answer to your question.

Show PHP file inside a DIV with jQuery

I have 3 files
register.php
reg.js
reg.php
When I hit the submit button in register.php (looks like this)
<div id="phpcontenthere"></div>
<form action="reg.php" method="post" id="myForm">
<input type='submit' id='submit' value='Sth'>
</form>
<script type="text/javascript" src="reg.js"></script>
It shows the error messages of reg.php but in another window.
I want those error messages to be shown inside the register.php.
And the reg.js looks like this:
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#phpcontenthere").empty();
$("#phpcontenthere").html(info);
});
$("myForm").submit( function () {
return false;
});
});
Maybe this solution i want to create is not good, or it's good but i missed something I don't know, but I would be really happy if anyone could help me,
Thanks in advance!
Tibor
I'll teach you the logic, with sample code as I don't want to spoon-feed you.
Firstly, create an array called 'errors':
$errors = array();
Then while you have your checks, just inflate your array.
if(something) {
$errors[] = "Error description";
}
Then once all your errors are inflated, you check for the length, and if it is greater than 0 errors, then return the array.
if(count($errors) > 0) {
return $errors;
}
And then, you can display the array with the for loop.
$c = count($errors);
for($i=0; $i < $c; $i++) {
echo $errors[$i];
}
You have a few problems.
First, $("myform") should be $("#myform") -- you forgot the # so it wasn't matching the ID.
Second, you shouldn't define a handler for submit inside the click handler; event handlers should almost always be defined at the toplevel.
You should just put return false in the click handler. Or better, put all that code in the form's submit handler (clicking on the submit button submits the form).
$("#myForm").submit( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#phpcontenthere").html(info);
});
});
return false;
});
It's also not necessary to call .empty() before calling .html(), since the latter completely replaces what's there.
From what I see, you are still submitting the form (the piece of code that returns false when trying to submit is inside the click listener). Maybe that's why it is ignoring the return false, and indeed submitting the form (instead of posting it with ajax)
So you should try a javascript code like this:
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#phpcontenthere").empty();
$("#phpcontenthere").html(info);
}
);
});
$("#myForm").submit( function () {
return false;
});

Form submit without going to the target page

I have question regarding form submit. I have this simple form on processFabrication.php to submit all the variables then process it to the database in another page called processExceededQty.php
Co, in processFabrication.php, I have
echo "<form action='processExceededQty.php' method='post'>";
When I click submit it goes to the processExceededQty.php.
What I am aiming to do is,
When user click submit, display confirmation yes/no with popup
After user click yes with the confirmation window, stay in processFabrication.php but methods in processExceededQty.php is still executed.
When user click no on the popup, go back and don't do form action
Any help would be greatly appreciated.
Something like this in your javascript:
function doSubmit(){
if (confirm('Are you sure you want to submit?')) {
// yes
return true;
} else {
// Do nothing!
return false
}
}
add the onsubmit to your form in html:
<form action='processExceededQty.php' method='post' onsubmit='doSumit()'>
Addition to #N0M3 answer.
Include below script in your <head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
and slight change in your function
function doSubmit(){
if (confirm('Are you sure you want to submit?')) {
// yes
$(this).submit(function(e){
e.preventDefault();
});
jQuery.ajax({
url : 'processExceededQty.php',
data : {'username':username}, // where first 'username' is your field name, and second one is your field's value
method: 'post',
success: function(data) {
// data is variable which has return data from `processExceededQty.php`
// do whatever you want with data
}
});
} else {
// Do nothing!
return false;
}
}
Use function on the "onsubmit" of the form like below,
<form action='processExceededQty.php' method='post' onsubmit='reutrn show_pop_up()'>
And on script you ca write following
<script>
function show_pop_up()
{
// show pop up
if(op_up_return =="Yes")
return true;
else
return false;
}
</script>
Hope this will help.

Categories