How to pass parameters to jQuery function when using Laravel - javascript

I'm trying to pass the value of a star rating using rateYo and the log gives me a:
4main.js:11 undefined
the way its set up, it uses the div to get a value. I'm trying to set the value for the star, and ultimately pass the value to route params. The backend PHP works, it's just a matter of passing the parameters.
Show.blade.php
<h5>Click to rate:</h5>
<form action="{{ route('rate', $book->id) }}" method="POST">
{!! csrf_field() !!}
<!-- <input id="rateYo" name="val" value="0" type="text"> -->
<div id="rateYo" name="val"></div>
<button type="submit" class="btn btn-primary">submit</button>
</form>
Main.js
$(document).ready(function() {
'use strict'
$('#rateYo').rateYo({
starWidth: "40px"
});
$('#rateYo').click(function() {
var owl = $('#rateYo').val();
console.log(owl);
$.ajax({
type: 'POST',
url: 'rate/' + owl,
success: function(data) {
// $("#msg").html(data.msg);
}
});
});
});
Route
Route::post('rate/{book_id}','BookController#rate')->name('rate');

See plugin documentation from http://rateyo.fundoocode.ninja/.
You can not get rating value using val() function.
Try using
var rating = $rateYo.rateYo("rating");
console.log(rating)

Related

How do I pass Button Value as a variable in Ajax?

I have a problem. I want to exchange certain data using PHP, MySQL and Ajax.
To do this I always have to pass the ID of a field to my backend, so I can continue working with this ID.
How do I pass the value from my button to my URL in Ajax?
What do I have to consider?
row['id'] is my variable (PHP)
HTML Code:
<a class='commentSikayet'>
<button id='commentSikayet' name='commentSikayet' value='{$row['id']}'>
Şikayet et
</button>
</a>
Ajax:
$(document).ready(function () {
$("#commentSikayet").click(function () {
$.ajax({
url: 'report_comment.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('Erfolgreich gemeldet.');
}
});
});
});
Assuming there might be more than one data sets in your page I modified your example to the following snippet. Each buttons has a data-id attribute that identifies the current dataset (the id would be supplied through your PHP script as $row["id"]):
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let data={cmt_id: $(this).data("id"),
value: $(this).prev().val()}
$.post("https://jsonplaceholder.typicode.com/comments",data)
.done(function (result) {
console.log("Erfolgreich gemeldet:",result);
});
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div><input type="text" value="some text">
<button name="commentSikayet" data-id="123">Şikayet et</button></div>
<div><input type="text" value="some other text">
<button name="commentSikayet" data-id="124">Şikayet et</button></div>
<div><input type="text" value="more text">
<button name="commentSikayet" data-id="125">Şikayet et</button></div>
In your backend PHP script (taking the place of the above typicode-URL) you can pick up the values from the $_POST superglobal as
$_POST["cmt_id"]; // id value
$_POST["value"];. // actual text content
Since you're listening for the click event on the button, you can access it via this in your handler function.
Add the name / value pair to your AJAX data option
$("#commentSikayet").on("click", function (e) {
e.preventDefault();
$.post("report_comment.php", {
bar: $("#bar").val(),
[ this.name ]: this.value // add name / value in here
}).done(function (result) {
alert('Erfolgreich gemeldet.');
});
});
This will include commentSikayet=rowIdValue in the POST request body which you access on the PHP side via...
$rowId = $_POST["commentSikayet"];

can't stop submitted form from refreshing page

The form is displayed dynamically and gives the id so I can found out which form it is coming from...
here is the php/html form
<div class="col-sm-4 text-center">
<!-- Task Name -->
<div><img src="{{ URL::asset('public/mealpics') }}/{{ $meal->picture }}" /></div>
<div>{{ $meal->name }} by {{ $meal->author }}</div>
<div>Rating: {{ $meal->rating }}</div>
<div>Cal: {{ $meal->calories }} Fat: {{ $meal->fat }} Chol: {{ $meal->cholesterol }}</div>
<div>Sodium: {{ $meal->sodium }} Sugar: {{ $meal->sugar }}</div>
<div>{{ $meal->created_at }}</div>
<div>
<form action="/mealtrist" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{!! csrf_token() !!}">
<input type="hidden" class="form-control" id="onPlan{{$meal->id}}" name="onPlan"
value="{{ $meal->id }}">
<button id="submit_btn" data-mealid="{{$meal->id}}" type="submit" class="btn btn-default">Add To Plan</button>
</form>
</div>
</div>
and the jquery ajax
$(document).ready(function () {
$('submit_btn').click(function(event) {
event.preventDefault();
var diffValue = $(event.currentTarget).attr("data-mealId");
var mealId = '#onPlan' + diffValue;
jQuery.ajax({
url : '<?php echo URL::to('mealtrist') ?>',
type : 'POST',
data : {
onPlan: diffValue},
});
});
});
i've also tried this...
$(document).ready(function () {
$('#submit_btn').click(function(event) {
event.preventDefault();
var diffValue = $(event.currentTarget).attr("data-mealId");
var mealId = '#onPlan' + diffValue;
$('#form').submit(function (e) {
jQuery.ajax({
url : '<?php echo URL::to('mealtrist') ?>',
type : 'POST',
data : $(mealId).serialize(), success : function( response ) {
$('#added').empty();
$(response).appendTo("#added");
}
});
e.preventDefault();
});
});
});
i've also tried the
('#form').on('submit', function (e) {
///i've even tried the e.preventDefault(); here but I think that prevents the code below from sending.
////code
e.preventDefault();
});
none of this seems to be working. I'm using larvel 5.1 and trying to get a form to submit on a page and send the value of one input to a controller so that I can get that id and use it to store information from another table in my database. It works of course, but it also refreshes the page...that's what I'm looking for. The page turns up blank, which i understand that is happening because I'm not returning anything in my controller...that doesn't matter, because when I return the same page in my controller it still shows the page refreshing...which is what I want to get rid of. I just want the data sent through ajax so I can use it...no page refresh. I don't understand why I'm having this issue. I've read alot of other questions on here about preventing the refreshing, but none of the solutions are working. Any idea?
Since you're handling the POST yourself via ajax (your first jquery example), try changing the button from type "submit" to just type "button"
This should help
$('form').submit(function (e) {
return false;
});
form has no id #form. Try form instead.
$('form').on('submit', function (e) {
e.preventDefault();
});
At first set an id into form --
<form id="MyForm" action="/mealtrist" method="post" enctype="multipart/form-data">
Then use this--
$(document).ready(function() {
$("#MyForm").on('submit', function(e) {
e.preventDefault();
})
});
I tried all the form submit answers above. return false did not work and event.preventDefault() did not work. I also wasn't as clear in my question. I really thought it was more secure to submit my form rather than use ajax, so that is why i was trying to use the form. I ended up just using ajax to send the data.
$(document).ready(function () {
$('.submit_btn').click(function(event) {
event.preventDefault();
var diffValue = $(event.currentTarget).attr("data-mealId");
jQuery.ajax({
url : '<?php echo URL::to('meals') ?>',
type : 'POST',
data : {
onPlan: diffValue},
/* success : function( response ) {
$('#added').empty();
$(response).appendTo("#added");
} */
});
});
});
It works perfectly fine.

How to call onclick jquery function having dynamic data, Asp.net Mvc5

I am loading packages using for-each loop, clearly from code.....
<div class="row">
#foreach(var items in ViewBag.packages)
{
<div class="col-md-2">
<div class="price-table-area">
<div class="fixed-img sec-bg5"></div>
<ul class="proce-table">
<li class="price-prdct"><i>$</i>#items.NewPrice<i>/m</i></li>
<input type="submit" class="submit" value="SignUp" onclick="packageSelect(#ViewBag.PackageId)">
</ul>
</div>
</div>
}
</div>
I am calling function packageSelect on click which invokes ajax call to controller action. As can be seen that I am passing #viewbag.PackageId parameter to function.
Controller action
public ActionResult SelectPackage(int PackageId)
{
Session["Package"] = PackageId;
return this.Json(string.Empty); ;
}
Script
<script>
function packageSelect(PackageId) {
$.ajax({
type: "POST",
url: '#Url.Action("SelectPackage", "Home")',
dataType: "JSon",
data: { "PackageId": PackageId },
success: function (data) {
console.log(data);
// $("#SecondInfo").focus({ scrollTop: "0px" });
$('html, body').animate({ scrollTop: $('#contact-us').offset().top }, 'slow');
},
error: console.log("it did not work"),
});
};
</script>
Is it right way to call like that? The problem is function not called.
In all the seriousness, I don't think this is a good way to do this.
Instead you should approach to it more clearer-
Use data attributes.
<button class="submit" data-id="#items.PackageId">SignUp</button>
And then-
$('button').on('click',function(){
var id = $(this).data('id'); //attribute's value
packageSelect(id); //passing the value to function
});
P.S.-
Also I suppose you are iterating the id, If yes then you shouldn't have used it as -
#ViewBag.PackageId
It should be (if its iterating and not going to stay the same)-
#items.PackageId
Your input is of submit type change its type to button. So when you click the button form will be posted and onclick will notfire.
<input type="button" class="submit" value="SignUp"
onclick="packageSelect(#ViewBag.PackageId)">
I don't think click accepts parameters that way. Try
<input type="submit" class="submit" value="SignUp"
onclick="function(){packageSelect(#ViewBag.PackageId);}">
I also agree with Mairaj that the type='submit' is suspicious.
Why do you need to pass PackageId value from ViewBag to the function packageSelect? If you are just passing the value to contoller action using ajax call, then I think it can be directly accessed in the action method from ViewBag.
And if you are making ajax call to another controller action then, There is TempData collection you can use to store PackageId.

Using results from a post request in a javascript variable

I have a very basic question (I'm sure) - I have an Zoho application and I'm using their REST API to recover a single result from a table.
I want to use that result in a javascript variable - the form request is here:
<form id="Latest" method="POST" action="https://creator.zoho.com/api/xml/my-company-culture/view/PageFeed_Report">
<input type="hidden" name ="authtoken" value="**********************">
<input type="hidden" name ="scope" id="scope" value="creatorapi">
<input type="submit" value="View Records">
</form>
I can auto submit the form using this
<script type="text/javascript">
document.getElementById("Latest").submit();
</script>
Which recovers a the result - but I want to assign this result to a javascript variable and use it in a following piece of code (within the same frame).
I am new to this, so please be gentle! Any help appreciated.
This is easily done with jQuery:
<form id="Latest">
<input type="hidden" name ="authtoken" value="**********************">
<input type="hidden" name ="scope" id="scope" value="creatorapi">
<input type="submit" value="View Records">
</form>
<div id="result"></div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#Latest').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var url = "https://creator.zoho.com/api/xml/my-company-culture/view/PageFeed_Report";
// Get some values from elements on the page:
var $form = $( this );
var authtokenData = $('#authtoken').attr('value');
var scopeData = $('#scope').attr('value');
// Send the data using post
var posting = $.post( url,
{
authtoken: authtokenData,
scope: scopeData
}
);
// Put the results in a div
posting.done(function( data ) {
// empty results div
$("#result").empty()
// write POST result to results div
$("#result").append("<p>" + data + "</p>);
});
});
</script>

Alloy UI problems with javascript function

I'm breaking my head trying to call a js function from a button element inside a form, here is my code:
<%
PortletPreferences prefs = renderRequest.getPreferences();
String employee = (String)prefs.getValue("name", "New Employee");
%>
<portlet:actionURL var="callURL" windowState="<%=LiferayWindowState.EXCLUSIVE.toString() %>" />
<script type="text/javascript">
Liferay.provide(window, 'insertEmployee',
function ()
{
var A = AUI();
var url = 'http://localhost:8080/c/portal/json_Service';
A.io.request(url,
{
method:'POST',
data:
{
serviceClassName: 'com.liferay.test.service.TrabajadorServiceUtil',
serviceMethodName: 'create',
servletContextName: 'TrabajadorPlugin-portlet',
serviceParameters: '[param]',
},
headers: {'Content-Type':'charset=utf-8'},
on:
{
success: function()
{
alert("success " + responseData.name);
}
},
form: {id: 'postForm'},
xdr: {dataType: 'json'}
});
},
['aui-io']
);
</script>
<div>
<aui:form name="postForm" id="postForm" method="post" onSubmit="insertEmployee();">
<input type="text" name="param" value="<%=employee %>"/>
<input type="submit" value="Submit"/>
</aui:form>
</div>
I'm not using an java class, thus I'm not using the portlet:actionURL either.
My intention is to call "insertEmployee()" when clicking the 'Submit' button, but it's only sending the param inserted by the user inside the text field. I've tried to put the 'onsubmit' also in the submit input, but the same result is given.
If you could help me or guide me to solve issue it would be so great! I'm not finding good information/tuts on the internet and I'm not sure where is the problem or what else I need to know.
Thanks a lot in advance!
I just need:
<aui:script>
window.functionName = function ()
{
//code
};
</aui:script>
and call it from:
<aui:form name="myform" action="javascript:functionName();">
<aui:input type="submit" name="Submit" value="Update"/>
</aui:form>
and the function is being called from the form tag.

Categories