How to take value from textarea to textarea with Laravel + Jquery Ajax? - php

How do I take value from one textarea to another with laravel and jquery ajax.
I have this files so far.
Route:
Route::post('/post', 'PostController#post');
Controller:
class PostController extends Controller
{
public function post(Request $request)
{
$request->json()->all();
}
}
JQuery file:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(data);
}
});
});
});
and the html :
<textarea class="form-control" name="firsttextarea" rows="10" id="firsttextarea" ></textarea>
<button id="insert" class="btn btn-md btn-primary"><span class="glyphicon glyphicon-circle-arrow-right"></span>Insert</button>
<textarea class="form-control" name="secondtextarea" rows="10" id="secondtextarea" ></textarea>
When i push the button nothing happens.

First problem probably can be in CSRF Verify. You can disable it if it so or add {{ csrf_token() }}.
Then your post action should be looks like this:
public function post(Request $request)
{
return response()->json($request->all());
}
I checked it and it's work fine. but in textarea insert [Object object] because it JSON. You can add JSON.stringify in your Jquery script like this:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(JSON.stringify(data));
}
});
});
});

Try this, you're not returning a response in your Controller method.
class PostController extends Controller
{
public function post(Request $request)
{
return response()->json([
'data' => $request->get('intrare'),
]);
}
}
then, add this to your head in your blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
and replace your JS with the below:
$(function() {
// We need CSRF Token in our ajax request so we can
// validate the POST request
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
}
});
// Insert text from first textarea to the other textarea
$("#insert").on("click", function(e) {
e.preventDefault();
var intrare = $("textarea#firsttextarea").val();
$.ajax({
type: "POST",
url: "/post",
data: { intrare: intrare },
success: function(response) {
$("textarea#secondtextarea").val(response.data);
}
});
});
});

Related

AJAX POST Request not working in Laravel 5.6

While trying to use ajax request in my application using Laravel 5.6 I've found that the ajax request is not triggering.
My Controller code
class AjaxController extends Controller
{
function index(Request $request)
{
$msg = "Sample Messgae";
return response()->json(['msg' => $msg)]);
}
}
The Route,
web.php
Route::post('/message','AjaxController#index');
Route::get('/sample','UserRedirectController#ajaxRedirect');
The view
<input type="text" name="ajax" id="ajax">
<input type="text" name="_token" value="{{csrf_token()}}" id="token" hidden>
<button id="save" onclick="ajaxRequestFun();">Show</button>
<span id="cont"></span>
Finally the script
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
});
functon ajaxRequestFun()
{
$.ajax({
type : 'POST',
url : '/message',
data : {'_token': {{csrf_token()}} },
success:function(res){
alert("success");
}
});
}
</script>
Finally found some solution,
I've just added a meta tag to the view head tag just like.
<meta name="token" content="{{csrf_token()}}">
then at the JavaScript side formed the data to send using,
var pass= {'_token':$('meta[name="token"]').attr('content'),
'MessageContent': document.getElementById("message").value,
};
and initiated the ajax call normally with data: parameter as variable pass which I've created,
My ajax code is something like,
$.ajax({
type:'POST',
url:'{{url("/message")}}',
datatype:'json',
data: pass,
success:function(data){
$("#bubble").html(data);
}
}).fail(function(jqXHR, textStatus, error){
alert(jqXHR.responseText);
});
what I've found important is,
Use of the meta tag with the csrf_token() key
what else is as same as that of the other frameworks,

On button click perform ajax for sending values in forms are in while loop

How can I send input values through AJAX on button click? My code is below. Thanks in advance.
while
{
<form class="commentform">
<input type="hidden" class="proid" name="proid" value="<?=$rr['id']?>">
<input type="text" class="form-control" name="comval" placeholder="Write a comment.." autocomplete="off">
<button class="btn btn-post" type="button">Post</button>
</div>
</form>
}
$(document).ready(function() {
$(document).on('click', '.btn-post', function(){
var thePostID = $(this).val;
$.ajax({
url: 'fetch_comments.php',
data: { postID: thePostID },
type: 'POST',
success: function() {
alert(data);
}
});
Firstly, the correct method is $(this).val(), not just $(this).val.
Secondly, you can simplify your code by getting the data from the closest form element using serialize(). Try this:
$(document).on('click', '.btn-post', function() {
var $form = $(this).closest('form');
$.ajax({
url: 'fetch_comments.php',
data: $form.serialize(),
type: 'POST',
success: function() {
alert(data);
}
});
});
$("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.

Yii 2, Submit form using Ajax

I'm new to Yii and would appreciate any help.
I render the view with form:
public function actionCreate()
{
return $this->render('create');
}
view:
<form id="myform" action="/test/web/index.php?r=form/preorder" method="post">
<input type="text" id="form-firstname" name="Form[firstName]" required maxlength="50">
<input type="text" id="form-lastname" name="Form[lastName]" required maxlength="50">
<input name="send" type="submit" value="Отправить">
</form>
Im using plain html instead of Yii extensions in form, because I need to have a frontend with html/javascript only. On backend I can use Yii.
Now, I try to submit the form using ajax:
$(document).ready(function(){
$("body").on('beforeSubmit', 'form#myform', function(e){
var form = $(this);
$.ajax({
url : form.attr('action'),
type : 'POST',
data : form.serialize(),
success: function (response)
{
console.log(response);
},
error : function ()
{
console.log('internal server error');
}
});
return false;
});
});
FormController:
public function actionPreorder(){
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
$res = array(
'body' => $_POST,
'success' => true,
);
//also I need to save to db
return $res;
}
}
The problem is when I submit the form, it redirects to the new page preorder, and I can't see my posted data. Im not sure what Im doing wrong.
Ok, so the solution is to remove action from form:
<form id="myform" action="" method="post">
js:
$("#myform").submit( function(e){
var form = $(this);
$.ajax({
url : '/megogo/web/index.php?r=form/preorder',
type : 'POST',
data : form.serialize(),
success: function (response)
{
console.log(response);
},
error : function (e)
{
console.log(e);
}
});
return false;
})

Form needs to post data to a controller in codeigniter

I have a form,
<form>
<input id="amount" type="text" placeholder="Give amount" name="myamount"/>
<button class="btn btn-lg" type="submit" id="btn1" >FirstBTN</button>
<button class="btn btn-lg" type="submit" id="btn2">SecondBTN</button>
</form>
Which needs to post data to a function inside the controller. I am trying to make two buttons, post data to two different controller functions. And this is my jquery code written in html file (view):
<script type="text/javascript">
$('#btn1').click(function() {
$.ajax({
url: 'helloworld/firstmoney',
type: 'POST',
data: {'submit' : true ,myamount: $("#amount").val()},
success: function (result) {
}
});
});
</script>
<script type="text/javascript">
$('#btn2').click(function() {
$.ajax({
url: 'helloworld/secondmoney',
type: 'POST',
data: {'submit' : true ,myamount: $("#amount").val()},
success: function (result) {
}
});
});
</script>
Here is the controller but I am not getting any values in my controller..
public function firstmoney(){
$this->load->helper('form');
$Money = $this->input->post("myamount");
$data = array(
'Money' => $Money
);
$this->load->view("page1", $data);
}
public function secondmoney(){
$this->load->helper('form');
$Money = $this->input->post("myamount");
$data = array(
'Money' => $Money
);
$this->load->view("page2", $data);
}
my controller name is helloworld and I need to assign values in $money but I cant get it working. I am a beginner programmer so please do tell me what steps I should follow.
First, your AJAX should look like this one.
$('#btn2').click(function() {
$.ajax({
url: 'helloworld/secondmoney',
method: 'POST',//not type
data: { myamount: $("#amount").val() }//no need for submit variable (although you can use it) since this will be submitted on click; no quotes over variables
})
.done(function(result)) {
//do your stuff on response
});
});
Second: no need for ajax and you should use classic form with post method because you are making redirection in controller/method where data is posted to.
AJAX requires JSON formated response, and it is not in this case. So wether change view to have form with method and action, wether change controller/method to return JSON string back to AJAX.
var base_url= '<?php echo base_url() ?>';
url: base_url+'helloworld /firstmoney',
You can try another way to do that
Try below code
form
<form action="" method="post" id="myform">
<input id="amount" type="text" placeholder="Give amount" name="myamount"/>
<button class="btn btn-lg" type="submit" id="btn1" >FirstBTN</button>
<button class="btn btn-lg" type="submit" id="btn2">SecondBTN</button>
</form>
Then you can add jquery to change the form action on submit button clicks
like below
<script type="text/javascript">
$('#btn1').click(function() {
$('#myform').attr('action', 'Your domain/Your controller/firstmoney');
});
$('#btn2').click(function() {
$('#myform').attr('action', 'Your domain/Your controller/secondmoney');
});
</script>
Now your form will call firstmoney() if you click #btn1 and it will call secondmoney() if you call #btn2
And you can get form data using
$this->input->post('myamount');
If you only want to print $_POST data then apply this code for btn1.
$(document).ready(function(){
$('#btn1').click(function() {
event.preventDefault();
$.ajax({
url: "<?php echo base_url(); ?>" + "helloworld/firstmoney",
type: 'POST',
data: {'submit' : true ,myamount: $("#amount").val()},
success: function (result) {
$("body").html(result);
}
});
});
});
In your helloworld controller
public function firstmoney(){
$Money = $this->input->post("myamount");
$data = array(
'Money' => $Money
);
$data = $this->load->view("page1", $data, TRUE); //it will return that page and save it in $data
}
In you page1.php view write the following code
<?php
echo $Money;
?>
<script type="text/javascript">
$('#btn1').click(function() {
$.ajax({
url: 'helloworld/firstmoney',
type: 'POST',
data: {'submit' : true ,myamount: $("#myamount").val()},
success: function (result) {
}
});
});
Keep the id and name value as myamount in above input tag and change in the jquery code also

How to use ajax post method inside another function?

I am trying to submit a form using ajax post.Before that i am checking that all the form data are correct, if so the form will be submitted.Can any body tell me why the form is not submitting ?
HTML:
<form id="formElem" name="formElem" action="" method="post">
<fieldset class="step">
<legend>Account</legend>
<p>
<label for="password">Password</label>
<input type="password" name="uPassword" id="uPassword" value="<?=$uPassword;?>" AUTOCOMPLETE=OFF />
</p>
<p>
<label for="password">Verify Password</label>
<input type="password" name="uVPassword" id="uVPassword" value="<?=$uVPassword;?>" />
</p>
<p class="submit">
<button id="registerButton" type="submit">Register</button>
</p>
</fieldset>
</form>
jQuery code :
$('#registerButton').bind('click', function () {
if ($('#formElem').data('errors')) {
alert('Please correct the errors in the Form');
return false;
} else {
$(function () {
$("#formElem").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
});
}); ///end of func
return true;
}
});
Why do you have event.preventDefault(); in the beginning of your submit function? It seems that that's the problem.
You don't need the click handler, in the submit handler you can check for the validity
jQuery(function ($) {
$("#formElem").on("submit", function (event) {
event.preventDefault();
if ($(this).data('errors')) {
return;
}
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
});
})
You can call ajax on click of button. For any error it will go in to the if condition otherwise submit the form successfully..
$('#registerButton').bind('click', function () {
if ($('#formElem').data('errors')) {
alert('Please correct the errors in the Form');
return false;
}
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
return true;
}); ///end of func
$(function() { /*code here */ }); That execute the function when the DOM is ready to be used. This means that this function is assigned to the event onDocumentReady that occurs only once (when the page loads), and you assign a function after this event, so never execute.
It's the same with this function $("#formElem").on("submit", function (event) {}); Do not tell her immediately but do you create a handle to the event onSubbmit.

Categories