Laravel Query Ajax Update - javascript

Hello someone can you explain me how to update with Ajax!!
I use laravel
I want html and ajax only
My routes
Route::post('/post/homepage', 'AdminController#HomePage');

First, you should name your route:
Route::post('/post/homepage', 'AdminController#HomePage')->name('post.create');
Then, create your HTML form :
<form id="myForm">
{{csrf_field()}}
<label for="name">Article Name :</label>
<input id="name" name="articleName" type="text" required>
<button type="submit">Save</button>
</form>
Note: {{csrf_field()}} will generate the Form CSRF field. Or you can use instead :
<input type="hidden" name="csrf_token" value="{{csrf_token()}}">
I'll use jQuery to handle ajax:
<script type="text/javascript">
$(document).ready(function (){
$('#myForm').submit(function (e) {
e.preventDefault(); //Do not submit the form
var dataflow=$(this).serialize(); //Get the inputs value
$.post('{{route('post.create')}}', dataflow, function (data){ //post.create is the route name
//The request is done, do something with the server response
});
});
});
</script>

Related

Submit Form With Both Action and Onsubmit Function

My JS is not that great so I have been fiddling with this for a while now.
I have a form which is being POST to another file when the submit button is clicked. When it is clicked I also want to show an alert then redirect the user back to a URL.
The redirecting code works just fine on a button where I call the function "onclick" like so:
<button onclick="test()">Return</button>
But I don't want to have an extra button for this...I want the form to POST then show an alert box then go to URL specified but I get not a function error from console, thanks.
<iframe name="noreloadhack" style="display:none;"></iframe>
<form action="http://www.example.com/test.php" onsubmit="return test();" method="post" target="noreloadhack">
JS:
<script>
function test() {
alert('Hello World');
var return_url = document.getElementById('return_url').value;
window.location.href= return_url;
}
</script>
If it makes a difference I have the form target set to a hidden iframe as a hack to not reload page on submit (I know, not the best method). I'm pretty much using 4 form attributes here.
I have some old code that I used to solve a similar situation. Where I wanted to submit a form but not reload the page, here it is. Since there were only 4 input fields I just grabbed the values using jquery.
Javascript:
function processForm() {
var teamMembers=new Array();
console.log($("#"));
var schoolName=$("#schoolname").val();
var teamMembers=new Array();
teamMembers.push($("#contestant1").val());
teamMembers.push($("#contestant2").val());
teamMembers.push($("#contestant3").val());
$.ajax({
method: "POST",
url: "php/register.php",
data: { schoolname: schoolName, teammembers:teamMembers.toString()}
})
.done(function( msg ) {
alert( "Your team is now registered " + msg );
$('#register').hide();
location.reload();
});
// You must return false to prevent the default form behavior
// default being reloading the page
return false;
}
HTML:
<form id="registration_form" onsubmit="return processForm()" method="POST">
<p style="margin:0px;">School Name:</p>
<input type="text" id="schoolname" name="schoolname" autocomplete="off" class="input" required>
<hr>
<p style="margin:0px;">Contestants</p>
<div id="teammembers">
<input type="text" id="contestant1" name="contestant1" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant2" name="contestant2" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant3" name="contestant3" autocomplete="off" class="input" required>
</div>
<input type="submit" id="registered">

Request is being sent to server twice

I am submitting a form to server using following method:
HTML Form
<form class="navbar-search pull-left" onsubmit="return mera()">
<input placeholder="Search" class="search-query span2" name="query" type="text" id="query" style="width:300px">
</form>
Method
<script>
function mera() {
alert('this is something!');
var query = document.getElementById('query').value;
window.location = '../Translation/Search_Query?query=' + query;
return false;
}
</script>
It sends request twice to server on single submission. But shows alert only once for first time. How to fix it ?
You dont need javascript. Simply use GET method
HTML :
<form class="navbar-search pull-left" method="GET" action="../Translation/Search_Query">
<input placeholder="Search" class="search-query span2" name="query" type="text" id="query" style="width:300px">
</form>
When you submit the form, this will become :
http://example.com/Translation/Search_Query?query=query
Hope this makes sense.
Try this
<script>
function mera() {
alert('this is something!');
var query = document.getElementById('query').value;
window.location = '../Translation/Search_Query?query=' + query;
return true;
}
</script>
<form class="navbar-search pull-left" onsubmit="return mera();">
why dont you change you code a bit. only thing is it will post the value instead of get.
<form class="navbar-search pull-left" action="../Translation/Search_Query">
it will submit your value once you submit the form.
Note : you might need to change the action as per your servlet mapping.
UPDATE
<script>
function mera() {
document.getElementById('testForm').submit();
}
</script>
<form id="testForm" class="navbar-search pull-left" onclick="mera();" method="GET" action="../Translation/Search_Query">

javascript function call for single form

I have multiple forms in my php file for different buttons. So, if I click on Back button, ramesh.php script should be called and so on. This is the code.
<form action="ramesh.php">
<input type="submit" value="Back" />
</form>
<form action="process.php" method="post">
<input name="rep_skyline" type="text" />
<input type="submit" />
</form>
<form action="update.php" method="post" >
<button type="submit">Update</button>
</form>
However, I need to pass some data to server from my client side on form submit just for the update button. I have a javascript function to send the data to server side as below.
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e) {
var mydata = 3;
if ($(this).is(':not([data-submit="true"])'))
{
$('form').append('<input type="hidden" name="foo" value="'+mydata+'">');
$('form').data('submit', 'true').submit();
e.preventDefault();
return false;
}
})
})
</script>
If I click on the update button, the javascript function is working fine. However, if I click on Back or Submit button, I should not be calling the javascript function. Is there someway to do this?
Give your form an id:
<form action="update.php" method="post" id="update-form">
Then use a more specific selector:
$("#update-form").submit(function() {
// Code
});
I'm not quite sure why you need JavaScript to dynamically add data to your form, however. You should just use an <input type="hidden" /> directly.
type=submit will always load the form's action. Try to specify wich form to submit.
<form name="backForm" id="backForm" action="ramesh.php">
<input type="submit" value="Back" />
</form>
<form name="form2" id="form2" action="process.php" method="post">
<input name="rep_skyline" type="text" />
<input type="submit" />
</form>
Now you can access the form via document.backForm or document.getElementById("backForm") and than use submit(); like document.getElementById("backForm").submit();

javascript Submit multiple forms with one button

In my html I have multiple forms (text inputs, radio buttons, check boxes and select) and one button. I would like to fill all these forms and send values to my php file. For now I am trying to submit values from text input and select but I am stuck at this point.
I have a js submit file:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
And my forms are like this:
SELECT:
<form id ="form1" name="dists" action="solve.php" method="post">
<select id="demo" name="sadzba" onchange="selectElement1(this.value)>
<option value="">-- vyberte oblasť --</option>
</select>
</form>
Text input form + button:
<form id="form2" action="solve.php" method="post">
<input type="text" name="spotVT" ><label>kWh za rok VT</label>
<div id="nt" style='display:none'><input type="text" name="spotNT" ><label>kWh za rok NT</label></div>
</form>
<input id="sub" type="button" value="Ok" style="margin-left:15px;" onclick="submitForms()"/>
But this is not working. Can you help me please? Thank you
Once you are submitting one form your page reloads or terminates the javascript after that submission of form so better use Ajax for submitting multiple forms at the same time
with jquery
$("#sub").click(function(){
$("form").each(function(){
var fd = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "solve.php",
data: fd,
processData: false,
contentType: false,
success: function(data,status) {
//this will execute when form is submited without errors
},
error: function(data, status) {
//this will execute when get any error
},
});
});
});
Above code will submit every form when you click a button with id sub
It will be easier to only submit one form. You can give your select and input tag the same form name by assigning form="your-form-id".
Here's an simple example of a native Javascript implementation.
<!DOCTYPE html>
<html>
<head>
<title>Multiform - JAVASCRIPT</title>
</head>
<body>
<fieldset>
<legend>Form 1</legend>
<form name="f1" id="f1" onsubmit="return validate(this)">
<input type="text" name="username" placeholder="Username" />
</form>
</fieldset>
<fieldset>
<legend>Form 2</legend>
<form name="f2" id="f2" onsubmit="return validate(this)">
<input type="text" name="email" placeholder="Email" />
</form>
</fieldset>
<fieldset>
<legend>Form 3</legend>
<form name="f3" id="f3" onsubmit="return validate(this)">
<input type="text" name="password" placeholder="Password" />
</form>
</fieldset>
<button onclick="submitAll();">SUBMIT ALL</button>
<script>
'use strict';
function validate(form){
//forms processsing goes here...
console.log(form, form.name)
return false;
}
function submitAll(){
for(var i=0, n=document.forms.length; i<n; i++){
document.forms[i].onsubmit();
}
}
</script>
</body>
</html>
You could try this. If submitting all forms is fine for your page
$('form').submit();
Function that's in actual use:
function trySubmitAllForms() {
if ($('.saveSpinner').is(':visible')) {
return;
}
if ($('form').valid()) {
$('.saveSpinner').show();
$('form').submit();
} else {
showValidationErrorMessages();
}
}
Bismillah, try our method below, insyaAllah we hope can provide a solution for you.
document.getElementById("submit").addEventListener("click", function () {
$(function () {
$("#formid01").delay(300).submit();
$("#formid02").delay(300).submit();
});
});

Force form field value on page load & submit

How could I force a specific value within a form field on page load; and have that value 'Submit' with JavaScript or jQuery?
I tried the below; but no cigar.
<script>
window.onload = function(){
document.forms['coolform'].submit()
}
</script>
Mark-Up.
<form id="search" name="coolform" class="navbar-form form-search" action="#">
<div class="input-append">
<input id="query" type="text" class="search-query" value="Bars" >
<button type="submit" class="btn"><i class="icon-search"></i></button>
</div>
Try the following (jQuery):
$(function(){
var s = $('#search');
$('#query', s).val('The value you want to force in.');
s.submit();
});
HTML:
<input id="query" name="query" type="text" class="search-query" value="Bars" >
you could use ajax to submit the value on document.ready...
$(document).ready(function(){
var query = $('#query').value;
$.ajax({
url:'url/to/your.php',
data:'query='+query,
success:function(data){
//handle response
}
});
});
You need a name attribute on the form field, otherwise it won't be included when the form is submitted:
<input id="query" name="query" type="text" class="search-query" value="Bars" >

Categories