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.
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'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').
I have used submit and added an onclick event to it and I want to call the controller method save for it, and after that I want to redirect my page to another method of the controller for that I have used onclick where I have used opener.href = "". My problem is that sometimes it goes to the save page but oftenly it goes to the onclick event first. I have searched it on google and all the methods tell me to the way I did but something is not right. Please help me.
Here is the code:
<input id="m_bs_btnNext" type="submit" value="Save" onclick="closeWindow();" />
and the onclick function is:
function closeWindow() {
window.opener.location.reload();
window.opener.location.href = "ViewDesign";
setTimeout("window.close()", 800);
}
I would have your close window happen after the save by using onsubmit on your form:
<form id="form" action="/save" onsubmit="saveAndCloseWindow()">
<-- Other form elements -->
<input id="m_bs_btnNext" type="submit" value="Save" onclick="closeWindow();" />
</form>
Then your save function would look like this:
function saveAndCloseWindow() {
$.ajax({
url: $('#form').attr('action'),
method: 'POST',
success: function() {
window.opener.location.reload();
window.opener.location.href = "ViewDesign";
setTimeout("window.close()", 800);
}
})
}
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'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.