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.
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"];
This is my HTML code
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="ADD TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
// Same form as above
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="ADD TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
Jquery Code:
<script>
$(".addtowatchlistform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(form).children("button").css('color',data.watchlisticoncolor);
$(form).children("button").data('tooltip', data.addremove + " TO YOUR WATCHLIST"); // This line not working
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
</script>
PHP file insertwatchlist.php file
$response = new \stdClass();
$response->addremove = "REMOVE";//you can get the data anyway you want(e.g database)
$response->watchlisticoncolor = "red";
die(json_encode($response));
Output of PHP file insertwatchlist.php file
{"addremove":"REMOVE","watchlisticoncolor":"red"}
Expected Result:
1.)When someone clicks on add_box button, it submits the form without reloading the page (This one works fine)
2.) When someone clicks on add_box button, it's color changes. (works fine too)
3.) When someone click on add_box button, the data-tooltip="" value changes. (this one do not work)
So the 3rd point do not work as expected, what is wrong in my Jquery code? Console tab is empty, it shows nothing.
your jquery code should be like this
$(form).children("button").attr('data-tooltip',data.addremove + "TO YOUR WATCHLIST");
or
$('.material-icons').attr('data-tooltip',data.addremove + "TO YOUR WATCHLIST");
Say i have a form in html with the following content
<form>
<div id="si-main">
<button id="si-btn">Add new content</button>
<div class="si-content">
<input type="text" class="si-input" name="content">
</div>
</div>
<input type="submit" id="si-submit" value="Submit">
</form>
Now i wanna append the ".si-content" div when i click the "#si-btn" i do that using this script in JS
$('#si-btn').click(function() {
$('#si-main').append('<div class="si-content"><input type="text" class="si-input" name="content"></div>')
})
I then submit the form like this in JS
$('form #si-submit').click(function() {
var data_to_send = {}
$('form').find('.si-input').each(function() {
if ($(this).hasClass('si-input')) {
data_to_send[$(this).attr('name')] = $(this).val()
}
})
//NEXT I SEND THE AJAX REQUEST AND HANDLE THE RESPONSE
})
Now the problem is each i append it adds a new "si-content" div. But when i send the data it only sends the content of the first div. Can someone tell me what would be the best way add the data in this case ?
try:
$('#si-main').append('<div class="si-content"><input type="text" class="si-input" name="content[]"></div>');
$('form #si-submit').click(function() {
var data_to_send = $(this).parent('form').serialize();
//NEXT SEND THE AJAX REQUEST AND HANDLE THE RESPONSE
})
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;
});
In the window.onbeforeunload event is there a way to detect if the new request is a POST (on the same page) or a GET (going to a page)? It would also be great to see the new document.location.
window.onbeforeunload = winClose;
function winClose() {
//Need a way to detect if it is a POST or GET
if (needToConfirm) {
return "You have made changes. Are you sure you want?";
}
}
This is how I just did it:
$(document).ready(function(){
var action_is_post = false;
$("form").submit(function () {
action_is_post = true;
});
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (!action_is_post)
return 'You are trying to leave this page without saving the data back to the server.';
}
});
Sounds like something you'd need to attach to a form, or specific links. If the event is raised by a link, and there is a request string full of variables, it will act as a GET. If it's a form, you'll have to check the METHOD, and then figure the URL based on the data being submitted in the form itself.
No method
GET method
<form method="GET" action="thisPage.php">
<!-- This is a GET, according to the method -->
<input type="text" name="usrName" value="jonathan" />
</form>
<form method="POST" action="thisPage.php">
<!-- This is a POST, according to the method -->
<input type="text" name="usrName" value="jonathan" />
</form>
So the detection would take place not in the window method, but in the click method of your links, and form submissions.
/* Check method of form */
$("form").submit(function(){
var method = $(this).attr("method");
alert(method);
});
/* Check method of links...UNTESTED */
$("a.checkMethod").click(function(){
var isGet = $(this).attr("href").get(0).indexOf("?");
alert(isGet);
});