I have a form...I want to add disabled to all the inputs inside a certain div but rest of the form. I verified that this is indeed happening as it should but, when I submit the form with the disables added, I get no POST data. But with all my code the same, except for not adding the disableds, I do get my post data as I should. And I repeat, I DID verify that the disableds are only going on the inputs that I expect and NOT the other inputs that I want data from.
There is not really even much code..the inputs look like this (and it is definitely inside a form element) -
<div class="abridged-hide">
<input type="hidden" name="actor_id[]" value="162705079">
</div>
The submit button -
<button type="submit" id="entry_submit" class="btn btn-primary">Update Page</button>
Jquery is simply -
$('#entry_submit').on('click', function(event){
$('.abridged-hide input').attr('disabled', 'disabled');
$('.unabridged-hide input').attr('disabled', 'disabled');
});
I tried
.attr('disabled', true);
.prop('disabled', true);
Like I said, if I comment out the Jquery and submit, I do get my post data fine, something about this Jquery is making me not get my post and really don't see any reason why... Thanks in advance.
edit - these are the inputs being created dynamically.
<td class="btn btn-primary">
<span class="glyphicon glyphicon-resize-vertical" aria-hidden="true">
<input type="hidden" name="actor_id[]" value="162705079">
</span> Julie Benz - J</td>
edit - code that generates the inputs
$( ".drop-container" ).droppable({
accept: ".draggable",
addClasses: false,
drop: function(event, ui) {
var drag_name = ui.draggable.html();
ui.draggable.hide();
var new_body_count = '<tr><td class="btn btn-primary">'+drag_name+'</td>
<td class="badge"><input placeholder="Number of Kills" name="body_count" class="number-count" type="number"></td></tr>'
$('.table').prepend(new_body_count);
}
});
Related
How to update multiple data using AJAX ?
Example :
TableA
id : 1, 2
name : Jack, John
It's only working with id 1, when I am trying to edit name for id 2 it's not working.
I have try with this code but failed.
HTML/PHP :
...
while($row=mysqli_fetch_array($query)){
echo'
<form class="btn-group">
<input type="text" class="form-control" name="id_user" id="id_user" data-user="'.$row['id'].'" value="'.$row['id'].'">
<input type="text" class="form-control" name="id_status" id="id_status" data-status="'.$row['id'].'" value="'.$row['id'].'">
<button type="submit" id="likestatus" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
AJAX :
$(document).ready(function(){
$("#likestatus").click(function(){
var id_user=$("#id_user").data("user");
var id_status=$("#id_status").data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
The problem with your code is that ids should be unique, but in the loop you create elements with same id.
Use this in the event handler to find the siblings of the button that has been clicked - closest returns the parent of type form.
$(document).ready(function(){
$(".btn-primary").click(function(){
var $form = $(this).closest('form');
var id_user=$form.find('[name="id_user"]').data("user");
var id_status=$form.find('[name="id_status"]').data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You might want to use your own class instead of .btn-primary because this affects all buttons on the page.
Judging from the incomplete PHP, it appears as if you're not assigning to $ruser within your loop. This would mean you're always posting the same id to like-status.php.
PS: Would've posted as comment, but I can't.
Make your ID unique so make them dynamic
<?php
$counter = 0;
while($row=mysqli_fetch_array($query)){
$counter++;
echo'
<form class="btn-group">
<input type="text" class="form-control" id="userid_$counter" data-user="'.$ruser['id'].'" value="'.$ruser['id'].'">
<input type="text" class="form-control" name="id_status" id="status_$counter" data-status="'.$rtimeline['id'].'" value="'.$rtimeline['id'].'">
<button type="submit" id="likestatus_$counter" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
?>
Then
<script type="text/javascript">
$(document).ready(function(){
$('[id^="likestatus_"]').on('click',function(){
var index = $(this).attr('id').split("_")[1];
var id_user=$("#user_"+index).data("user");
var id_status=$("#status_"+index).data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You're using the id's multiple times. Thus your query for var id_user=$("#id_user").data("user"); always finds the first input field on the page. You should avoid using the same id multiple times on one page (see this Question).
You may subscribe to the jQuery submit event of the form and then search for the input fields within that form, to properly extract the id_user and status_user values. For that you have to add an appropriate event listener to the <form> element. To find the form I would recommend adding a css-class like like-status-form.
$(document).ready(function(){
// We're attaching a submit-event listener to every element with the css class "like-status-form"
$(".like-status-form").submit(function(event){
// Form get's submitted
// Prevent that the Browser reloads the page
event.preventDefault();
// Extract the user id and status from the form element (=== $(this))
var id_user = $(this).find('[name="id_user"]').data('user');
var id_status = $(this).find('[name="id_status"]').data('status');
// TODO Perform AJAX Call here
});
});
To detect the form elements one can use the jQuery Attribute Equals Selector.
Find a working example at https://jsfiddle.net/07yzf8k1/
I am trying to send form data using ajax. My index page the records are showing after having been fetched using ajax from remote page.
Below is my page image.
Each record has comment box I want to store these comments in a data base using ajax.
Below is my jquery
$(function(){
$('body').on('submit','.comment_p',function(){
var post_id = $("#post_id").val();
var com_dis= $("#comment_disc").val();
var cominfo = 'id=' + post_id + '&disc=' + com_dis;
if(com_dis=='')
{
alert('Please add your comment');
} else{
$.ajax({
type:"POST",
url:"/comment_update.php",
data:$(".comment_p").serialize(),
success: function(data){
alert(data);
}
});
}
return false;
});
});
i used body on click because these records are loaded from remote page.
and my form is below
<div class="panel-zesteve-textarea">
<form method="post" id="'.$row['id'].'" class="comment_p">
<input id="post_id" type="hidden" name="post_id" value="'.$row['id'].'">
<textarea id="comment_disc" name="comment_disc" rows="2" cols="48"></textarea>
<button id="com_submit" type="submit" class="btn btnbg">Post comment</button>
<button type="reset" class="[ btn btn-default ]">Cancel</button>
</form>
nowWhen I click on post, comment is working for one record that is the last record. I need to send id no. and textarea value to php page to update in mysql, but both comments are showing same record id and comment. It's not working for sencond one
Try to reference the form with $(this)
data: $(this).serialize(), instead of `data:$(".comment_p").serialize(),`
I am trying to add an effect to the login form and when the effects is done ( like 1 sec) it then goes to php.
I tried to make a setTimeout() function inside the .submit with e.preventDefault() so I can delay it for a sec but the problem is it didnt take the data but instead it goes to the php in a blank webpage that sopposed to be checking the data that was inputted.
And when the e.preventDefault() is been taken away the php works but it didnt give me a second to perform the animation first then go to php file to check all the data
here is my code
<script> $("#effectsExplode").submit(function (e) {
var form = this;
e.preventDefault();
$("#effectsExplode").toggle("explode");
setTimeout(function () {
form.submit();
},1000);
});
</script>
<form id="effectsExplode" class="form-1" method="post" action="checklogin.php">
<p class="field">
<input type="text" name="login" placeholder="Username or email">
<i class="icon-user icon-large"></i>
</p>
<p class="field">
<input type="password" name="password" placeholder="Password">
<i class="icon-lock icon-large"></i>
</p>
<p class="submit">
<button id="buttonexplode" type="submit" name="loginsubmit">
<i class="icon-arrow-right icon-large"></i>
</button>
</p>
</form>
You've created an infinite loop. If for example I had a button and this javascript:
$('button').click(function() {
var b = this;
$('#status').append('Clicked<br/>');
setTimeout(function() {
b.click();
}, 1000);
});
http://jsfiddle.net/b9chris/yaNdc/
Once I click that button, I'll get another "Clicked" message appended to that status tag every second... forever. That's because jquery fires all its event handlers for the events you manually trigger; in this case you attached to 'submit' then fired 'submit' and looped right back into your own code, which keeps preventing the form from ever actually submitting.
Most likely on your local test machine this form submission happens almost instantly, but once you put it out on the webserver the live version will take longer, and your animation will have time to play. Simplest solution is to just get rid of the ev.preventDefault() and let it submit and play while the submission takes its time.
I'm pulling my hair out over this one - I have a page that searches a MySQL database and returns the results in a table. I want the user to be able to update the results and hence update the MySQL database. The first part works ok, I have a search box on the page, which uses jQuery/ajax to query the database and display the results, e.g.:
<form class="well" id="jquery-submit-ajax" method="post">
<input type="text" name="userSearch" placeholder="Search…">
<label>Name/Email/id</label>
<Br />
<input type="submit" id="searchButton" value="Search">
</form>
<div class="alert alert-success hide">
<div id="success-output" class="prettyprint"></div>
</div>
<div id="loading-image" class="alert hide" style="text-align:center">
<img src="../images/ajax-loader.gif" /></div>
<div class="alert alert-error hide">
<div id="error-output" class="prettyprint"></div>
</div>
</div>
and the jQuery:
$("#jquery-submit-ajax").submit(function(e) {
$('#loading-image').fadeIn();
$.ajax({
type: "POST",
url: "jquery-ajax-control.php",
data: $(e.target).serialize(),
dataType: "html",
beforeSend:function(){
$('.alert-error,.alert-success').hide();
},
error: function(jqXHR, textStatus, errorThrown){
$('#loading-image').hide();
$('.alert-error').fadeIn();
$('#error-output').html(errorThrown);
},
success: function(data){
$('#loading-image').hide();
$('.alert-success').fadeIn();
$('#success-output').html(data);
}
});
return false;
});
So the results are parsed into a table for each result. Within that table is a form with a submit button. e.g.:
<form method="post">
<table>
<tr>
<td><input type="text" class="editbox" name="subs-expiry" value="<?php echo $expiry_date; ?>"</td>
</tr>
</table>
<input type="submit" class="updateSubsButtons" value="Update" />
</form>
I'm trying to submit this form via jQuery/Ajax again, but I can't get it to work. Pressing the Update button results in the whole page refreshing. I've stripped the jQuery for this button right back to just display an alert when the button is pressed, but even that doesn't work.
$(".updateSubsButtons").on("submit", function(e){
alert("clicked");
e.preventDefault();
});
Using the Chrome debugger a breakpoint in the function never gets hit, so maybe jQuery can't find the button? I've tried .on() and .live() functions, but I get the same result with both. I really can't figure out what's going on here, so any help would be gratefully received!
Try replacing it with a button, and a 'click' event.
<button class="updateSubsButtons">Update</button>
$(".updateSubsButtons").on("click", function(e){
alert("clicked");
console.log(e);
e.preventDefault();
});
Here's how to deal with asynchronously loaded items(added because this is how the problem was actually fixed.):
$(".AlreadyLoadedParent").on("click",'.buttonYouWantToClick', function(e){
alert("clicked");
console.log(e);
e.preventDefault();
});
First, you "click" a button, you don't "submit" it. You submit the form. So you should work with the event "click".
Second, if the button that should trigger the jQuery code is loaded using AJAX you should bind the event using .live() function like this:
$('.updateSubsButtons').live('click', function(e) {
e.preventDefault();
// Your code here...
}
This way the click event is bound to every new object with class="updateSubsButtons" that is loaded even after the page is loaded. If you use $('.identifier').click() it only works on objects that are already loaded when the page loads and doesn't work on elements being loaded through AJAX.
I have a simple application here (QandATable2.php) where when the user clicks on the plus button, it will open a modal window and it displays the details which is stored in another page (previousquestions.php).
Now the problem I have is that if you straight away click on the "Search" button when the textbox is blank, you will see that it loads the page on its own page, displaying the message to enter in a phrase for the search and it also displays all of the features previously from the modal window into that page as well. This is incorrect.
What I want it to do is that if the user has clicked on the search button, then when it post's the form and outputs the message, it does it within the modal window, not on its own whole page. So does anyone know how this can be acheived?
The modal window I am using is known as SimpleModal and it's website is here
Below is the QandATable2.php code where it displays the plus button and where it opens the modal window, linking the content of the modal window to the previousquestions.php page:
<script type="text/javascript">
function plusbutton()
{
$.modal( $('<div />').load('previousquestions.php #previouslink') );
return false;
}
</script>
<h1>CREATING QUESTIONS AND ANSWERS</h1>
<table id="plus" align="center">
<tr>
<th>
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look <br/> up Previous Questions)</span>
</th>
</tr>
</table>
Below is the previousquestions.php code, where it displays the details in the modal window and where the search feature is stored:
<?php
foreach (array('questioncontent') as $varname) {
$questioncontent = (isset($_POST[$varname])) ? $_POST[$varname] : '';
}
?>
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<?php
//...connected to DB
if (isset($_POST['searchQuestion'])) {
$questionquery = "SELECT QuestionContent FROM Question
WHERE(QuestionContent = '".mysql_real_escape_string($questioncontent)."')";
if (empty($questioncontent)){
echo "Please enter in a phrase in the text box in able to search for a question";
}
?>
You'll probably want to use AJAX, since you're already using jQuery you'll just need something like this:
// override the "default" form submitting behavior with a callback function
$("form").submit(
// this is the callback function for your form submit function.
function(e)
{
// this prevents the page from reloading -- very important!
e.preventDefault();
// get the search data from the input textbox
var s = $("input[name='questioncontent']").val();
// see annotation
$("#simplemodal-data").html("loading...")
.load("previousquestions.php #previouslink",
{
questioncontent : s,
searchQuestion : "Search"
}
);
}); // end submit wrapper
This will send the value to the server and load it in the div with id simplemodal-data
Annotation:
The last line in the code does several things. First, it replaces the simplemodal DIV with a "loading" message. At the same time, it makes a POST request to your previousquestions.php page. This part { questioncontent : s, searchQuestion : "Search"} is where the data from the form gets passed to the PHP page, (remember the variable var s assignment above. Lastly, the results from the previousquestions.php page should be loaded in the simplemodal-data modal window.
One thing that's missing is to add #previousquestions in the load method so that only a portion of your HTML document gets inserted in the modal. It's never a good idea to load an entire HTML page inside another HTML document, and "load" is designed to allow you to just pick the part of the document you want to insert, which is just that DIV.
I added "#previouslink" after the php filename. This is where the magic happens. The browser knows to extract that DIV from your PHP file and insert just that part on the page, no <head> <body> or any of the unneeded markup.
You can achieve what you're looking for by using AJAX to submit the form instead of using the default behavior where the page reloads with the new content. You can't use modal.load because you need to POST data in the request in order to get the appropriate response.
However, when using AJAX to post your data, you can take the response as HTML and add that HTML to a DIV on your page, and then invoke the SimpleModal command on that DIV container.
First, modify the submit button on your form so that it's type="button" instead of type="submit". This will prevent the form from submitting and redirecting the page. Alternatively, you could add event.preventDefault(); and return false to the form submit click handler (see the second step), but it's probably easier to try this method while you're making the changes:
Step 1:
<!-- change type to button -->
<input id="searchquestion" name="searchQuestion" type="button" value="Search" />
Step 2:
Create a handler for the form button, which uses serializeArray to serialize the form into a string and then POST it to the server. In the success callback handler, you'll then take the HTML response and replace the content in the modal window with the new HTML. This also catches errors, if any, and alerts them and writes them to the console:
$('form[type="button"]').click(function() {
var dataString = $('form').serializeArray();
$.ajax({
url: "/previousquestions.php?t="+new Date().getTime(),
type: "POST",
data: dataString,
context: document.body,
success: function(data){
alert(data); // results from server, either the HTML page, or JSON/XML
$('simplemodal-data').html(data); // if HTML, just insert into div#results
},
error: function(jqXHR, textStatus, errorThrown) {
if(window.location.hostname == "localhost") {
alert("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
console.error("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
});
});
Step 3:
Lastly, be sure that your previousquestions.php code returns only a partial HTML document, not a full HTML document. Since you're injecting HTML into an existing page, you don't need the <html>, <head>, or <body> sections. These will just cause your page to not validate, and may cause undesired behavior in legacy browsers. Here is an example of what your response might look like:
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="test" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<p>
Your Search: 'test' </p>
<p>Number of Questions Shown from the Search: <strong>0</strong></p><p>Sorry, No Questions were found from this Search</p>
I have found out from an answer on another page to a similar question to this that like Bergi has stated, it is easier using an iframe than using ajax to keep content displayed within a modal window. So the best answer for this question is below where it shows how an iframe is used for the question above:
function plusbutton() {
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}