I'm using jquery tabify with 4 tabs and each content same form calling via ajax.(assume form.php)
1st tab everything works fine with the form.
2nd,3rd and 4th tab failed to get input type="text" value
tabify field with (4 tabs here actually I make it short as the code is long):
$(document).ready(function () {
$('#general_information_tab').tabify();
});
function recp(refer,id,plan){
if(plan == 0)
{
$('.stgcontent').load('stage/stage_procedure1.php?plan_id=' + id + '&T_REFERID=' + refer );
}else{
$('.stgcontent').load('stage/new_taskstg.php?plan_id=' + id + '&T_ID=' + refer);
}
<div id="general_tab_content">
<ul id="general_information_tab" class="general_information_tab">
<li class="active"><a href="#one" onClick="recp('1','<?php echo $plan_id; ?>','0')" >Immediate Response Steps</a></li>
<div id="one" class="content_gi">
<div class="stg1">
<img src="images/task/add.ico" height="10px" width="10px" /> Add Task
<div class="stgcontent">
<script type="text/javascript">
recp('1','<?php echo $plan_id; ?>','0');
</script>
</div>
</div>
</div>
in new_taskstg.php
$(function(){
$(".newTaskSubmitBtn").click(function(){
var T_CONTENT = $(".task_name").val();
var T_REFERID = $(".refer").val();
var SAVE_PLAN = $(".plan").val();
var V_ID = $(".vendor").val();
var dataString='T_CONTENT=' + T_CONTENT + '&T_REFERID=' + T_REFERID + '&SAVE_PLAN=' + SAVE_PLAN + '&V_ID=' + V_ID;
alert(T_CONTENT + T_REFERID + SAVE_PLAN + V_ID);
if(T_CONTENT=='' || T_REFERID=='' || SAVE_PLAN=='' || V_ID=='')
{
//ERROR MESSAGE
$(".fail").show();
$(".success").hide();
}
else
{
$.ajax({
type: "POST",
url: "stage/insert.php",
data: dataString,
success: function(data){
//SUCCESS MESSAGE
$(".success").show();
$(".fail").hide();
}
});
}
return false;
});
});
form field code:
<input type="text" name="task_name" class="form_input task_name" />
TEST I DID :
As above var T_CONTENT = $(".task_name").val(); and prompt like this alert(T_CONTENT); what it shows on 1st tab it able to capture it while the 2nd 3rd and 4th tab failed...
Was suspecting multiple instances problem...
Problem Solved. Mian point is to avoid from multiple instances since tabify couldn't differentiate which tab the form is and it takes 4 tabs together. So to solve my case I just use unique id in 4 forms.
Related
I cannot seem to get my suggestion box to show for the nearest input after adding more inputs dynamically.
The below code is where I am currently, I can see the suggestion box for a new input and add to that new input but if I go back to edit the input data the suggestion box fails to show.
<div id="tester"></div>
<button id="add_test">ADD</button>
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e){
var token = '<?php echo json_encode($token); ?>';
var search = $(this).val();
$.ajax({
type: "POST",
url: "controllers/recipeControl.php",
data: { token: token, search: search },
beforeSend: function(){
$(".flavour-name-input").css("background","#FFF no-repeat 165px");
$(".suggestion-box").css("background","#FFF no-repeat 165px");
},
success: function(data){
$('.flavhey input').closest('flavourInput input').next('.suggestion-box').show();
$('.flavhey input').next('.suggestion-box').html(data);
$(".suggestion-box").css("background","#FFF");
}
});
return false;
});
$(document).on("click",".search-flavour",function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
if(isset($_POST['search'])) {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& json_decode($_POST['token']) === $_SESSION['token']){
$search = $_POST['search'];
$html = '<ul>';
$content = $flavours->getAllFlavoursSearch($search);
foreach ($content as $con) {
$html .= '<li class="search-flavour"><b>'.$con['flavour_name'].'</b> - <i>'.$con['flavour_company_name'].'</i></li>';
}
$html .= '</ul>';
echo $html;
}
}
Ok short version:
Use var box = $(e.target).next(".suggestion-box"); to aquire a reference to the correct suggestion box in the success handler of the ajax request.
Long version:
I replaced the php parts with static placeholders to get a runnable example.
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e) {
var token = "[token]";
var search = $(this).val();
var box = $(e.target).next(".suggestion-box");
box.show();
box.html("TestData");
box.css("background", "#FFF");
return false;
});
$(document).on("click", ".search-flavour", function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tester"></div>
<button id="add_test">ADD</button>
<ul>
<li class="search-flavour">
<b>flavour_name_1</b> - <i>flavour_company_name_1</i>
</li>
<li class="search-flavour">
<b>flavour_name_2</b> - <i>flavour_company_name_2</i>
</li>
<li class="search-flavour">
<b>flavour_name_3</b> - <i>flavour_company_name_3</i>
</li>
</ul>
Now being able to execute your code I was able to reproduce the described error. Please try to provide a runnable example next time.
I realized that your box was only appearing once because the call to .show() wasn't working at all. It was visible from the beginning just without any content so you couldn't see it, then after setting html() it had content and it looked like the call to show() worked as intended.
Afer you clicked on a .search-flavour all boxes were correctly hidden and thus never appeared again.
So to fix this, replace the success handler of the ajax request with this:
success: function(data){
// e.target is the currently active input element
var box = $(e.target).next(".suggestion-box");
box.show()
.html(data)
.css("background", "#FFF");
}
I don't know what i did wrong in the ajax call. I want to return the data back to my script and work with it but its not returning result. Here are some things i will like to clarify as well as i am new to ajax programming. if the ajax call is successful and it returns result to the script. Where in the script will the result be. Will i have to create an array that holds the result or ...
Here is the html
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
<div id="response"></div>
<div>
<label>Name</label><input type="text" name="name" id="nameid">
</div>
<div>
<label>Phone Number</label><input type="text" name="phone" id="phoneid">
</div>
<div>
<button type="submit" class="btn" id="btnsubmit">Submit</button>
</div>
</form>
<div id="success"></div>
//my script
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
function submitForm(formData){
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
}
If you are trying ajax form submission and need to populate the result in the success div without refresh, you need return false
Don't use
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
Here don't need the action in form, try like
<form id="reserveform" onsubmit="return submitForm();">
In function use form serialize so all input elements value in form will available
function submitForm(){
var formData = $("#reserveform").serialize();
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
return false; // use this otherwise the form will be submitted and results an entire page refresh
}
please try this
you have to put the btnsubmit click event inside onload or document ready
$(document).ready(function()
{
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
}
);
You cant use like this $("#success").html(data); because data is in json format. here, the data is an object. You need to parse it and assign to tags.
I see you configured the form to submit to the same document that you are in already. This is fine, we do this all the time.
However, you are also stopping the form from submitting and then using AJAX to submit the values. You specify reservation.php as your ajax processor. Is this the same PHP page you are on already? If so, then I know what the problem is: you can't do that.
By design, AJAX must use an external PHP file to process the AJAX. If you try to do this inside the same document, the AJAX will only echo back the full HTML of the document itself.
Short answer: use an external PHP file. This is by design.
See this other answer for more information about exactly this issue.
See these other posts for further info about AJAX and getting info into the PHP processing script, and returning info back from the PHP processing script:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
I am currently working with a wmd editor and jQuery-UI tabs. I have created an ajax/js function that will submit (when next button is clicked) the wmd-preview value and then php echo the result in tab 2. The problem is that I am not getting any results displayed. I am not looking for the textarea value but the div #wmd-preview value. How can I display the value of the div wmd-preview through my ajax/function?
JS
<script>
$(function () {
var $tabs = $('#tabs').tabs({
disabled: [0, 1],
select: function () {
$.ajax({
type: "POST",
url: "post_tabs.php",
data: {
"wmd": $("#wmd-preview").val(),
},
success: function (result) {
$("#tab-2").html(result);
}
});
}
});
$(".ui-tabs-panel").each(function (i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 2;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab').click(function () {
var currentTab = $('#tabs').tabs('option', 'selected');
if (
(
currentTab == 0 && /*(B)*/
$.trim($('#wmd-input').val()).length > 0
)
) {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex).tabs('select', tabIndex).tabs("option", "disabled", [0, 1]);
} else {
switch (currentTab) {
case 0:
alert('Please fill out all the required fields.', 'Alert Dialog');
break;
}
}
console.log("preventing default");
return false;
});
$('.prev-tab').click(function () {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex).tabs('select', tabIndex).tabs("option", "disabled", [0, 1]);
return false;
});
});
</script>
PHP
<?
if (isset($_POST['wmd'])){
$wmd = $_POST['wmd'];
echo ('<div id="text_result"><span class="resultval"><h2>Textarea Echo result:</h2>'.$wmd.'</span></div>');
}
?>
HTML
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<div id="wmd-button-bar"></div>
<textarea id="wmd-input" name="wmd-input" cols="92" rows="15" tabindex="6"></textarea>
<div id="wmd-preview"></div>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
</div>
PHP code should start with <?php , yours start with <? which is incorrect.
When you see PHP code presented as text - it should tell you it is not running, this is why you keep getting output like '.$wmd.''); } ?> instead of real PHP echo output.
The other comment still stands as well - you should either use $("#wmd-preview").html() or $("#wmd-input").val() but you cannot use val on divs, it does not work.
In this scenario $("#wmd-input").val() is the better choice just because this is the reason input fields exist - to get input.
Let me know if there are more questions I can help with.
I have a Google Instant style jQuery search script that queries a PHP file then parses the results into an HTML div. It uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/.
My problem is, when the user searches for something and then selects a new search type (clicks on a tab) they have to go to the text box and press enter to submit their query again. How can I make it so when a search is active and a tab is clicked that it loads the results straight away instead?
I hope you can understand what I'm trying to describe. JSfiddle: http://jsfiddle.net/phWSR/
My current jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
});
$('#type_search').click();
$('input').keyup(function () {
query = $(this).val();
url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
});
My current HTML code is:
<div id='nav'>
<a id='type_search'>All</a>
<a id='type_images'>Images</a>
<a id='type_videos'>Videos</a>
<a id='type_news'>News</a>
<a id='type_social'>Social</a>
</div>
<input type='text' autocomplete='off'>
<div id='results'></div>
You could isolate the code for the ajax call (currently in $('input').keyup()) in a separate function, and bind it to both $('input').keyup() and $('#nav a').click().
Hey all, I am facing a rather serious security error. Let me first outline my code.
<li class="comment">
<form action="" method="POST" name="edit-form" class="edit-area">
<textarea style="width: 100%; height: 150px;"><?php echo $response->comment; ?></textarea>
</form>
<div class="comment-area" style="padding-top: 2px"><?php echo (parseResponse($response->comment)); ?></div>
<p class="ranking">
<?php if ($response->user_id == $user_id) : ?>
Edit • Delete
<?php else : ?>
Like (<?php echo $response->likes; ?>) • Dislike (<?php echo $response->dislikes; ?>)
<?php endif; ?>
</p>
</li>
is what I got in my body, and here's the relevant JS
$('.editting').bind('click', function(event) {
var num = $(this).data('edit');
var user = $(this).data('user');
if ($(this).hasClass('done')) {
var newComment = $('#comment-' + num + ' .edit-area textarea').val();
var dataString = 'newComment='+ newComment + '&num=' + num;
if(newComment == '')
{
alert('Comment Cannot Be Empty!');
}
else
{
$.ajax({
type: "POST",
url: "edit.php",
data: dataString,
success: function(){}
});
$('#comment-' + num + ' .edit-area').slideDown('slow', function() {
$('#comment-' + num + ' .edit-area').addClass('invisible');
});
$('#comment-' + num + ' .comment-area').slideUp('slow', function() {
$('#comment-' + num + ' .comment-area').removeClass('invisible');
});
$(this).removeClass('done');
$(this).html('Edit');
}
}
else {
$('#comment-' + num + ' .comment-area').slideDown('slow', function() {
$('#comment-' + num + ' .comment-area').addClass('invisible');
});
$('#comment-' + num + ' .edit-area').slideUp('slow', function() {
$('#comment-' + num + ' .edit-area').removeClass('invisible');
});
$(this).html('Done');
$(this).addClass('done');
}
return false;
});
which works fine, but i'm having an issue. If the user finds a comment (not by them) and uses a plugin like firebug, they can replace the response->short with another, and edit ANY comment. Of course, within edit.php, I could check the short against the response table and see if the user checks out, but i'd like to find a way to not show the text area unless that response is for-sure by that user.
Is this possible?
Thanks in advance,
Will
Is this possible?
Sure...but it'll do nothing to stop the user/fix your security hole. To fix this check server-side, always double-check anything that should be secure server-side, never trust your input. The users trying to do something malicious won't be stopped by anything in JavaScript...sending data to your server that they shouldn't is exactly what they'll do first.
Like Nick said; never ever trust a JavaScript test!
It will/might work for "regular users", but when it comes down to avoiding hacks, you might as well ask the hacker to click a button to "prove" his input is valid!
Your validator script is running on someone else's computer, so he/she will be able to manipulate it (or even turn it of using NoScript etc. )