I can't get the ajax response when submitting a modal dialog form. It works perfectly when the form is not modal.
The form:
<div id="form2" style="display: none">
<form id="objectInsert" action="element/create" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" id="name"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description"></textarea>
</div>
</form>
Here i get the ajax success part in the console!
$("#objectInsert").submit(function(e) {
e.preventDefault();
resetErrors();
var form = this;
var url = $(this).attr('action');
var data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//Working
},
error: function() {
console.log('there was a problem checking the fields');
}
});
});
Here i get the ajax error part in the console! can someone tell me where i'm doing wrong?
$("#add_element").click(function(){
$("#form2").dialog({
modal:true,
width:400,
buttons:{
Send:function(e){
e.preventDefault();
var form = $("#objectInsert");
var url = form.attr('action');
var data = new FormData(form[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//not working
},
error: function(xhr, status, error) {
console.log('there was a problem checking the fields');
console.log(xhr);
console.log(error);
}
});
return false;
},
Cancel:function(){
$(this).dialog("close");
}
}
});
});
The controller
public function create() {
try{
$this->form = new Form();
$this->form->post('name');
$this->form->val('isEmpty', 'name');
$this->form->post('description');
$this->form->val('isEmpty', 'description');
$this->form->fetch();
$this->form->submit();
$data = $this->form->get_postData();
$this->model->insert($data);
echo json_encode('success');
} catch (Exception $ex) {
$errors = $this->form->get_error();
$_SESSION["errors"] = $errors;
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])
== 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
exit;
}
foreach ($_SESSION["errors"] as $errors){
echo $errors;
echo '<br/>';
}exit;
}
}
see this code you have not closed the function block
success: function(resp) {
console.log(resp);//not working
},//This is not closed for success function
error: function() {
console.log('there was a problem checking the fields');
}
Related
I have a form on my front-end and when the submit button is clicked I want to send the details to my get-emp.php file without page reload.
The code looks like this:
index.html
<form class="form-emp-details hide" action="">
<div class="form-group">
<label for="">First name:</label>
<input type="text" class="form-control input-emp-firstname" name="input_emp_firstname">
</div>
<div class="form-group">
<label for="">Last name:</label>
<input type="text" class="form-control input-emp-lastname" name="input_emp_lastname">
</div>
<div class="form-group">
<label></label>
<button type="submit" class="btn btn-default btn-submit-1" name="submit_emp_details">Save</button>
</div>
</form>
custom.js
$(".form-emp-details").("submit", function(e) {
var input_first_name = $(".input-emp-firstname").val();
$.ajax({
type: "POST",
url: "get-emp.php",
data: {
input_emp_firstname:input_first_name,
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
});
get-emp.php
if(isset($_POST['submit_emp_details'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
I want to display the submitted form data on get-emp.php file but it seems that I am not able to detect the submitted button and echo the form data on.
My goal is to capture all form data with a single request variable or identifier $_POST['submit_emp_details']
Any help is greatly appreciated. Thanks
$("#MyformId").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
// success..
}
});
});
You passing the POST data of firstname and lastname by:
input_emp_firstname
input_emp_lastname
so, you need to change the $_POST['submit_emp_details'] to $_POST['input_emp_firstname'] on file get-emp.php to
<?php
if(isset($_POST['input_emp_firstname'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
Edit 2:
$.ajax({
type: "POST",
url: "get-emp.php",
cache: false,
data: {
submit_emp_details: {
input_emp_firstname:input_first_name,
input_emp_lastname:input_last_name
}
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
I have a datatable where I have the detail column with an edit button. When the user clicks on the edit am passing the id as a parameter. I am fetching all the values for that id and displaying in the form. Now when I edit the values and submit the form using PUT method it is getting inserted in the table, the values are passing as a parameter and it shows the empty form. How to solve this issue.
HTML:
<form class="container" id="myform" name="myform" novalidate>
<div class="form-group row">
<label for="position" class="col-sm-2 col-form-label fw-6">Position</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" required>
</div>
</div>
<div class="form-group row">
<label for="location" class="col-sm-2 col-form-label fw-6">Location</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="location" name="location" placeholder="Location" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
PUT Method Script:
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
GET method script:
<script type="text/javascript">
$(document).ready(function(){
var id_val;
var params = new window.URLSearchParams(window.location.search);
id_val = params.get('id');
console.log(id_val);
var url1=id_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
type: "GET",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
console.log(typeof(data));
$("#position").val(data.position);
$("#location").val(data.location);
},
error: function(data) {
console.log(data);
}
});
});
</script>
After submitting the form the page should remain the same with edit form values. only the edited values should be inserted. How to achieve this.
$('#myform').on('submit', function (e) {
e.preventDefault();
..........
I have checked your code in my editor. There are some changes which i made in ajax request, and it now works for me. here is the code. Try it
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
e.preventDefault();
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
method: 'POST', //or you can use GET
dataType : "json", //REMOVED CONTENT TYPE AND ASYNC
data: {send_obj:JSON.stringify(parms)}, //ADDED OBJECT FOR DATA
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
Adding prevent default in form submit handle is enough. You're handling the post request by ajax call.
e.preventDefault();
There are 2 changes in your code.
This code will prevent your page from reloading and also you are not sending the data in proper format.
$("#myform").submit(function(e) {
e.preventDefault(); // 1. Dont reload the page
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: parms, // 2. Just send the parms object bcoz you already defined the dataType as json so it will automatically convert it into string.
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
I am trying to submit a form using ajax in Laravel 5.5
The problem is the page is refreshing and not submitting data in the database. I need to store data in the database without refreshing the page.
Here is my code:
Controller
public function new_timing_table(Request $request)
{
if (Request::ajax()) {
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "yes";
} else {
$msg = "yes";
}
return ['msg'=> $msg];
}
View
<form id="timeForm" class="form-horizontal form-material" >
<div class="form-group">
{{ csrf_field() }}
<div class="col-md-12 m-b-20">
<label> Table Name</label>
<input type="text" id="timing_tables_name" class="form-control"
name="timing_tables_name" />
</div>
<div class="modal-footer">
<input type="button" value="Replace Message" id='btnSelector'>
</div>
</div>
</form>
Ajax script
const xCsrfToken = "{{ csrf_token() }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': xCsrfToken
}
});
jQuery(document).ready(function() {
jQuery('#btnSelector').click(function(e) {
event.preventDefault();
getMessage();
});
});
var getMessage = function() {
var timing_tables_name = $("input[name=timing_tables_name]").val();
$.ajax({
type: 'post',
url: '/new_timing_table',
dataType: 'json', //Make sure your returning data type dffine as json
data: timing_tables_name,
//data:'_token = <php echo csrf_token() ?>',
success: function(data) {
console.log(data); //Please share cosnole data
if (data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg);
}
}
});
}
Router
Route::post('/new_timing_table','Timing_TableControoler#new_timing_table');
You got a typo or a mistake in your script.
jQuery('#btnSelector').click(function(e){
// An error here - it should be e.preventDefault();
event.preventDefault();
getMessage();
});
My code is working now after adding beforeSend: function (request) in Ajax script
var getMessage = function(){
var timing_tables_name = $("#timing_tables_name").val();
console.log(timing_tables_name);
$.ajax({
type:'GET',
url:'/new_timing_table', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:
{
timing_tables_name
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-
token']").attr('content'));
},
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
and editing the controller to be simple as this one
public function new_timing_table(Request $request){
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "This is a simple message.";
return ['msg'=> $msg];
}
Thank you all for your help
I have very very little knowledge of javascript but somehow I managed to post form data to a php file.
Now I am facing a little problem, there are some validations on php file, what I want is if there is any validation fails and the php file returns $error = 'Invalid data'; I want this ajax request to simply display the error message.
Or, if it returns no error, or $error = ''; this ajax request redirect to thankyou.php page.
HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "data.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
if (data == 'true') {
window.location.href="thankyou.php";
};
if (data !== 'true') {
$("#status").html(data);
};
},
error: function(){
}
});
}));
});
<form id="frmContact" action="" method="post">
<div id="status"></div>
<div>
<label>Email</label>
<span id="userEmail-info" class="info"></span><br/>
<input type="text" name="userEmail" id="userEmail" class="demoInputBox">
</div>
<div>
<input type="submit" value="Send" class="btnAction" />
</div>
</form>
data.php
<?php
// PHP code above...
//Lets add $error variable for test purpose...
$error = 'Invalid data';
?>
Change only success function like this
success: function(data){
if (data === 'Invalid data') {
$("#status").html(data);
}
else {
window.location.href="thankyou.php";
}
}
and in php you should echo $error
Echo out "Success" if everything goes according to what you wanted in the posted data i.e all validations passed or echo out any specific validation error. The echoed response will be the response according to which our JS will act accordingly.
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "data.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false
})
.done(function(response){
if(response=="Success")
window.location.href="thankyou.php";
else
$("#status").html(response);
});
}));
});
I have a modal form with Bootstrap that is associated with a specific item that is customized by the user before being added to the cart. I'm trying to trigger an Ajax request when the "Add to Cart" button is clicked. But the button doesn't seem to be triggering anything. I'm using a modified version of Bootstrap's sample code: http://getbootstrap.com/javascript/#modals-related-target
Any suggestions on how to get the button to trigger an ajax request properly?
UPDATE: I've added the PHP code below in case that might be the issue.
HTML:
<div class="modal-body">
<form name="formBasic" id="formBasic">
<input type="hidden" name="function" value="basic-form">
<div class="form-group">
<label for="message-text" class="control-label">Enter customized information</label>
<textarea class="form-control" id="customized-information"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="basic-submit">Add to Cart</button>
</div>
Javascript:
$(document).ready(function () {
var formBasic = function () {
var formData = $("#formBasic").serialize();
$(form).ajaxSubmit({
type: 'post',
data: formData,
dataType: 'json',
url: 'http://localhost/forms.php'
error: function () {
console.log(output);
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
$('#formBasicResults').html(output.responseText);
}
});
return false;
};
$("#basic-submit").on("click", function (e) {
e.preventDefault();
formBasic();
});
});
PHP:
//formBasic Processing
function formBasic(){
$output = 'Output from Form Basic:
';
foreach ($_POST as $key => $value) {
$output .= $key . ': ' . $value . '
';
}
echo $output;
}
//FormAdvanced Processing
//. . .
if(in_array($_POST['function'], array('formBasic','formAdvanced'))){
$_POST['function']();
}else{
echo 'There was an error processing the form';
}
Your code should be:
$(document).ready(function () {
var formBasic = function () {
var formData = $("#formBasic").serialize();
$.ajax({
type: 'post',
data: formData,
dataType: 'json',
url: 'http://localhost/forms.php',
error: function () {
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
$('#formBasicResults').html(output.responseText);
}
});
return false;
};
$("#basic-submit").on("click", function (e) {
e.preventDefault();
formBasic();
});
});
Issues:
1- Missing comma on line:
url: 'http://localhost/forms.php'
2- form not defined:
$(form).ajaxSubmit({
Working fiddle: http://jsfiddle.net/p9v2eg4u/2/
$('#basic-submit').click(function() {
var formData = $("#formBasic").serialize();
console.log(formData);
added a console.log(); of the value of form data
$('#formBasic').ajaxSubmit({
type: 'POST',
data: formData,
dataType: 'JSON',
url: 'http://localhost/forms.php',
added missing comma after URL
error: function () {
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
console.log(output);
another console.log of output object
$('#formBasicResults').html(output.responseText);
},
success: function(output) {}
consider using success instead of complete, complete will execute if success or error.
});
return false;
});