Getting different results from the same form in laravel - php

I'm trying to create an ajax form using laravel. The display is a table with names and next to the names are buttons enclosed by forms to do actions.
Here is the html:
<div style="margin-top: 100px;">
<h2>Character settings</h2>
<table class="table table-striped table-bordered table-hover">
<tr>
<th>Name</th>
<th>Map</th>
<th>Move</th>
</tr>
#foreach($chars as $char)
<tr>
<td>{{$char['name']}}</td>
<td>{{$char['map']}}</td>
<td>
{{Form::open(array('action' => 'UsersController#move', 'id' => 'mover'))}}
<input type="hidden" name="charID" id="charID" value="{{$char['id']}}" />
<button type="submit" class="btn btn-small btn-info">Move</button>
{{Form::close()}}
</td>
</tr>
#endforeach
</table>
Here is the javascript ajax processing:
$('#mover').on('submit', function(e){
e.preventDefault();
var $form = $( this ),
method = $form.attr( "method" );
$.ajax({
url: "{{action('UsersController#move')}}",
dataType: "json",
data: $('#charID').val(),
type: method,
success: function (response) {
console.log(reponse['test']);
}
});
});
Here is the controller:
public function move() {
return Response::json(array('test' => 'test'));
exit();
}
The table looks like:
Image here
If I click the first button for Sambte, it works and I see "test" in the console. But when I click the 2nd link it doesn't send as ajax and sends me to a new page with the json object as the content of that page so I see {"test":"test"} in the new page it brought me to.
I can't figure out what's wrong. Hopefully its a small error somewhere.
Thank you

ID's are unique, you need to use a class on the form instead.
'class' => 'mover'
Then just use the class instead of the ID in the selector
$('.mover')
Sidenote, the same needs to be done for the charID, here's how I'd tackle that:
class="charID"
then, in your submit handler:
data: $form.find('.charID').val()

$(document).on('submit','.mover', function(e){
e.preventDefault();
var $form = $( this ),
method = $form.attr( "method" );
$.ajax({
url: "{{action('UsersController#move')}}",
dataType: "json",
data: $(this).serialize(),
type: method,
success: function (response) {
console.log(reponse['test']);
}
});
});
change id=mover to class=mover

Related

How to write an ajax script to delete an entry?

Good day!
Please tell me how to correctly implement the method of deleting a record of Laravel through Ajax. I wrote a script, but somehow it works very crookedly.
The script from the part works, but when you click on the delete button, the record does not disappear. It disappears only after reloading the page. And when I try to delete a fresh record, a route error just flies.
Route
Route::delete('/id{id}/delete', 'ProfileController#delete')->name('deletePost');
Form
<form action="{{route('deletePost', ['id' => $post->id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-outline-dark btn-sm mt-4">Удалить</button>
</form>
And my script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#delete').on('click', function(e) {
e.preventDefault();
var $this = $(this),
data = $this.data();
$.ajax({
url: "{{route('deletePost', ['id' => $post->id])}}",
method: 'POST',
data: data,
success: function(data) {
$( data ).remove();
},
error: function(d) {
console.log(d);
}
})
})
</script>
You must first remove the ID from the route:
Route::delete('/id/delete', 'ProfileController#delete')->name('deletePost');
You must assign a class name to each html record(or row).
Like the following code:
<table>
<tbody>
#foreach($records as $record)
<tr class="myRow">
...
</tr>
#endforeach
</tbody>
</table>
Also, it is better to create a hidden input in each deletion form to hold the record ID. Like the following:
<form method="post" id="formDelete">
<input type="hidden" name="id" value="{{$record->id}}">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-outline-dark btn-sm mt-4">Удалить</button>
</form>
Then, when a record is deleted by Ajax, you must delete the corresponding row by the specified class name in the success section of ajax code. Like the following code:
var data = $(this).closest("form").serialize();
$.ajax({
url: "{{route('deletePost')}}",
method: 'POST',
data: data,
success: function(data) {
$(this).closest("#myRow").remove();
},
error: function(d) {
console.log(d);
}
})
I hope it helps

How to run a first instance of ajax jquery when page loads

I have a jquery and ajax that performs a query and shows a table when a button is clicked. The problem is that when the page loads for first time, the query not run and do not shows anything, so the button has to be clicked to start showing the query result.
Is there a way that the query runs when page loads? and then just use the button.
My code is:
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
Thanks in advance!
Just call click() on the element to simulate a click.
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}).click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
You could extract the function you're calling in the click handler and call it within ready.
$(document).ready(function() {
const displayContent = () => {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}
displayContent();
$("#display").click(displayContent());
});

Angular JS with PHP with Input field and Submit Button

I have UI with Input field and Submit Button,And After Entering Number in field and clicking on Submit Button. I want this to go to first.php file and second.php depends on the first.php response. At the end I want to show to value from second.php, Can you please help me on this.
And I am using AngularJS with PHP And I am creating 2 functions with in one controller and calling 2 functions at time by clicking on button Can you please suggest me on the approach?
HTML Code
<html>
<div ng-controller="get_controller">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="sendAccountNumber();geValues()" class="btn btn-primary">Submit</button>
</span>
</div>
<div ng-controller="get_controller">
<table>
<tbody>
<tr>
<th ng-repeat="list in personDetails">{{list.Name}}
</th>
</tr>
<tr>
<td class="features" ng-repeat="list in personDetails">{{list.Location}}
</td>
</tr>
</tbody>
</table>
</div>
</html>
AngularJS
var app = angular.module('myApp', ["ngTable"]);
app.controller('get_controller', function($scope, $http) {
$scope.sendAccountNumber = function() {
var request = $http({
method: "post",
url: "first.php",
data: {
accountnumber: $scope.accountnumber
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
/* Check whether the HTTP Request is successful or not. */
request.success(function(data) {
console.log("Account Number " + data + " Sent to first.php");
});
}
$scope.geValues = function() {
$http({
method: 'POST',
url: 'second.php'
}).success(function(data) {
$scope.post = data;
$scope.personDetails = Employee;
})
},
});
You can call your next function call in the promise of the first call in the following way:
//First function
$scope.firstFunction = function(){
$http({
method: 'POST',
url: 'first.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
}).then(
function (response) {
var data = response.data;
$scope.secondFunction(data);
// not relevant
}, function (error) {
var data = error.data;
// not relevant
});
}
//Second function
$scope.secondFunction = function(data)
{
$http({
method: 'POST',
url: 'second.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
}).then(
function (response) {
var newData = response.data;
// not relevant
}, function (error) {
var newData = error.data;
// not relevant
});
}
And call a one function firstFunction() on button click only.
<button type="button" ng-click="firstFunction();" class="btn btn-primary">Submit</button>
FYI,
I would recommend to use ng-submit() event for form to submit the form data rather then submitting by submit event of your form.
And one more thing, why would you request two ajax calls ?
You can do both the server side operations in single call only.
Hope this helps you :)

Ajax multiple input not showing all data?

I'm stuck in multiple input. My code is not showing all data. below is the html I am using:
<form id="matkul" class="form-horizontal" method="POST">
<table class="table table-condensed">
<thead>
<tr>
<th>Matakuliah</th>
<th>Data Lain</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<button id="post" type="submit">Save</button>
<button id="get">Get Data!</button>
below is the code to get the data
<script>
$(document).ready(function() {
$("#get").click(function() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22https%3A%2F%2Funisys.uii.ac.id%2Fuii-ras%2Fmatakuliah.asp%3Fidx%3D1%26session_id%3DxxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511%26no_mhs%3D%22&format=json';
$.getJSON(url,
function(data) {
var id = data.query.results.body.table.tr.td.table.tr[2].td.table.tr;
for (var i = 1; i <= id.length; i++) {
$("<tr> <td> <input name='fmatakuliah' value='"+id[i].td[1].a.content+"'> </td> <td> <input name='fdata' value='" + id[i].td[1].a['href'] + "'> </td> </tr>").appendTo("#matkul tbody");
};
});
});
});
</script>
from the above code output will be
Matakuliah Data Lain
StringOne OtherData
StringTwo OtherData
below is the ajax post code, but when it is already sending the data, the alert does not show all the data
<script type="text/javascript">
$(document).ready(function(){
$("#post").click(function(){
string = $("form").serialize();
alert(string); // this alert is normal, show all data
$.ajax({
type: "GET",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});
});
});
</script>
below is the code on save.php
print_r($_GET);
The latest response is showing like this
Array
(
[fmatakuliah] => Wide Area Network
[fdata] => matakuliahdetail.asp?session_id=xxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511&mk=52323605&kur=2010
)
My question is how to show all data and save it to the database?
It looks like you need to change the AJAX type from GET to POST:
$.ajax({
type: "POST",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});

jquery post form

I have this code for send simple data using jquery , but no works , all time reload de page and no load contents i send by post
My code it´s this :
<script>
$(document).ready(function() {
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "indexer_adm.php?send_order2=ok",
success: function(data){
$("#load_order").html(data);
}
});
return false;
});
</script>
<form name="forma" id="form_order" method="post" action="">
<table width="100%" border="1">
<tr>
<td height="30" align="center" valign="middle">
<select name="select_order">
<option value="articles">Articles</option>
<option value="blogs">Blogs</option>
<option value="products">Products</option>
</select>
<input type="submit" name="Submit" value="Acceder">
<input type="hidden" name="send_order2" value="ok">
<input type="hidden" name="action_load" value="<?php echo $_REQUEST['action_load'];?>">
</td>
</tr>
<tr>
<td height="30" align="center" valign="middle"> </td>
</tr>
</table>
</form>
<div id="load_order"></div>
In the div called load_order , it must load the result of this send by post from the form , but the page reload and no works , i see the code many times but i don´t understand what happen
Thank´s for All
There is a syntax error in your code, you haven't closed the submit handler.
$(document).ready(function() {
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "indexer_adm.php?send_order2=ok",
success: function(data){
$("#load_order").html(data);
}
});
return false;
}); // <---
});
Try returning false inside of the submit block, rather than of the ready block.
You may have a syntax error since return false should stop the form from refreshing. I would use the post function instead:
<script>
$(function() {
$("#form_order").submit( function () {
$.post('indexer_adm.php?send_order2=ok', $(this).serialize(), function(data) {
$("#load_order").html(data);
});
return false;
});
</script>
Ok !!! , Thank´s everybody
The Right code :
<script>
$(document).ready(function() {
/*
$("#load_order").show(1000);
$("#load_order").load("<?php print "".$ruta_path_adm."".$ruta_modulos."/mod_order/indexer_adm.php?send_order2=ok";?>");
*/
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "<?php print "".$ruta_path_adm."".$ruta_modulos."/mod_order/indexer_adm.php?send_order2=ok";?>",
success: function(data){
$("#load_order").html(data);
}
});
return false;
});
});
</script>
Thank´s for the help i put bad the script and no see this , thank´s

Categories