Laravel 8 and ajax - javascript

Never used ajax before and I'm quite new to Laravel as well.
I'm running a function where it gets the information from the form and i have no idea how to do the request with the information that I need.
function myFunction() {
var x = document.getElementById("frm1");
//console.log(x.elements.personSearch.value);
var details = x.elements.personSearch.value;
document.getElementById("personValidation").innerHTML = "";
if (
!details.match(
/\b[a-zA-Z ]*\\[a-zA-Z ]*\\[0-3][0-9][0-1][0-9][0-9]{4}\b/g
)
) {
document.getElementById("personValidation").innerHTML =
"Your search does not match the required format";
return;
}
$.ajax({
url: "/api/pnc/person",
type: "POST",
dataType: "json",
success:function(amount) {
console.log(amount);
}
});
``` Javascript
public function person(Request $request)
{
$request->validate([
'search' => 'required'
]);
return "test";
}

You need to Follow 3 steps for Ajax Request-
1. Setup Ajax Header bottom of your code. I mean before </html> add below code.
<script>
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
2. If you don't use Header Then you can use.
<script>
$(document).ready(function () {
$("#your_form_id").submit(function(e) {
var details = $('#details_input_id').val();
if(your_condition){
$.ajax({
url: "api/url",
type: "post",
data: {"_token": "{{csrf_token()}}", 'details':details},
success:function(data){
//Your response
if(data){
consol.log("Print what you want to print");
}
}
});
}else{
alert("Your search does not match the required format")
}
});
});
</script>
3. Your Route will be like ajax url
Route::post('api/url', [YourController::class, 'functionName'])->name('functionName');

Related

Refresh data without reloading the page

I have a function for adding likes on the page
blade.php
<a href="/article/{{ $article->id }}?type=heart" class="comments-sub-header__item like-button">
<div class="comments-sub-header__item-icon-count">
{{ $article->like_heart }}
</div>
<a href="/article/{{ $article->id }}?type=finger" class="comments-sub-header__item like-button">
<div class="comments-sub-header__item-icon-count">
{{ $article->like_finger }}
</div>
js
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
});
$('.like-button').on('click', function(event) {
event.preventDefault();
let href = $(this).attr('href');
$.ajax({
url: href,
type: 'POST',
success: function() {
window.location.reload();
},
});
});
});
But when I click on the like to update the data, I reload the page using window.location.reload();
Can this somehow be done without reloading the page?
This is how adding likes is implemented, they are added to cookies and stored for 24 hours
web routes
Route::post('article/{id}', 'App\Http\Controllers\ArticleController#postLike');
Article controller
public function postLike($id, Request $request) {
$article = Article::find($id);
if(!$article){
return abort(404);
}
$type = $request->input('type');
if ($article->hasLikedToday($type)) {
return response()
->json([
'message' => 'You have already liked the Article '.$article->id.' with '.$type.'.',
]);
}
$cookie = $article->setLikeCookie($type);
$article->increment("like_{$type}");
return response()
->json([
'message' => 'Liked the Article '.$article->id.' with '.$type.'.',
'cookie_json' => $cookie->getValue(),
])
->withCookie($cookie);
}
Article model
public function hasLikedToday(string $type)
{
$articleLikesJson = Cookie::get('article_likes', '{}');
$articleLikes = json_decode($articleLikesJson, true);
if (!array_key_exists($this->id, $articleLikes)) {
return false;
}
if (!array_key_exists($type, $articleLikes[$this->id])) {
return false;
}
$likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$this->id][$type]);
return ! $likeDatetime->addDay()->lt(now());
}
public function setLikeCookie(string $type)
{
$articleLikesJson = Cookie::get('article_likes', '[]');
$articleLikes = json_decode($articleLikesJson, true);
$articleLikes[$this->id][$type] = now()->format('Y-m-d H:i:s');
$articleLikesJson = json_encode($articleLikes);
return cookie()->forever('article_likes', $articleLikesJson);
}
Assuming those DIVs hold the number of hearts, if the response of the target page is the new number of hearts then:
success: function(data) {
targetElement.find(".comments-sub-header__item-icon-count").html(data)
}
elsewhere if you want to add +1 to current number regardless of server response:
success: function() {
var current= parseInt(targetElement.find(".comments-sub-header__item-icon-count").html());
targetElement.find(".comments-sub-header__item-icon-count").html(current+1)
}
Footnote: as the ajax request is nested inside the click function, the targetElement in my codes is the clicked element. You may get it in defferent ways e.g.
$('.like-button').on('click', function(event) {
var targetElement=$(this);
....
}
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
});
$('.like-button').on('click', function(event) {
event.preventDefault();
let href = $(this).attr('href');
$.ajax({
url: href,
type: 'POST',
success: function(response) {
$(this).parent(".comments-sub-header__item-icon-count").html(
parseInt($(this).parent(".comments-sub-header__item-icon-count").html()) + 1
)
// or return like or heart count from server
$(this).parent(".comments-sub-header__item-icon-count").html(response)
},
});
});
});
This should work for you
$(function () {
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
},
});
$(".like-button").on("click", function (event) {
event.preventDefault();
const likeBtn = $(this);
$.ajax({
url: likeBtn.attr("href"),
type: "POST",
success: function () {
let currentCount = likeBtn.next().text();
likeBtn.next().text(parseInt(currentCount) + 1);
},
});
});
});
You can simply add the new count to the response from your controller.
return response()
->json([
'message' => 'Liked the Article '.$article->id.' with '.$type.'.',
'cookie_json' => $cookie->getValue(),
'new_count' => $article->{"like_{$type}"},
])
->withCookie($cookie);
Now you can use the updated count as new_count from the database.
$.ajax({
url: href,
type: 'POST',
success: function (response) {
$(this).next().text(response.new_count)
},
});

How to run JavaScript code on Success of Form submit?

I have an Asp.Net MVC web application. I want to run some code on the successful response of the API method which is called on form submit.
I have the below Code.
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", id = "formID" }))
{
}
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
FunctionToBeCalled(); //JS function
}
}
But FunctionToBeCalled() function gets called before the APIMethod(), but I want to run the FunctionToBeCalled() function after the response of APIMethod().
So I made the below changes by referring this link. But now the APIMethod is getting called twice.
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
//Some custom javasctipt valiadations
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
function FunctionToBeCalled(){alert('hello');}
So I am not able to solve the issue.
If you want to execute some work on success, fail, etc. situation of form submission, then you would need to use Ajax call in your view. As you use ASP.NET MVC, you can try the following approach.
View:
$('form').submit(function (event) {
event.preventDefault();
var formdata = $('#demoForm').serialize();
//If you are uploading files, then you need to use "FormData" instead of "serialize()" method.
//var formdata = new FormData($('#demoForm').get(0));
$.ajax({
type: "POST",
url: "/DemoController/Save",
cache: false,
dataType: "json",
data: formdata,
/* If you are uploading files, then processData and contentType must be set to
false in order for FormData to work (otherwise comment out both of them) */
processData: false, //For posting uploaded files
contentType: false, //For posting uploaded files
//
//Callback Functions (for more information http://api.jquery.com/jquery.ajax/)
beforeSend: function () {
//e.g. show "Loading" indicator
},
error: function (response) {
$("#error_message").html(data);
},
success: function (data, textStatus, XMLHttpRequest) {
$('#result').html(data); //e.g. display message in a div
},
complete: function () {
//e.g. hide "Loading" indicator
},
});
});
Controller:
public JsonResult Save(DemoViewModel model)
{
//...code omitted for brevity
return Json(new { success = true, data = model, message = "Data saved successfully."
}
Update: If SubmitButton calls a JavaScript method or uses AJAX call, the validation should be made in this method instead of button click as shown below. Otherwise, the request is still sent to the Controller without validation.
function save(event) {
//Validate the form before sending the request to the Controller
if (!$("#formID").valid()) {
return false;
}
...
}
Update your function as follows.
$('#formID').submit(function (e) {
e.preventDefault();
try{
$.validator.unobtrusive.parse("form");
if ($(this).valid()) {
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
catch(e){
console.log(e);
}
});
Check the browser console for fetching error. The above code will prevent of submitting the form.
I think line $.validator.unobtrusive.parse("form") were throwing error.
For that use you need to add the following jQuery libraries.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
I think you should remove razor form tag if you want to post your form using ajax call and add post api URL directly to ajax request instead of getting it from your razor form tag using id:
Here is the revised version of your code :
<form method="post" id="formID">
<!-- Your form fields here -->
<button id="submit">Submit</button>
</form>
Submit your form on button click like:
$('#submit').on('click', function (evt) {
evt.preventDefault();
$.ajax({
url: "/Configuration/APIMethod",
type: 'POST',
dataType : 'json',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
});
function FunctionToBeCalled(){alert('hello');}
You need to use Ajax.BeginForm, this article should help [https://www.c-sharpcorner.com/article/asp-net-mvc-5-ajax-beginform-ajaxoptions-onsuccess-onfailure/ ]
The major thing here is that I didn't use a submit button, I used a link instead and handled the rest in the js file. This way, the form would nver be submitted if the js file is not on the page, and with this js file, it initiates a form submission by itself rather than th form submitting when the submit button is clicked
You can adapt this to your solution as see how it respond. I have somthing like this in production and it works fine.
(function() {
$(function() {
var _$pageSection = $('#ProccessProductId');
var _$formname = _$pageSection.find('form[name=productForm]');
_$formname.find('.buy-product').on('click', function(e) {
e.preventDefault();
if (!_$formname.valid()) {
return;
}
var formData = _$formname.serializeFormToObject();
//set busy animation
$.ajax({
url: 'https://..../', //_$formname.attr('action')
type: 'POST',
data: formData,
success: function(content) {
AnotherProcess(content.Id)
},
error: function(e) {
//notify user of error
}
}).always(function() {
// clear busy animation
});
});
function AnotherProcess(id) {
//Perform your operation
}
}
}
<div class="row" id="ProccessProductId">
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", name="productForm" id = "formID" })) {
<li class="buy-product">Save & Proceed</li>
}
</div>

No data receive in Jquery from php json_encode

I need help for my code as i have been browsing the internet looking for the answer for my problem but still can get the answer that can solve my problem. I am kind of new using AJAX. I want to display data from json_encode in php file to my AJAX so that the AJAX can pass it to the textbox in the HTML.
My problem is Json_encode in php file have data from the query in json format but when i pass it to ajax success, function(users) is empty. Console.log also empty array. I have tried use JSON.parse but still i got something wrong in my code as the users itself is empty. Please any help would be much appreciated. Thank you.
car_detail.js
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
cache: false,
data: { car_rent_id: this.car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
car_detail.php
$car_rent_id = $_GET['car_rent_id'];
$query = mysql_query("SELECT c.car_name, c.car_type, c.car_colour,
c.plate_no, c.rate_car_hour, c.rate_car_day, c.car_status,
r.pickup_location
FROM car_rent c
JOIN rental r ON c.car_rent_id=r.car_rent_id
WHERE c.car_rent_id = $car_rent_id");
$users = array();
while($r = mysql_fetch_array($query)){
$user = array(
"car_name" => $r['car_name'],
"car_type" => $r['car_type'],
"car_colour" => $r['car_colour'],
"plate_no" => $r['plate_no'],
"rate_car_hour" => $r['rate_car_hour'],
"rate_car_day" => $r['rate_car_day'],
"car_status" => $r['car_status'],
"pickup_location" => $r['pickup_location']
);
$users[] = $user;
// print_r($r);die;
}
print_r(json_encode($users)); //[{"car_name":"Saga","car_type":"Proton","car_colour":"Merah","plate_no":"WA2920C","rate_car_hour":"8","rate_car_day":"0","car_status":"","pickup_location":""}]
car_detail.html
<label>ID:</label>
<input type="text" name="car_rent_id" id="car_rent_id"><br>
<label>Car Name:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_name" id="car_name" class = "form-control" placeholder = "Car Name" aria-describedby = "sizing-addon3">
</div></br>
<label>Car Type:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_type" id="car_type" class = "form-control" placeholder = "Car Type" aria-describedby = "sizing-addon3">
</div></br>
Remove this in this.car_rent_id1 and cache: false this works with HEAD and GET, in your AJAX you are using POST but in your PHP you use $_GET. And car_rent_id is not defined, your function $_GET(q,s) requires two parameters and only one is passed.
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id'); // missing parameter
car_rent_id.value = car_rent_id1; // where was this declared?
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
You can also use $.post(), post is just a shorthand for $.ajax()
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.post('http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php', { car_rent_id: car_rent_id1 }, function (users) {
console.log(users);
$('#car_name').val(users.car_name);
});
});
and in your PHP change
$car_rent_id = $_GET['car_rent_id'];
to
$car_rent_id = $_POST['car_rent_id'];
Here is a code skeleton using .done/.fail/.always
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$.ajax({
url: 'theurl',
dataType: 'json',
cache: false
}).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
}).always(function(data){
console.log(data);
});
});
</script>
I've adapted your code, so you can see the error, replace the ajax call with this one
<script>
$.ajax({
url: "theurl",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
},
error: function(data) {
console.log(data);
alert("I failed, even though the server is giving a 200 response header, I can't read your json.");
}
});
</script>
A couple of recommendations on this, I would follow jQuery API to try an see where the request is failing http://api.jquery.com/jquery.ajax/. Also, I would access the ids for the input fileds with jQuery. e.g.: $("#theID").val().

Can't send data to the Controller with a POST method Symfony3

I have a POST method Jquery. Ajax and I can't send my data to the controller, I have tried every solution on the net, but no result.......
My JavaScript
$(document).ready(function(){
$('#submitForm').click(function(){
var data1 = {request : $('#request').val()};
$.ajax({
type: "POST",
url: "/Manufacturer",
data: data1,
success: function(dataBack) {
console.log(dataBack);
},
contentType: "application/json",
dataType: 'json'
});
});
});
MY controller
public function indexAction(Request $request)
{
//$name = $request->request->get('data');
//return new Response($name);//or do whatever you want with the sent value
if($request->isXmlHttpRequest()){
$name = $request->request->get('data1');
If($name == 1)
{
return new Response('Yeap');
}
else
{
return new Response(';(');
}
}
return $this->render('MyIndex/Manufacturer_LIST.html.twig' );
}
HEre is my Console ::
And my response is as it's obvious ";("
First you need to install FOSJsRoutingBundle to be able to "expose" your Symfony routes into the javascript code. Follow the steps in the official documentation.
Then, in your twig template if you have a form like:
<form>
<input type="text" id="name"> <br>
<button type="submit" id="submitForm">Submit</button>
</form>
your js code could look liks this:
$('#submitForm').click(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
method: 'POST',
url: Routing.generate('Manufacturer_LIST');
// OR: url: "/Manufacturer", if you don't want to install FOSJsRoutingBundle
data: { name:name }
}).done(function(msg){
console.log(msg);
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus + ' ' + errorThrown);
});
});
And in your controller:
/**
* #Route("/Manufacturer", name="Manufacturer_LIST", options={"expose"=true})
*/
public function indexAction(Request $request){
if($request->isXmlHttpRequest()){
$name = $request->request->get('name');
return new Response($name);//or do whatever you want with the sent value
}
return $this->redirectToRoute('homepage');
}

AJAX reloads the page without inserting into database

I am new to Ajax and confused. The problem is the ajax reloads the page. The function mentioned in the url inserts the data into database. but the page reloads. I guess the URL is not working but i am not sure on this.
Here is my Controller Function
public function insert_student_fee_payment()
{
$std_code=$this->input->post('std_code');
$total_fee=$this->input->post('total_fee');
$payable_fee=$this->input->post('payable_fee');
$date=date('Y m d');
$class_detail=$this->db->select('class.class_year,class.class_semester')
->join('class','class_student.class_id=class.class_id','LEFT')
->where('class_student.student_id',$std_code)
->where('class_student.class_student_status',2)
->limit(1)
->get('class_student')
->result();
if(count($class_detail)>0)
{
foreach($class_detail as $cd)
{
$year=$cd->class_year;
$semester=$cd->class_semester;
}
}
$data=array(
'std_code'=>$std_code,
'year'=>$year,
'semester'=>$semester,
'total_fee'=>$total_fee,
'payable_fee'=>$payable_fee,
'date'=>$date,
'status'=>2
);
if($this->db->insert('student_fees',$data))
{
echo '1';
}
}
and here is my Ajax code in form
<script type="text/javascript">
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '<?php echo base_url()."index.php/finance/insert_student_fee_payment;?>',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
});
});
any help guys
We don't see the HTML so it's hard to say what's wrong but my guess is that $('#insert_fee_payment') is a submit button so you have to cancel the action by default which is submitting the form.
$('#insert_fee_payment').click(function(e){
e.preventDefault();
};
or
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
return false;
});
Add return false after the error function.
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
return false;
});
});
});

Categories

Resources