submit form with ajax but get "Illegal Invocation" - javascript

I try to submit form via ajax, below is the form.
<form class="form-vertical" method="POST" id="request-form" action="/post_handler?request=add_data" enctype="multipart/form-data">
<div class="form-group">
<label for="date_inp" class="control-label">Date</label>
<input class="form-control hasDatepicker" id="datepicker" type="text" name="date">
</div>
</div>
<div class="form-group">
<label for="file_inp">Upload File</label>
<div>
<input class="form-control" id="file_inp" type="file" placeholder="Upload File" name="file">
</div>
</div>
<div class="form-group">
<div>
<button type="submit" class="btn btn-default submit-button" onclick="on_click_form_submit(event);">Submit</button>
</div>
</div>
</form>
This is the click function.
on_click_form_submit = function(event) {
event.preventDefault();
var form_data = new FormData($('#request-form')[0]),
form_url = '/' + $('#request-form')[0].action.split('/').pop();
console.log('url: ' + form_url);
$.ajax({
url: form_url,
type: 'POST',
data: form_data,
dataType: 'json',
encode: true
})
.done(function(response) {
alert(response);
})
.fail(function(xhr, status, error) {
alert(xhr.responseText);
});
return false;
};
When I click submit, it reports
Uncaught TypeError: Illegal invocation
at add (jquery-1.9.1.js:7340)
at buildParams (jquery-1.9.1.js:7392)
at Function.jQuery.param (jquery-1.9.1.js:7360)
at Function.ajax (jquery-1.9.1.js:7863)
at Object.on_click_form_submit (spa.shell.js:301)

Per the docs, jQuery's $.ajax accepts:
Type: PlainObject or String or Array
So, your form_data should be in one of those formats - it should not be an instantiation of a FormData. It depends on what your backend is expecting, but one option would be to convert the form's values to an object with serializeArray():
on_click_form_submit = function(event) {
event.preventDefault();
var form_data = $('#request-form').serializeArray(),
form_url = '/' + $('#request-form')[0].action.split('/').pop();
console.log('url: ' + form_url);
$.ajax({
url: form_url,
type: 'POST',
data: form_data,
dataType: 'json',
encode: true
})
.done(function(response) {
alert(response);
})
.fail(function(xhr, status, error) {
alert(xhr.responseText);
});
return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-vertical" method="POST" id="request-form" action="/post_handler?request=add_data" enctype="multipart/form-data">
<div class="form-group">
<label for="date_inp" class="control-label">Date</label>
<input class="form-control hasDatepicker" id="datepicker" type="text" name="date">
</div>
</div>
<div class="form-group">
<label for="file_inp">Upload File</label>
<div>
<input class="form-control" id="file_inp" type="file" placeholder="Upload File" name="file">
</div>
</div>
<div class="form-group">
<div>
<button type="submit" class="btn btn-default submit-button" onclick="on_click_form_submit(event);">Submit</button>
</div>
</div>
</form>

Related

How to check if submitting form with jQuery if successful?

I have following codes as form, and I wanted to check if the form is been successfully submitted.
I was wondering how I can check on the console. I want to check if the form is been successfully submitted so I can display another form.
<form id="signup" data-magellan-target="signup" action="http://app-service-staging.com" class="epic_app-signup" method="POST">
<div class="grid__column " style="width: 100%;">
<input type="text" name="first_name" placeholder="Name" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="password" placeholder="Password" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="confimred-password" placeholder="Confirmed password" />
</div>
<div class="grid__column " style="width: 100%;">
<input type="date" name="startdate" id="startdate" min="2019-12-16">
</div>
</div>
<button type="submit" class="grid__column" style="width: 50%;"></button>
</div>
</div>
</div>
</form>
and the script,
$('.epic_app-signup').on('submit', function(e) {
e.preventDefault();
var formData = $('.epic_app-signup').serializeArray();
var jsonData = {};
formData.forEach(function(item, index) {
jsonData[item.name] = item.value;
});
console.log('data\n', jsonData);
$.ajax({
url: 'http://app-service-staging.com/api/auth/register',
type:'POST',
data: jsonData,
contentType: 'application/json'
}).done(function(data, textStatus, jqXHR) {
if (textStatus === 'success') {
}
});
});
});
you can do this by various ways currently you are not using ajax request if you want to achieve this without ajax let follow these steps
when user click on submit button your form is submitted received form information(you define the path in action attribute where form submitted) after processing successfully redirect toward a new form
second solution use jquery ajax request
//first form
<form action='test.php' id='form_1' method='post'>
<label>Full Name</label>
<input type='text' name='full_name'>
<input type='submit'>
</form>
//second form
<form action='test.php' id='form_2' method='post' style='display:none'>
<label>Father Name</label>
<input type='text' name='father_name'>
<input type='submit'>
</form>
use jquery cdn
<script src='https://code.jquery.com/jquery-git.js'></script>
<script>
$("#form_1").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
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("form submitted successfully");
$('#form_1').hide();
$('#form_2').show();
},
error:function(data){
alert("there is an error kindly check it now");
}
});
return false;
});
</script>

Jquery Not Sending the Form to HTTP

I'm having some problems with Jquery/Ajax.
This is my code for the form :
<form class="form-auth-small" method="POST" id="form" enctype="multipart/form-data">
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Email</label>
<input type="email" class="form-control" name="email" value="samuel.gold#domain.com" placeholder="Email">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Name</label>
<input type="text" class="form-control" name="name" value="John">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Phone</label>
<input type="text" class="form-control" name="phone" placeholder="938434928">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only"></label>
<input type="password" class="form-control" name="password" placeholder="****">
</div>
<div class="form-group">
<input name="image" type="file" />
</div>
<button type="submit" id="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</form>
And this is my code to AJAX/Jquery:
<script>
$(".submit").on("click", function(e) {
var form = $("#form");
// you can't pass Jquery form it has to be javascript form object var formData = new FormData(form[0]);
console.log(formData);
$.ajax({
type: "POST",
url: '/user/signup/',
data: formData,
contentType: false, //this is requireded please see answers above processData: false, //this is requireded please see answers above //cache: false, //not sure but works for me without this error: function (err) { console.log(err);
success: function(res) {
console.log(res);
},
});
});
</script>
When i do console.log to check that from form i don't receive any value, and when i check in network i dont see any HTTP callback.
Your code doesn't work because you were using the class selector token . (dot) instead of the id selector token # hashtag. Further details can be found on the documentation
Change this instruction
$(".submit").on("click", function(e) // …
to
$("#submit").on("click", function(e) // …
You dont have submit class. You have id="submit"
$("#submit").on("click", function(e) {
Use this and it should work.
Also change type="submit" to type="button" or in your js code you need to add
e.preventDefault();

jQuery and AJAX work only once

I have problem with AJAX and jQuery. I write function for login to system, but it works only first time. Here is my code:
html in modal:
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
here is jquery:
function login(){
login=document.getElementById('userName').value;
pass=document.getElementById('password').value;
var dataString="emailLogin="+login+"&passLogin="+pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text){
if(text=='0'){
$("#loginError").removeClass('hidden');
}else{
$("#loginOk").removeClass('hidden');
$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">"+login+" (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html(""+login+" (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
}
});
return false;
}
You are overwriting your login function with a string.
function foo() {
alert('foo');
foo = function () {
alert('bar');
}
}
<a onclick="foo()">
click me!
</a>
See how the second click here causes a different alert? In your case you're replacing the function with a string instead of a function, causing a syntax error. Don't forget to var your variables.
var login=document.getElementById('userName').value;
var pass=document.getElementById('password').value;
The snippet tests your logic and there was a console error for your login and pass variables. I set them as 'var' and put your success logic in the 'error' section of the ajax request since I cannot reach your server, but it does create the logout button. Is that what you wanted?
function login() {
var login = document.getElementById('userName').value;
var pass = document.getElementById('password').value;
var dataString = "emailLogin=" + login + "&passLogin=" + pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text) {
/* Success logic */
},
error: function() {
alert('Test - success logic');
$("#loginOk").removeClass('hidden');
//$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">" + login + " (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html("" + login + " (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
<div id="loginLi"></div>
<div id="regLi"></div>
<div id="loginOk">Login OK</div>

Insert data using bootstrap modal in datatables library

I want to insert data with the help of bootstrap modal. But I've got an error on the action index. So the button I've added couldn't run. Did I make any wrong thing in coding?
Controller
function user_action(){
if ($_POST['action'] == "Tambah"){
$data=array(
'kodebayar' => $this->input->post('kodebayar'),
'nama' => $this->input->post('nama'),
'harga' => $this->input->post('harga')
);
$this->bpem_m->create($data);
}
}
View Of Modal
<div class="modal fade text-xs-left" id="modalpem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel35" aria-hidden="true">
<div class="modal-dialog modal-sm">
<form method= "post" id="form_pem">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<fieldset class="form-group floating-label-form-group">
<label for="Kode">Kode <span class="required">*</span></label>
<input type="text" class="form-control" name="kodebayar" id="kodebayar" placeholder="Kode Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="nama">Nama <span class="required">*</span></label>
<input type="text" class="form-control" name="nama" id="nama" placeholder="Nama Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="projectinput7">Biaya Perbulan <span class="required">*</span></label>
<div class="input-group">
<span class="input-group-addon">Rp.</span>
<input type="number" class="form-control" placeholder="Biaya Perbulan" aria-label="Amount (to the nearest dollar)" name="harga" id="harga">
<span class="input-group-addon">.00</span>
</div>
</fieldset>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" name="action" value="Tambah"/>
</div>
</div>
</form>
</div>
</div>
JS
$(document).on('submit','#form_pem', function(event){
event.preventDefault();
var kodebayar = $('#kodebayar').val();
var nama = $('#nama').val;
var harga = $('#harga').val;
var postData = new FormData(this);
if(kodebayar != '' && nama != '' && harga != ''){
$.ajax({
url:"<?=site_url('bpem/user_action')?>",
method: "POST",
data: postData,
contentType: false,
processData: false,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
alert(data);
$('#form_pem')[0].reset();
$('#modalpem').modal('hide');
dataTable.ajax.reload();
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
}
else{
alert("Silahkan isikan semua data!");
}
});
You can use serialize()
var datastring = $("#form_pem").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
return type is json
EDIT: I use event.preventDefault to prevent the browser getting submitted in such scenarios.

Jquery ajax not working in firefox

My code is working in chrome,safari but its not working in firefox.
Here is my code
<script>
$(document).ready(function () {
$("#loginform").on('submit',(function(e) {
e.preventDefault();
$('#loading').html("Loading....");
$.ajax({
url: "login.php",
type: "POST",
data: new FormData(this),
contentType:false,
cache: false,
processData:false,
async:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
return false;
}));
});
</script>
Can anyone solve this issue??? I have one more same script in the same page only url is different but its working fine,but this script is not working .Iam getting empty data .But in chrome,safari its working fine.
My Html Code :
<form role="form" method="post" id="loginform" action="">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Username" required>
</div>
<div class="form-group">
<label for="password"> Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<div class="checkbox">
<label><input type="checkbox" value="" name="user_rememberme" checked>Remember me</label>
</div>
<div id="loading"></div>
<div id="message"></div>
<button type="submit" name="login" class="btn btn-success pull-right">Login</button>
</form>
Never use async:false in ajax call unless you knows specifically wat you are doing.The problem is that async:false freezes the browser until ajax call is complete (either error or success).set it to true or remove it (by default it is true).Implement error block too and check if its an error from server side
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
},error:function(data){
console.log(data)
}
Try this:
<script>
$(document).ready(function () {
$("#loginform").on('submit',(function(e) {
dta = $(this).serialize();
e.preventDefault();
$('#loading').html("Loading....");
$.ajax({
url: "login.php",
type: "POST",
data:dta,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
return false;
}));
});
</script>

Categories

Resources