I have some HTML and Ajax set up so that if you click a certain image (the reply-quote class below), it initiates some Ajax to echo HTML elsewhere on the page.
As shown below, the HTML file contains the same block of divs multiple times. My problem is that, if a user clicks the image, how can I make Ajax show the HTML (within show-reply div) for that specific block and not all of them?
<!-- BLOCK ONE -->
<div class="style1">
<div class="style2">
<img src="image.png" class="reply-quote" />
<div class="style3">
<div class="style4">
<div id="show-reply"></div>
<div class="reply-box">
<form class="reply-container no-margin" method="POST" action="">
<textarea class="reply-field" name="new_comment" placeholder="Write a reply..."></textarea>
<button name="submit" class="btn" type="submit">Post</button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- BLOCK TWO -->
<div class="style1">
<div class="style2">
<img src="image.png" class="reply-quote" />
<div class="style3">
<div class="style4">
<div id="show-reply"></div>
<div class="reply-box">
<form class="reply-container no-margin" method="POST" action="">
<textarea class="reply-field" name="new_comment" placeholder="Write a reply..."></textarea>
<button name="submit" class="btn" type="submit">Post</button>
</form>
</div>
</div>
</div>
</div>
</div>
Here's the JQuery I have right now:
$(document).ready(function() {
$(".reply-quote").click(function() {
$.ajax({
url: 'assets/misc/show_reply.php', // this file simply echoes back the HTML to the `show-reply` div
type: "POST",
data: {post_id: $(this).attr('id')},
success: function(data) {
$("#show-reply").append(data); // this is where the problem lies
}
});
});
});
To my understanding, I have to somehow implement $(this), parent(), find(), etc. instead of the current line I'm using ($("#show-reply").append(data);). The question is, what should that line be so that if I click the image, it only shows the HTML for that specific block?
Please help!
First: ID should be unique in a document, use class attribute instead for show-reply and other elements where id is repeated
<div class="show-reply"></div>
then you need to find the show-reply next to the clicked reply-quote image
$(document).ready(function() {
$(".reply-quote").click(function() {
var $reply = $(this);
$.ajax({
url: 'assets/misc/show_reply.php', // this file simply echoes back the HTML to the `show-reply` div
type: "POST",
data: {post_id: $(this).attr('id')},
success: function(data) {
$reply.closest('.comment-container').find(".show-reply").append(data);
}
});
});
});
try this
$("div").click(function(e) {
if($(e.target).is('.reply-quote')){
e.preventDefault();
return;
}
alert("work ");
});
You should change the id="show-reply" to class="show-reply" in html, and then in JS change $("#show-reply").append(data); to $(this).parent(".show-reply").append(data);
Related
I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>
I want to show selected data by user on ajax call.
Scenario is that I have two radio buttons, and when user clicks on either one it should show the respective data on the right side, in the response div.
HTML:
<form id="package-call" method="post" accept-charset="utf-8">
<div class='pakges'>
<div class="sub-pakge">
<div class="sub-pakge-content">
<span class="content-title">North America</span><br>
<span class="content-title">Basic</span>
<div class="content-time">150 Minutes</div>
<span class="content-price">Rs.500</span>
<div class="pakges-radio"><input type="radio" name="package" id="package" > </div>
</div>
</div>
<div class="sub-pakges">
<div class="sub-pakges-content">
<span class="content-title">North America</span><br>
<span class="content-title">Max</span>
<div class="content-time">400 Minutes</div>
<span class="content-price">Rs.200</span>
<div class="pakges-radio"><input type="radio" name="package" id="package"> </div>
</div>
</div>
</div>
</form>
AJAX:
$("#package").click(function(e){
$.ajax( {
type: "POST",
url: "package _selection.php",
data: $('#package_call').serialize(),
success: function( response ) {}
});
});
This is the div where i want to show my response:
<div class="form-results">
<div class="rslt-content-main">
<div class="rslt-content">Selected Pakages / Bolts</div>
<div id="package_response"></div>
</div>
</div>
And these are the result div's that i want to get through ajax call from package _selection.php and want to display respectively
<div class="radio_one_rslt">
<div>voice:</div><br />
<div>IDD Asia - Rs 200</div>
</div>
<div class="radio_two_rslt">
<div>voice:</div><br />
<div>IDD Asia - Rs 500</div>
</div>
For listening to a radio button, use the 'change' event
$("#package").on('change', function(e){
Then, assuming your response is the HTML you want to append, append it in your success callback
$.ajax( {
type: "POST",
url: "package _selection.php",
data: $('#package_call').serialize(),
success: function( response ) {
$('#package_response').append(response);
}
});
A blog post for reference: http://blog.stephenborg.com/?p=37
I have been using this to process a form via AJAX and jQuery
$("#uploadBtn").click(function()
{
var formData = new FormData($('form')[0]); //--FormData here, problem line
$.ajax({
url: 'resources/ajax/ajax_upload_video.php',
type: 'POST',
xhr: function()
{
xhr = $.ajaxSettings.xhr();
if (xhr.upload)
{
xhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return xhr;
},
success: function(msg)
{
log(msg);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
It has been working fine. I added a second form on the page (Search on top, uploader on bottom)
I understand the $('form')[0] will grab the first form on the page, so naturally I changed my javascript to $('form')[1]. When I do a console.log on it, it is the correct form.
When I hit the upload button, but my php file says nothing was posted. For simplicity sake, my php file is this:
<?php
var_dump($_POST);
?>
I get just an empty array. I even gave the form I want an ID and called it this way $('#uploadForm').
I have 1 multi-select FILE input, a hidden field and a text input field.
What am I doing wrong with the FormData object?
One side not, I've been developing this page locally using WAMP and just moved it to our CentOS server that is online. Could this be a PHP setting that isn't the same as my local environment? I can't think of what PHP setting would have to do with POST
Upload Form
<form id="videoUploadForm" method="post" enctype="multipart/form-data" class="upload-form modal-edit-form">
<div class="modal-body">
<p>
<div align="center" id="fileSelect">
<input type="hidden" value="video" name="mediaType" id="mediaType" />
<input type="hidden" value="<?php echo $_GET['reelId']; ?>" name="reelId" id="reelId" />
<input type="file" name="videos[]" id="videos" accept="video/mp4" multiple />
</div>
<br>
</p>
<p>
<div id="dropbox">
<ul class="hide" id="filelist">
</ul>
<div align="center" id="nofiles">Select some file to begin</div>
</div><br>
</p>
<p>
<hr>
<label>Search Tags <small>[at least two tags separate by comma]</small></label>
<input type="text" class="span5" name="searchTags" id="searchTags" disabled />
</p>
<hr>
<p align="center">
<img src="resources/img/loader.gif" class="hide" id="loader" />
<button type="button" class="btn btn-info" name="uploadBtn" id="uploadBtn" disabled><i class="icon-circle-arrow-up icon-white"></i> Begin Upload</button>
<div id="successfulUpload" class="alert alert-success hide">
<b>The videos have been successfully uploaded.</b><br/>
</div>
</p>
</div>
</form>
Try accessing it this way:
var form = document.getElementById('form-id');
var formData = new FormData(form);
From this page on FormData.
I am using a dialog box to display and submit a enquiry form on my page.I am having problem when I try to call it again and again.The first time everything works fine and the form s submitted successfully.But if I click the GO button(added html below).I get an error for this line document.
EDITED:
<div class="hidden" id="dialog">
<form action="index.php" class="testForm" id="testForm">
<div class="name" id="name">
<div class="displayName" id="dispName">Name</div>
<div class="textName" id="viewName"><input type="text" class="fname" id="fullName" /></div>
<div class="hide" id="nameErr"></div>
</div>
<div class="address" id="addressDetails">
<div class="displayAddress" id="dispAddress">Address</div>
<div class="textAddress" id=""><input type="text" class="taddress" id="fullAddress" /></div>
<div class="hide" id="addressErr"></div>
</div>
<div class="submitForm" ><input type="button" class="submitDetails" id="submitInfo" name="Submit" value="Submit" onClick="validateAndSubmitForm()"/>
<a name="Close" onclick="$('#dialog').dialog('close');">Close</a>
</div>
</form>
</div>
Javascript\jquery
function submitEnquiryForProperty()
{
document.forms.testForm.reset();
$("#dialog").dialog({
modal:true,
resizable:false,
autoOpen:false,
width:260,
});
openDialog();
}
function openDialog(){
$("#dialog").dialog("open");
}
function closeDialog(){
$("#dialog").dialog("close");
}
Callback function on form submit
$.ajax({
type:'POST',
url:"processForm.php",
data:"name="+name+"&address="+address,
dataType:"html",
success:function(msg){
if(msg=="success"){
$("#dialog", window.parent.document).html("<div class='pad5'><div class='flt' style='padding-left:3px; width:235px;'><div class='thanx_msg'>Thank you for submitting the details. <br /><div class='spacer5'> </div><span class='gre'>Our Sales team shall revert to your query soon.</span></div></div><div class='spacer5'> </div><div style='padding-left:3px;' class='text'><strong>You can also:</strong></div><div style='margin-left:20px; line-height:20px;'>• Apply for a <a href='homeloan.php'>Home Loan</a><br />• Visit <a href='http://www.proptiger.com'>proptiger.com</a> for more properties<br />• See our <a href='http://www.proptiger.com/blog'>Blog</a> for latest updates</div></div><br/><div class='msg' style='color:red;'>Click to close the box</div>");
$(function(){
$('#dialog').click(function() {
closeDialog();
});
});
}
else
{
alert("Operation cannot be completed,please try again");
}
}
But I am facing the same problem.Error at the .reset() line.
Thanks for your time.
Updated answer
If you want to have a reusable dialog, do it like this:
Include the dialog element (almost assuredly a <div>) in your initial HTML. Use a CSS class so that it will not be immediately visible, for example:
HTML:
<div id="dialog" class="hidden">...</div>
CSS:
.hidden { display: none }
Unconditionally call $("#dialog").dialog(options) from Javascript immediately after the page loads. Be sure to set autoOpen: false in the options.
Whenever you want to display the dialog, use $("#dialog").dialog("open").
Whenever you want to hide the dialog, use $("#dialog").dialog("close").
Repeat steps 3 and 4 as much as you like.
.dialog( "destroy" )
Remove the dialog functionality completely. This will return the element back to its pre-init state.
.dialog( "close" )
Close the dialog.
I have any page for answer/question. i retrieve list of question for admin. admin see this. now i need to send answer to each question. so i for each question put textarea and form with post action. now i need to when send answer of question message, if send message to external php files = true; of message(ID) remove(jquery slideup effect). for this i have jquery submit form code ( without refresh page ) but I have big problem. this worked ONLY with one form ! and not worked for all list form ( question + answer form ) . how to worked my code for multiple form ? I chose the right way?
html code :
<form action="insert.php?id=42" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=45" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=48" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=50" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
Thanks
Your major issue is probably that you are trying to reuse ids. All the forms have the id of "forms" and you are also sharing the id "box".
All ids should uniquely identify an element. Use a class when you need to classify an element. I'd recommend you change id="forms" on all the forms to class="reply_form" and then also change id="box" on all the divs to class="reply_box". Then change styles set for #forms and #box to those set for .reply_form and .reply instead.
EDIT - tweaks made in jsfiddle after some discussion with the OP.
http://jsfiddle.net/gvnfg/5/
just change the selector. id attribute must be unique in html
$("[name='form']").submit(function() {
$this = $(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
cache: false,
beforeSend: function() {
$('#loading').show();
$('#result').hide();
},
success: function(data) {
if(data==1){
$('#loading').hide();
$('#result').fadeIn('slow').html("ok");
$('#result').addClass('true');
$this.slideUp(1000);
}
else {
$('#loading').hide();
$('#result').fadeIn('slow').html(data);
$('#result').addClass('errors');
}}
});
e.preventDefault();
return false;
});
use Jquery .each() method:
$(document).ready(function() {
$('#forms').each(function() {
this.submit(function() {
$.ajax({ ... });
});
});
})