I'm trying to pass the value of a post method using form method in my ajax call. When a print the value of my variable which should contains the value of the input i got undefined.
This is my form method
GO
<form action="allproducts.php" id="link_code" name="postlink" method="post">
<input type="hidden" id="link_code" name="name_link" value="2">
</form>
Below my ajax call
link_data();
function link_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var name_link = $('#link_code').attr("value");
console.log(name_link);
$.ajax({
url:"action.php",
method:"POST",
data:{name_link:name_link},
success:function(data){
$('.filter_data').html(data);
}
});
}
Thank you in advance
Remove the ID from the form element. That element does not have a value attribute.
Also, I would recommend using .val() instead of attr('value').
Related
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"];
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.
I have a <form>:
<form method="post" action="">
<button type="submit" name="age" value="20">Age 20</button>
<button type="submit" name="age" value="30">Age 30</button>
</form>
When I am handling submission of this <form> with ajax like this:
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
});
});
it completely ignores POST['age']. Is this intended behaviour or am I doing something wrong?
I've also tried <input type="submit" name="age" value="30" /> without luck.
As per the jQuery documentation for .serialize()...
Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button.
In other words, the button value will not be part of the POST array when the form is submitted with .ajax(). A regular "non-ajax" submit, however, WILL include the clicked button in the POST array.
A workaround would be to simply append the value of the button onto the serialized array...
$('button').on('click', function (event) {
event.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).parent('form').attr('action'),
data : $(this).parent('form').serialize() + '&' + $(this).attr('name') + '=' + $(this).val(),
});
});
Note that I'm using the click event of the button, rather than the submit event of the form, so that I can easily capture which button was used.
DEMO: http://jsfiddle.net/ty7c5k9b/
I have a scenario where I have a code like this
HTML
<input type="submit" value="" name="submit" id="slider1">
SCRIPT
$(document).ready(function() {
$("#slider1").Slider();
});
when document loads, some stuff is done to my input box by my Slider() function.
The issue am facing is that, am replacing the same input box html on ajax return and can't get my Slider() called.
AJAX RETURN
...
success: function(data) {
// This was removing the wrapper element, all the other calls
// to $('#slider1') were doing nothing
//$("#slider1").remove();
$("#slider1").html('<input type="submit" value="{{ some variable }}" name="submit" id="slider1">');
}
...
I was thinking of calling the Slider() function inside the input box so that it will be called,
something like:
$("#slider1").html('<input type="submit" callSliderFunction="Slider()" value="{{ some variable }}" name="submit" id="slider1">');
Is it possible to call it there? If not How can I achieve this? Thanks
I would just call .Slider() again after you add it to the page in the success function.
success: function(data) {
$("#slider1").remove();
$("#slider1").html('<input type="submit" value="{{ some variable }}" name="submit" id="slider1">');
$("#slider1").Slider();
}
As Juan pointed out, you can't call .html() on #slider1 once you .remove() it. From looking at what you have, its my guess that you're trying to change the value of the #slider1, in which case it would be simpler to do just that
success: function(data) {
$("#slider1").attr("value", "{{ some variable }}");
$("#slider1").Slider();
}
Just call it after you've setup the HTML
success: function(data) {
var wrapper = $("#slider1");
wrapper.html('<input type="submit" value="{{ some variable }}" name="submit" id="slider1">');
wrapper.Slider();
}
Just call it like you did when the document loaded after you have changed the html.
$("#slider1").Slider();
I have the following code:
<form action="" method="get" onsubmit="doRequest($('word').value); $('word').value=''; return false;">
<input type="text" name="word" id="word" value="" />
<input type="submit" name="submit" value="Send" />
</form>
doRequest() function:
function doRequest(request)
{
$.ajax(url, {
type: 'get',
data: { 'msg' : request }
});
}
The problem is, if I change the word value manually like value="111", I can see the value is being posted to PHP. However, when I want it to post whatever I write into textarea, it posts nothing, so the problem lies in the onSubmit area.
Can anybody help me about this?
You are missing the # in your jQuery selectors.
onsubmit="doRequest($('#word').value); $('#word').value=''; return false;"
I would also remove the inline JavaScript and replace it with a function in the submit handler instead. Also using jQuery .val() instead of .value.
$(document).ready(function() {
$('form').submit(function() {
doRequest($('#word').val());
$('#word').val('');
return false;
});
});
The correct way to access the value via jQuery is val() - not by setting a property.
$(...).val("set the value");
var get_the_value = $(...).val();
Also, your current selectors are looking for <word> elements which you hopefully don't have. Use #word as the selectors to search by ID.