I am dynamically creating a form in Jquery, and this form needs to submitted using AJAX. I'm probably doing something stupid, so your help would be greatly appreciated.
I am dynamically creating a form when a link is clicked:
$('.edit_item').click(function(){
$(this).closest('table').wrap("<form id='update_project' name='update_project' method='POST'>");
var input_name = $(this).closest('tr').find("td:eq(0)");
var input_submit = $(this).closest('tr').find("td:eq(1)");
input_name.html("<input type='text' id='update_name' name='update[]' value='"+input_name.text()+"' />");
input_submit.html("<input type='submit' value='update' id='update_submit' name='update_submit' />");
});
When the form is submitted:
$('#update_project').live("submit", function(e){
e.preventDefault();
$.post('project/update', $(this).serialize(), function(data){
$('#complete_msg').html(data);
});
$('.update_submit').css('background', '#c9c9c9');
});
Unfortunately, the page is refreshing (it shouldn't), and there is no return.
Thank you!
I would change the submit to a button:
input_submit.html("<input type='button' value='update' id='update_submit' name='update_submit' />
and the event, live is depreciated (http://api.jquery.com/live/):
$('#update_submit').click(function(e){
$.post('project/update', $('#update_project').serialize(), function(data){
$('#complete_msg').html(data);
});
$('.update_submit').css('background', '#c9c9c9');
});
Forgive me if my answer is too basic - your coding is quite advanced but you missed a couple of things. Better for me to be too pedantic rather than not provide enough info to immediately resolve your problem.
The page is refreshing when user clicks the update button because you are using the .submit method. If you do not want the form to refresh, use Stephen King's answer above to:
change the <input> type to type="button", then
use the ("#yourbuttonID").click() event to $.post your form data.
Also as SK said above, note the .live() is deprecated, so simply switch for .on()
Try this:
$('.edit_item').click(function(){
$(this).closest('table').wrap("<form id='update_project' name='update_project' method='POST'>");
var input_name = $(this).closest('tr').find("td:eq(0)");
var input_submit = $(this).closest('tr').find("td:eq(1)");
input_name.html("<input type='text' id='update_name' name='update[]' value='"+input_name.text()+"' />");
input_submit.html("<input type='button' value='update' id='update_submit' name='update_submit' />");
});
$(document).on("click", "#update_submit", function(e){
$.post('your_processor_filename.php', $(this).closest('form').serialize(), function(data){
$('#complete_msg').html(data);
});
$('.update_submit').css('background', '#c9c9c9');
});
Note that you need the .closest('form') selector to get your form data serialized.
I would also use $(document).on('click'... to ensure your injected button is found.
I am unfamiliar with the type of file to which you are sending the form data for processing, but project/update is not a familiar file type to me. Ensure that it is a page of code that can process your data, such as a .PHP file. See my example above -- or, better yet...
By way of example, create a .PHP file named 'your_processor_filename.php' (i.e. the filename I am referencing in the code I typed above). Put it in the same folder and type the following at the top:
//echo 'Got to the PHP side';
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
That will echo back what you sent and allow you both to see the data going through and confirm that the AJAX is working.
Note that your HTML must contain a div with the ID complete_msg to see the return message, such as:
<div id="complete_msg"></div>
Related
I have made a web page with a dropdown menu. The idea is when we click any option of the dropdown menu it open produccion.php with a POST parameter 'edicion'. This parameter I use to do a query in a Database.
At moment the problem is that it's open the produccion.php but I think that doesn't POST the value of the variable
Jquery code:
$('#drEdicion a').click(function(event){
alert($(this).text());
var ed = $(this).text();
$.ajax({
url:"produccio.php",
type:"POST",
data:{edicion: ed},
dataType:"text",
success:function(data){
window.location.href = 'produccio.php'
}
});
});
Is it possible that the problem is when it's send via ajax?
Thanks in advance.
Your code is currently POSTing the content of the hyperlink over to produccio.php via AJAX. When that call completes it is then redirecting the user to the same page but without the POSTed value. Based on your comment:
I want to open produccion.php after selection option in dropdown button. With this option I do a query
it appears you actually want to open produccio.php with the POSTed value in the browser.
By far the easiest solution to the problem would be to alter the PHP code to accept the value of edicion from $_GET["edicion"] instead, and output your hyperlink as:
...
This will also provide a better experience for users, especially if they have issues with JavaScript (or, for example, happen to be a search engine). However, if you're set on only using $_POST, the following code may - I've not tested this myself - allow this:
$('#drEdicion a').click(function(event){
event.preventDefault();
var ed = $(this).text();
$('<form action="produccio.php" method="POST">' +
'<input type="hidden" name="edicion" value="' + ed + '" />' +
'</form>').appendTo('body').submit();
});
(with credit to the top answer on Dynamically create and submit form)
Follow bellow code :
$('#drEdicion a').click(function(event){
//alert($(this).text());
event.preventDefault();
var ed = $(this).text();
$.ajax({
url:"produccio.php",
type:"POST",
data:{edicion: ed},
dataType:"html",
success:function(data){
//#dropdown-menu id show all produccio.php data
$("#dropdown-menu").html(data);
}
});
});
produccio.php
<?php
$edicion = $_POST['edicion'];
//now you can able to access edicion post param
?>
HTML like this :
<div id="dropdown-menu"></div>
To give you the most basic view of my question, I'm trying to create a page that is very similar to how facebook and twitter's dashboards and comment systems work. You have one page that will continuously create form elements (posts) from database rows in a loop as the user scrolls down. Users will then be able to comment on each of these posts. I want to be able to use ajax to submit comments on each post individually without reloading the page.
I run into a problem where when I try to submit a comment on any form other than the first one that is loaded on the page. In addition the ajax only posts the first form elements on submit (due to each form and elements having the same name I'm guessing).
Below is my comment loading script: [forgive the old php, I know I need to update it to mysqli or PDO]
php
<?php ...
$query = mysql_query("SELECT * FROM `posts`");
while ($row = mysql_fetch_array($query)) {
echo "
<div name='comment_body'>
<form name='comment_form'>
<td>User: ".$row['user']."</td>
<td>Post: ".$row['post']."</td>
<textarea name='comment'></textarea>
<p name='post_id' style='display:none;'>".$row['post_id']."</p>
<input type='submit' name='submit'>
</form>
";
$query2 = mysql_query("SELECT * FROM `comments` WHERE `post_id` = $row['post_id']");
while ($row2 = mysql_fetch_array($query2)) {
echo "
<td>User: ".$row2['user']."</td>
<td>Comment: ".$row2['comment']."</td>
</div>
";
}
... ?>
jscript
<script>
$('.comment_form').on('submit', function (e) {
e.preventDefault();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : $('#comment').val(), post_id : $('#post_id').text()}
success: function() {
$("#comment_body").load("load_comments.php #comment_body");
}
});
});
</script>
The script works to a point because when I comment on the first post, it works as expected. I just can't seem to figure out how to target the forms further down the page individually. Here's an example:
The very top post has a post_id value of 40. If I comment on post_id = 38, ajax will submit the empty comment field and post_id = 40 into the database.
Any help with the script form targeting would be great. If I need to rebuild my php query to give each echoed form element an individual name, that's fine as well. Thanks in advance!
The data you're trying to send to in the ajax call is using:
$('#comment').val(), post_id : $('#post_id').text()
But your HTML doesn't have anything with an ID="comment" and ID="post_id". (the '#' in your selector means getElementById.) So you aren't sending any data to your php page. You need to use the correct selectors to get that data. (see below)
Get rid of the 'form' tags you don't need them. Change your
<input type="submit">
to a:
<input type="button" class="comment-submit">
Then your script can be:
<script>
$('.comment-submit').on('click', function (e) {
e.preventDefault();
// get a referenct to this particular comment_body div
var $commentbody = $(this).closest('.comment_body');
// find the textarea within this particular comment_body
var commenttext = $commentbody.find('textarea[name="comment"]').val();
// find the post_id paragraph within this particular comment_body
var postId = $commentbody.find('p[name="post_id"]').text();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : commenttext , post_id : postId}
success: function() {
$comment_body.load("load_comments.php #comment_body");
}
});
});
</script>
Frankly I'm not sure what your success function is trying to do. But I think you need to work on it too. Normally an ajax call will return data so your success function should have a return value and that would be used to populate some part of your screen. The jQuery 'load()' function is another ajax call inside the success callback of an ajax call. I really don't think you want or need to do this.
You cannot select a unique form by class because your class is identical across all forms. Add an "id" field to the form element like this:
"<form name='comment_form' id='"+ .$row['id'] +"'>"
Then select a given form using that unique ID, and add your event handler. This must be in the same scope as you define your form. Like this:
$('#'+ .$row["id"]).on('submit', function (e) {
//Handle the event
})
I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
In createq() you are trying to access the local variable txt that was defined in another function. If you declare a variable inside a function, only that function has access to the variable.
You can fix this by passing txt as an argument to createq. In order to do this, you need to call createq yourself instead of setting it as an event handler for a click event.
Use jqoery's .click() to add a proper event handler for the click event and from that handler call createq, passing along the value of txt. In order to set the click handler, you need a reference to the element with the id "create", that you currently don't have.
The solution to this particular problem looks something like this:
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\"><br>Not found above? Create.</div>");
$("#search_output create").click(function() {
createq(txt);
});
});
...
function createq(txt){
...
}
About the way page refresh. If DOM element with id of window.location.href is missing the page will refresh. For example
assume you have window.location.href="#div1";
If DOM element with id="div1" is missing the page will surely refresh.
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
This question is directly related to the question I asked here:
stop click() from happening on a ajax created input
I figured out the answer to that one by simply adding if (e.target === this), but now my returned response wont do anything when I check the box.
The new code that is being returned by my .post is:
$output .= "<table><tr><td>";
$output .= "<input id=\"toedit\" type=\"text\" placeholder=\"$item_to_edit\" size=20>";
$output .= "</td><td>";
$output .= "<input id=\"test_editing_check\" type=\"checkbox\" name=\"test_editing_check\" value=\"test_editing_check\" \>";
$output .= "</td></tr></table>";
But my Jquery which is on the original page:
$("#testing_editing").click(function(e){
if (e.target === this) {
var testhtml = $(this).html();
var meatseafood = '<?php echo $meatseafood; ?>';
$.post('edit_order.php', {'itemtoedit':testhtml,'meatseafood':meatseafood}, function(data) { //make ajax call to check_username.php
$("#testing_editing").html(data); //dump the data received from PHP page
});
}
});
$("#test_editing_check").click(function(){
if ( this.checked ) {
var testvalue = "HI";
alert(testvalue);
}
});
Doesn't seem to work on the check box that is being returned by the .post() call.
Is there something i need to do in order to make a .post() return be recognized by the main page's jquery code?
I hope its not something wrong with my syntax but i've used this exact (very basic) code on another page (but not with a .post() call) and it works fine.
Basically, when you click the div my main page writes, it calls a .post() and returns a editable input field and a check box. When i click that checkbox, i want it to make another .post() call and update a database with the newly entered data.
however, when i check the check box nothing happens.
it would seem my ajax returned code isn't recognized by the jquery from the original/main page.
with my test code all i'm trying to do is pop up an alert box when i click the checkbox to show that it has "read" the input box and can now send that data through the .post() call to be processed.
Let me know if you need any other code.
It seems pretty cut and dry though so i'm not sure why it isn't working and that's why i'm here :)
(the idea of what i'm trying to do is, a user submits a form, on the next page, a "confirmation box" is shown saying "is this what you wanted to submit with your form? and if the answer is no, they can "click" on the data and change it w/out having to reload the page. the clicking part works but the checkbox to acknowledge "yes, i want to change my data to this newly entered data" isn't working.)
Thanks for any help.
Derek Conlon
Try to assign the event after loading the checkbox like this:
$("#testing_editing").click(function(e){
if (e.target === this) {
var testhtml = $(this).html();
var meatseafood = '<?php echo $meatseafood; ?>';
$.post('edit_order.php', {'itemtoedit':testhtml,'meatseafood':meatseafood}, function(data) { //make ajax call to check_username.php
$("#testing_editing").html(data); //dump the data received from PHP page
// This is applied after loading the data from the ajax call
$("#test_editing_check").click(function(){
if ( this.checked ) {
var testvalue = "HI";
alert(testvalue);
}
});
});
}
});
I am loading a form as a json output from an AJAX request.
The following PHP forms the JSON output of the request that displays the form:
$this->errors[] = "<form id='confirmreset' name='confirm_reset' action='" . URL .
"login/forgotPassword_action' method='post'><input type='hidden' name='user_email' value='" .
$this->user_email . "'> Email already registered. <input type='submit'
value='Click here for a PIN reminder'></form>";
I then want to be able to submit this form as an AJAX form too, but because it's not loaded in the DOM, my jquery doesn't seem to reference it. Any ideas?
Here's the code so far:
$("#confirmreset").on("submit",function(event){
//disable default click operation
event.preventDefault();
var action_url = $(this).attr("action");
alert_box_register("Resetting password...");
console.log(action_url);
var postData = $(this).serializeArray();
console.log(postData);
$.post(action_url,postData,function(data){
console.log(data);
var obj = $.parseJSON(data);
alert_box_register(obj.message);
});
});
Use .on()
As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.
$(document).on('submit','#confirmreset',function(event){ ..code here.. }
Syntax
$( elements ).on( events, selector, data, handler );
This should be as simple as putting the second request inside the first one's success function.