I'm using laravel framework and JQuery and AJAX in order to save a new entry into my database, however I fail at capturing the values of my inputs since validation is failing (some fields are required and I can't seem to gather data correctly so they are empty).
This is the error:
errors: {…}
body: Array [ "The body field is required." ]
image: Array [ "The image field is required." ]
title: Array [ "The title field is required." ]
<prototype>: Object { … }
message: "The given data was invalid."
Here is my jQuery code:
$('.form_new_button').click(function() {
var linked_entry = $(this).attr("data-link");
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')
}
});
switch (linked_entry) {
case "sliders":
console.log('new slider button clicked');
var form = $('new_slider_form').get(0);
$.ajax({
async: true,
url: '/sliders',
type: 'POST',
data: new FormData(form),
dataType: 'JSON',
processData: false,
contentType: false,
success: function(data) {
$('.form_valid_container').html('<span class="form_valid_text">✓ ' + data.success + '</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
$.each(errors, function() {
$('.form_error_container').html('<span class="form_error_text">✘ ' + errors.message + '</span>')
});
}
});
break;
default:
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
And this is the form modal I'm using to fill the input fields with data:
<div class="modal_overlay_maincontainer closeable form_new_modal" data-link="sliders">
<form id="new_slider_form" class="modal_container" method="POST">
<i class="close fa fa-times-circle" title="Cerrar"></i>
<h2 class="modal_title">Nueva Diapositiva</h2>
<div class="modal_body_container">
<div class="modal_body_check_container">
<span class="modal_body_options_title">Visible</span>
<input class="modal_body_check" name="isVisible" type="checkbox" title="La diapositiva se subirá al pasador de diapositivas" required>
</div>
<div class="modal_body_check_container">
<span class="modal_body_options_title">Imagen</span>
<input type="file" name="image" required>
</div>
<input class="modal_input" type="text" name="title" placeholder="Titulo de la diapositiva" required>
<textarea class="modal_input_textarea" name="body" placeholder="Contenido de la diapositiva" required></textarea>
</div>
<div class="modal_footer_container">
<button class="modal_footer_add_button form_new_button" type="button" data-link="sliders" title="Crear nueva entrada">Crear</button>
<button class="modal_footer_reset_button form_reset_button" type="button" title="Resetear los campos">Reset</button>
</div>
</form>
</div>
Try
var form = $('new_slider_form').get(0);
$.ajax({
type: "POST",
async: true,
url: '/sliders',
data: $(form).serialize(),
success: function(data) {
$('.form_valid_container').html('<span class="form_valid_text">✓ ' + data.success + '</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
$.each(errors, function() {
$('.form_error_container').html('<span class="form_error_text">✘ ' + errors.message + '</span>')
});
}
});
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 have a form validation to validate my adding data into database. I am a beginner in using ajax/javascript. How could i display error in my view using ajax.
I have already json return from ajax by this code:
if ($validator->fails()) {
return response()->json(['errors' => $validator->messages(), 'status' => 422], 200);
}
in my view i have this:
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 {{ $errors->has('catname') ? ' has-error' : '' }}" style="padding-bottom: 10px;">
<input class="form-control" name="catname" placeholder="Category name" type="text" required />
#if ($errors->has('catname'))
<span class="help-block">
<strong>{{ $errors->first('catname') }}</strong>
</span>
#endif
</div>
</div>
how can i return the errors to make my input type display the error .
Here is my ajax.
function addCategoryAjax(e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.addcat') }}",
type: "POST",
data: $("#frmAddcategory").serialize(),
dataType: "JSON",
success: function(data) {
if(data.status == 422) {
for (var error in data.errors) {
$('.errors').append(data.errors[error] + '<br>');
}
}
}
});
}
function addCategoryAjax(e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.addcat') }}",
type: "POST",
data: $("#frmAddcategory").serialize(),
dataType: "JSON",
success: function(data) {
//if success
console.log(data);
alert('success');
},
error: function(data){
//if error
if(data.responseJSON == 422) {
$('.errors').html('');
for (var error in data.responseJSON) {
$('.errors').append(data.responseJSON[error] + '<br>');
}
}
}
});
}
Hello everyone I am newbie in java-script so i hope you can help me with my issue. So I have the form, it look something like this:
<form method="post">
Field1: <input type="text" name="field1"><br>
Field2: <input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
I need to take data from the form and make xml request, the xml request should look like this
<root>
<header section>
<section>data</section>
</header section>
<data section>
<field1>data</field2>
<field2>data</field2>
</data section>
</root>
After that i have to display xml response on the page.
I made xml request
<script>
$('.button').click( function() {
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
success: function(xml) {
$(xml).find('root').each(function(){
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
But I don't know how to take data from the form and make request. Can you help me with it? Thanks a lot.
// You can use jQuery to build XML document:
function buildXmlFromForm(form) {
var xml = $('<XMLDocument />');
xml.append (
$('<header-section />').append(
$('<section />').text('data')
)
).append (
$('<data-section />').append(
$('<field1 />').text(form.find("input[name='field1']").val())
).append(
$('<field2 />').text(form.find("input[name='field2']").val())
)
);
return xml.html();
}
// you should use POST or PUT method (not GET) to post xml-data to server side
$( "#form1" ).submit(function(event) {
event.preventDefault();
$("#results").append("<ul></ul>");
var xmlString = buildXmlFromForm($(this));
$("#xmlSrc").val(xmlString);
$.ajax({
type: "POST",
dataType: 'xml',
url: 'response.xml',
data: xmlString,
success: function(respData) {
$("<li></li>").html("ok: "+respData).appendTo("#results ul");
console.log(respData);
},
error: function(errorData) {
$("<li></li>").html("error: "+errorData.statusText).appendTo("#results ul");
console.log(errorData);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form1">
Field1: <input type="text" name="field1" value="***v1***"><br/>
Field2: <input type="text" name="field2" value="***v2***"><br/><br/>
<input type="submit" value="Submit">
</form>
<hr/>
<textarea id="xmlSrc" cols="70" rows="5"></textarea>
<div id="results"/>
Try this:
serialize will return formData of current form
You must have unique identifier for your form to be used as querySelector
$('#myForm').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
data: formData,
success: function(xml) {
$(xml).find('root').each(function() {
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="myForm">
Field1:
<input type="text" name="field1">
<br>Field2:
<input type="text" name="field2">
<br>
<input type="submit" value="Submit">
</form>
am using kendo inline and popup editing in a single grid
i used custom template for popup grid
<script id="customPopUpTemplate" type="text/x-kendo-template">
<form id="myForm" action="" method="post">
<div class="k-edit-field">
<input name="LoginName" class="k-textbox"/>
<span id="sta3" style="color: Red; font-size:medium;"> </span>
</div><div class="div">Login Name: </div>
`<div class="k-edit-field">`<br>
` <input name="Password" type="Password" class="k-textbox"/> `<br>
<span id="sta4" style="color: Red; font-size:medium ;"> * </span>
</div> <div class="div">Password: </div>
<div class="k-edit-field">
<input name="ScopeId"
data-bind="value:ScopeId"
data-value-field="ScopeId"
data-text-field="ScopeName"
data-source="DataSourceScopepopup"
data-role="dropdownlist" /> <span id="sta6" style="color: Red; font-size:medium ;"> </span>
</div>
<div class="div">Scope: </div>
</form>
var DataSourceScopepopup = new kendo.data.DataSource(
{
transport:
{
read:
{
url: "WebServices/Project.asmx/GetScopepopup",
data: "{}",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json'
},
parameterMap: function(options, operation)
{
if (operation == 'read')
return kendo.stringify(options);
}
},
schema:
{
data: function(Data)
{
return (Data.d);
},
model:
{
id: "ScopeName",
fields:
{
ScopeId: { type: "number"},
ScopeName: { type: "string"}
}
}
},
error: function(e)
{
var xhr = e[0];
var statusCode = e[1];
var errorThrown = e[2];
alert('DataSourceScope - ' + xhr + ', ' + statusCode + ', ' + errorThrown);
}
});
This is My coding How to Add the Default item --Select-- in dropdownlist?
Now i get only the Database items,,, how to i add it?
thanks in Advance!!
Add attribute data-option-label="--Select--" in your template
<input name="ScopeId"
data-bind="value:ScopeId"
data-value-field="ScopeId"
data-text-field="ScopeName"
data-source="DataSourceScopepopup"
data-role="dropdownlist"
data-option-label="--Select--" <!- display default value-->
/>
Since you are using a bound element, I would change either the SQL statement or the Service to add the value you want to the returned list of values.
Otherwise, you can use the databound event to add a new item to the list, something like this:
dataBound: function () {
if (DataSourceScopepopup.at(0). !== "--Select--") {
DataSourceScopepopup.insert(0, { ScopeId: 0, ScopeName: "--Select--" });
}