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

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"];

Related

Send hidden input data using AJAX

I am using AJAX live search plugin.
It passes input data to backend-search.php
backend-search.php selects data from the database and return to the search page.
Now I want to pass one hidden input value with the search query.
Hidden Input
<input type="hidden" name="group" value="<?php echo $grp_id; ?>" />
Following is my html in search.php
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search..." />
<div class="result"></div>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var term = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(term.length){
$.get("backend-search.php", {query: term}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
How do I send the data of the hidden input field with above js?
You could use $.post instead of $.get like this:
$.post( "backend-search.php?query="+ term, { hidden_key: "hidden_value"})
.done(function(data) {
alert( "Data Loaded: " + data );
});
So, customizing it for your code,
if(term.length) {
// get value of hidden field
var hidden_value = $('[name="group"]').value();
// make a post request, but also pass query params
$.post("backend-search.php?query=" + term, { group: hidden_value})
.done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
}
Here, everything after the ? mark is passed as a query string (i.e. via get method) whereas the hidden field is passed by the Post method.
In your Php script, use print_r($_REQUEST) to verify that you get the 2 parameters as desired.
Also, you should encode URI parameters like this encodeURIComponent(term) to make sure your javascript does not break if the user enters special characters

Get input value inside a form depending on which button is clicked

I've got the following form:
<div>
<form name="ajaxformname" id="ajaxform" action="/request" method="POST">
AJAX:
<input id="btn1" name="feeling" type="submit" value="Fine">
<input id="btn2" name="feeling" type="submit" value="Neutral">
<input id="btn3" name="feeling" type="submit" value="Bad">
</form>
</div>
which should be posted to a server via ajax.
Here is the associated javascript:
$('#ajaxform').submit(function (event) {
event.preventDefault();
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.attr("value");
$.ajax({
url: "/request",
type: method,
data: data
});
Now - depending on which of the three buttons has been clicked - I want their values to be posted to the server. But form.attr("value") just gives me the value of the form but not of the input field.
Any suggestions? A solution would be to create the different forms but that doesn't seems to be DRY ...
First thing, if you wanna use the action attribute of the form, you should reference it in the url param of ajax request:
url: form.attr('action'),
Now, for the button clicked, you should use this (it's a workaround because submit buttons are not incluided in the form serialization, if not, I would use it instead):
$(function () {
//When any of the buttons is clicked, we store in the form data the clicked button value
$('#ajaxform').on('click', 'input[type=submit][name=feeling]', function(e) {
$(this.form).data('clicked', this.value);
});
$('#ajaxform').submit(function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr("method"),
data: { clickedButton : form.data('clicked') } //Retrieve the button clicked value from the form data
});
});
});
Here the working example: https://jsfiddle.net/68qLxLgm/1/
Hi kindly use the following to get the id of the button that has been clicked
$("input").click(function(e){
var idClicked = e.target.id;
});

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.

Take input from html field and store it in JSON object (lots of input fields)

I am looking for a way to take input from an HTML form and store it into a JSON object for use with AJAX. I can't use the normal $('#id').val();, because, as you can see below, there are a lot of fields. Here is some sample code
Javascript/jQuery:
$(document).ready(function() {
$('.add-to-cart').click(function() {
var id = $(this).attr('id');
//var qty = $(this).attr('qty'); <- need the quantity from the field
console.log(id);
//console.log(qty);
$.ajax({
url: 'addproduct',
type: 'POST',
datazType: 'JSON',
data: {
"id": id
//"qty": qty
},
success: function(addedproduct) {
console.log(addedproduct.name);
$('#cart').append('<li>'+ addedproduct.name +'</li>');
},
error: function() {
console.log('failed to add product');
}
})
});
});
HTML:
<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>
Help me please, or at least guide me in the right direction, this HAS to happen using AJAX.
jQuery's selialize method is what you are looking for. It serializes the values of inputs in a form.
Helpful example: https://stackoverflow.com/a/6960586/4180481

Response from AJAX request is only displayed once

I've got some code that sends an ajax request when a form is being submitted. This works the first time the form is submitted (it's a search module), but only once. I've added an effect to highlight the table when data is returned, and you can only see it once (the data changes only once as well).
When I look at the response in the chrome dev tools, I can see it contains the data of the new search query but this isn't shown. Why can I only display results once?
JS:
$(function () {
// Creates an ajax request upon search form submit
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-nn-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect("highlight");
});
// Prevent default action
return false;
};
$("form[data-nn-ajax='true']").submit(ajaxFormSubmit);
});
HTML:
<form method="GET" action="#Url.Action("Index", "Show")" data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
<div class="input-append mysearch">
<input type="search" class="span5 search-query" name="query" data-nn-autocomplete="#Url.Action("AutoComplete")" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="contentlist">
#Html.Partial("_Shows", Model)
</div>
I think you should use html() instead of replaceWith() method:
$target.html($newHtml);
just an idea... try
$target.html(data);
instead of
$target.replaceWith($newHtml);
By replaceWith, you might actually remove the div that you want to fill your content in. Then, the second time, it doesnt find the div to insert the content into.

Categories