I am working with an ajax form that it is suppose to submit with a button click. I have seen similar projects but I am running into dead ends. The problem i am having is that the input field values are not getting echo in tab 2. I set a parameter var currentTab to indicate and compare when a click has been made to the next tab.
How can I display the value of the input fields after a click has been made?
(Additional) Also how can adapt the code if in the future I have multiple tabs with input fields and the last tab will be where the values get php echo out?
Thank you
AJAX/JS Function
<script>
var currentTab = 0;
$(function() {
var $tabs = $('#tabs').tabs({
disabled: [0, 1]
, select: function() {
if (currentTab == 0) {
$.ajax({
type: "POST",
url: "tabs.php",
data: { "textarea": $("#textarea_input").html(),
"title": $("#title_input").html()
},
success: function(result) {
$("#tab-2").html(result);
}
});
}
}
, show: function(event, ui) {
currentTab = ui.index;
}
});
$(".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, .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['title'])){
$title = $_POST['title'];
echo ('<div id="title_result"><span class="resultval"><h2>Title Echo result:</h2>'.$title.'</span></div>');
}
if (isset($_POST['textarea'])){
$textarea = $_POST['textarea'];
echo ('<div id="textarea_result"><span class="resultval"><h2>Textarea Echo result:</h2>'.$textarea.'</span></div>');
}
?>
HTML Tab2 is where the results should be php echo out
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<label for="title">Title</label>
<input type="text" id="title_input" name="title_input" size="60" autocomplete="off" value="<?=$title?>"/><br>
<label for="textarea_input">Textarea</label>
<textarea id="textarea_input" name="textarea_input"><?=$textarea?></textarea>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<div id="title_result" style="padding:20px;"></div>
<div id="textarea_result" style="padding:20px;"></div>
</div>
A few comments :
You should first add the echoed html from PHP, only then can you access it from jquery with $("#resultval")
I will explain - look at your "success" handler
success: function(result) {
$('#textarea_result').html( $('#resultval', result).html());
$('#title_result').html( $('#resultval', result).html());
}
The code should be
success: function(result) {
$('#textarea_result').html( result);
$('#title_result').html( result);
}
If at all.. but I don't think that it what you meant.
If you want to ask me - render the entire next tab in PHP and do something like $("#tab2").html(result);
Comment #2
You have 2 identical IDs - resultval..
Comment #3 -
You are sending "textarea" and "title" in Ajax, but referring to $_POST["textarea_input"] and $_POST["title-input"]
Comment #4 -
You are using $("#textarea-input").html() to get the value instead of $("#textarea-input").val(). same for "title_input"
Here is my working version ( just remove the "head" stuff ).
This is my main.php -
<html>
<head>
<link rel="stylesheet" type="text/css" href="/stackoverflow/public/jquery-ui-1.8.22.custom.css" media="screen" />
<script src="/stackoverflow/public/jquery-1.7.2.min.js"></script>
<script src="/stackoverflow/public/jquery-ui-1.8.22.custom.min.js"></script>
</head>
<body>
<div id="page-wrap">
<div id="tabs">
<ul>
<li> TAB1</li>
<li> TAB2</li>
</ul>
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<label for="title_input">Title</label>
<input type="text" id="title_input" name="title_input" size="60" autocomplete="off" value="my title"/><br>
<label for="textarea-input">Textarea</label>
<textarea id="textarea-input" name="textarea-input"></textarea>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
</div>
</div>
</div>
<script>
var currentTab = 0;
$(function() {
var $tabs = $('#tabs').tabs({
disabled: [0, 1]
, select: function() {
console.log("selecting a new tab " + currentTab);
if (currentTab == 0) {
$.ajax({
type: "POST",
url: "tabs.php",
data: { "textarea": $("#textarea-input").val(),
"title": $("#title_input").val()
},
success: function(result) {
$("#tab-2").html(result);
}
});
}
}
, show: function(event, ui) {
currentTab = ui.index;
}
});
$(".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, .prev-tab').click(function() {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex)
.tabs('select', tabIndex)
.tabs("option","disabled", [0, 1]);
return false;
});
});
</script>
</body>
</html>
And this is my "tabs.php"
My working example can be found at my site
<?php
echo "This is the result are you ready?";
if (isset($_POST['title'])){
$title = $_POST['title'];
echo ('<div id="title_result"><span id="resultval"><h2>Title Echo result:</h2>'.$title.'</span></div>');
}
else{
echo "title_input is not defined!";
}
if (isset($_POST['textarea'])){
$textarea = $_POST['textarea'];
echo ('<div id="textarea_result"><span id="resultval"><h2>Textarea Echo result:</h2>'.$textarea.'</span></div>');
}
?>
Let me know if there's anything else.
You may want to look into cleaning up your HTML first and utilizing PHP correctly... your HTML tab 2 should be:
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<label for="title">Title</label>
<input type="text" id="title_input" name="title_input" size="60" autocomplete="off" value="<?=$title?>"/><br>
<label for="textarea-input">Textarea</label>
<textarea id="textarea-input" name="textarea-input"><?=$textarea?></textarea>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<div id="title_result" style="padding:20px;"></div>
<div id="textarea_result" style="padding:20px;"></div>
</div>
You had an extra quote after title_input name and also when you want to spit out PHP code without an echo, use it like this:
<?=$title?>
also by the way, you have additional dirty code in your php... this:
if (isset($_POST['title_input"'])){
$title = $_POST['title_input"'];
echo ('<div id="title_result"><span id="resultval"><h2>Title Echo result:</h2>'.$title.'</span></div>');
}
should be:
if (isset($_POST['title_input'])){
$title = $_POST['title_input"'];
echo ('<div id="title_result"><span id="resultval"><h2>Title Echo result:</h2>'.$title.'</span></div>');
}
you had an additional quote in the php here:
$_POST['title_input"']
go through and clean up your code
Related
This is controller.php
<?php
class Autocomplete extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('datacomplete');
}
public function index($id)
{
echo $id;
$this->load->view('view_demo', $data);
}
public function GetCountryName()
{
$keyword = $this->input->post('keyword');
$data = $this->datacomplete->GetRow($keyword);
echo json_encode($data);
}
}
?>
This is a model
<?php
class Datacomplete extends CI_Model
{
public function GetRow($keyword)
{
$this->db->order_by('id', 'DESC');
$this->db->like("name", $keyword);
return $this->db->get('autocomplete')->result_array();
}
}
this is view.php
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled and minified JavaScript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js">
</script>
<script src="<?php echo base_url(); ?>assets/custom.js">
</script>
</link>
</head>
<body style="background-color: #000000;">
<?php echo $id= 1; ?>
<form action="<?php echo base_url('autocomplete/index/' .$id); ?>" method="post">
<div class="row">
<center>
<h2 style="color: #fff;">
AUTOCOMPLETE FORM FROM DATABASE USING CODEIGNITER AND AJAX
</h2>
</center>
<div class="col-md-4 col-md-offset-4" style="margin-top: 200px;">
<label class="control-lable" style="color: #fff;">
Country Name
</label>
<input autocomplete="off" class="form-control" id="country" name="country" placeholder="Type to get an Ajax call of Countries" style="height:70px" type="text">
<ul aria-labelledby="dropdownMenu" class="dropdown-menu txtcountry" id="DropdownCountry" role="menu" style="margin-left:15px;margin-right:0px;">
</ul>
<input type="submit">
</input>
</input>
</div>
</div>
</form>
</body>
</html>
This is custom.js file
$(document).ready(function() {
$("#country").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/codeajax/autocomplete/GetCountryName",
data: {
keyword: $("#country").val()
},
dataType: "json",
success: function(data) {
if (data.length > 0) {
$('#DropdownCountry').empty();
$('#country').attr("data-toggle", "dropdown");
$('#DropdownCountry').dropdown('toggle');
} else if (data.length == 0) {
$('#country').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue">' + value['name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#country').val($(this).text());
});
});
I want to fetch the id of the country dynamically in the URL after clicking the submit button.
Now I have this using static passing id as 1.
the table has two column id and name of the country.
how to pass the id dynamically to url when I click the submit button.
I m failing to fetch the id dynamically from database ie when I click on submit should redirect to the new page with country id or echo $id in the new page as well as to the URL it should show me id of the country
You could achieve it using javascript.
First change the form :
<form action="<?php echo base_url('autocomplete/index/' .$id); ?>" method="post">
To :
<form method="post" id="countryForm">
Then change the submit button :
<input type="submit">
To :
<input type="submit" id="submitForm" disabled>
And then apply the following javascript codes :
$(document).ready(function() {
$("#country").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/codeajax/autocomplete/GetCountryName",
data: {
keyword: $("#country").val()
},
dataType: "json",
success: function(data) {
if (data.length > 0) {
$('#DropdownCountry').empty();
$('#country').attr("data-toggle", "dropdown");
$('#DropdownCountry').dropdown('toggle');
} else if (data.length == 0) {
$('#country').attr("data-toggle", "");
}
// Assign each country id into each country list `data-` element
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" data-countryid="' + value['id'] + '" class="dropdownlivalue">' + value['name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#country').val($(this).text());
$('#countryForm').attr('action', '<?php echo base_url('autocomplete/index/'); ?>' + $(this).data('countryid'); // set new form action which contain country id
$('#submitForm').removeAttr('disabled'); // enable the submit button after one country is selected
});
});
So I've got this small draggable item that I am able to drag and drop in the canvas I've created and that is working perfectly fine, however as I want to save the position of the draggable item when the item is dropped, I am using ajax to post to PHP where PHP will then store it in sessions.
However it is simply not posting. No error shows. The $_POST[] simply returns nothing.
Notice I have set value of the ajax data to 1. I am hardcoding atm for testing purpose.
page-online-tool.php
<div id="Canvas" class="col-xs-6">
<div class="col-xs-11" id="Purse_Background"></div>
<div class="col-xs-1">
<div id="FLOWER_Blue" class="draggable ui-widget-content">
<img src="imgs/blue_01.png" alt=""/>
</div>
<p id="pos_T" ></p>
<p id="pos_R" ></p>
<p id="pos_B" ></p>
<p id="pos_L" ></p>
<input type="text" id="id_input_01" name="name_input_01" value=""/>
<?php
if(isset($_POST['Blue_Top_Position'])) {
$Blue_Top_Position = $_POST['Blue_Top_Position'];
echo $Blue_Top_Position;
} else {
echo 'fail';
}
?>
</div>
</div>
<?php include 'footer.php'; ?>
JQUERY.JS
$(document).ready(function () {
$('#FLOWER_Blue').draggable({
containment: "#Canvas",
scroll: false,
drag: function(event, ui){
$BLUE_T = ui.position.top;
$BLUE_R = ui.position.right;
$BLUE_B = ui.position.bottom;
$BLUE_L = ui.position.left;
$('#pos_T').text('TOP: ' + $BLUE_T);
$('#pos_R').text('RIGHT: ' + $BLUE_R);
$('#pos_B').text('BOTTOM: ' + $BLUE_B);
$('#pos_L').text('LEFT: ' + $BLUE_L);
$('#id_input_01').val(ui.position.top)
},
stop: function(event, ui){
$.ajax({
url:'http://localhost/42_TEST/page-online-tool.php',
type: 'post',
data: {Blue_Top_Position : 1},
done: function(data) {
console.log('done');
}
}).fail (function() {
alert('error');
})
}
}
);
});
I have a PHP page with a search function and I use AJAX for pagination. When I submit my search input, AJAX should grab the input and pass it to the PHP page which will further query the database. The last bit does not work and I have been struglling to understand why. Could anyone help please. The code I have is below:
PHP/HTML page with form:
<form action="" id="postData" method="post">
<p><b> Search all videos in database below: </b></p>
<ul><center>   Keywords: </center>
<input type="text" id="input" name="input" size="50" maxlength="64">
</ul>
<ul>
<center><input type="submit" name = "submit" value ="Search"></center>
</ul>
</form>
Javascript with AJAX:
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='../images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "POST",
url: "search_videos.php",
data: { 'page': page, 'input': $('#postData').serialize()},
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}
});
});
PHP to query and print the results:
<?php
if($_POST['page'])
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 5;
$previous_btn = true;
$next_btn = true;
$start = $page * $per_page;
include"core/database/connect.php";
// Get the input of the selected video
$input = $_POST['input'];
//$input = 'video';
echo $input; // CANNOT get input variable from the initial form!
... The mysql query and rest of the code continued ...
HTML:
<div>
<p><b> Search all videos in database below: </b></p>
<ul>
<li>
<label for="keywords">Keywords</label>
<input type="text" id="keywords" name="keywords" size="50" maxlength="64" />
</li>
<li>
<button onClick="loadData()">Search</button>
</li>
</ul>
</div>
<div id="container">
</div>
Javascript:
$(document).ready(function(){
// ...
function loadData()
{
loading_show();
$.ajax
({
type: "POST",
url: "http://yourwebsite.com/search_videos.php",
data: { 'keywords': $('#keywords').val() },
success: function(msg)
{
loading_hide();
$("#container").html(msg);
}
});
}
});
PHP:
echo $_POST['keywords'];
i am using Ajax to make a filtered search system. I have three different tabs where users can search by names, by category and location.
I am able to seacrh when user enters name in the search box(tab-1).
In second tab, how can I use the same Ajax, so when user clicks a link, the id is passed in the ajax script to my php, and that id is passed as varibale in my mysql query.
First time with Ajax, any help would be highly appreciated.
AJAX script:
$(document).ready(function () {
$("#search_results").slideUp();
$("#button_find").click(function (event) {
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function (event) {
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way() {
$("#search_results").show();
var search_this = $("#search_query").val();
$.post("search.php", {
searchit: search_this
}, function (data) {
$("#display_results").html(data);
})
}
html:
<form id="searchform" method="post">
<input id="search_query" name="search_query" placeholder="What You Are Looking For?"
size="50" type="text" />
<input id="button_find" value="Search" type="submit" />
</form>
<div id="display_results">
</div>
<div class="tab">
<input id="tab-2" name="tab-group-1" type="radio" />
<label for="tab-2">Search by Category</label>
<div class="content">
<div id="searchbycategory">
<div id="nav_1_a">
<ul>
<li>All Categories</li>
<li>Category-1</li>
<li>Category-2</li>
<li>Category-3</li>
</ul>
<div id="display_results">
</div>
</div>
<!-- END nav_1_a -->
</div>
</div>
</div>
<div class="tab">
<input id="tab-3" name="tab-group-1" type="radio" />
<label for="tab-3">Search by location</label>
<div class="content">
<div id="searchbylocation">
<div id="nav_1_a">
<ul>
<li>All</li>
<li>Location-1</li>
<li>Location-2</li>
<li>Location-3</li>
<li>Location-4</li>
</ul>
</div>
search.php:
<?php
$connection = mysql_connect('localhost', 'user', 'pwd');
$db = mysql_select_db('db', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term);
echo "Enter name to search";
else{
$sql = mysql_query("select col1,col2 from tab2 where tab2.somecolm like
'{$term}%'", $connection);
echo "<ul>";
if (mysql_num_rows($sql)){
while($info = mysql_fetch_array($sql, MYSQL_ASSOC ) ) {
echo "<li>";
echo "" . $info['col2'] . "";
echo "</li>";
}
}else{
echo "No matches found!";
}
echo "</ul>";
}
?>
Pass block id to search_ajax_way function:
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way(this.id);
});
Then pass block id in data param in ajax request:
function search_ajax_way(blockId){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this, 'blockId': blockId}, function(data){
$("#display_results").html(data);
})
}
Now blockId will be availible in your php script as $_POST['blockId'].
You say you want to pass the id when a link is clicked, but you don't have any code that handles link clicks. Add a click handler for links, and modify search_ajax_way() to accept an optional id for when links are clicked:
$("a").click(function (event) {
event.preventDefault();
search_ajax_way(this.id);
});
function search_ajax_way(clickedId) {
$("#search_results").show();
var postData = { searchit: $("#search_query").val() };
if (clickedId) {
postData.clickedId = clickedId;
}
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}
The id will be available in PHP as $_POST['clickedId']
Edit: Actually, I'd refactor to use search_ajax_way() as the event handler, rather than calling it from an anonymous event handler:
$("#button_find,a").click(search_ajax_way);
$("#search_query").keyup(search_ajax_way);
function search_ajax_way(event) {
event.preventDefault();
$("#search_results").show();
var postData = {
searchit: $("#search_query").val(),
clickedId: this.id
};
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}
I have a form with select fields dynamically generated and with the options taken from php (same for all the selects). But I need that every <select>...</select> must be shown in a different line. This can be done having every <select>...</select> inside a <div>...</div>.
This is the code that I have, it´s working but the select fields are not within a div:
<script type="text/javascript">
//<![CDATA[
$(function(){
var counter = 1;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var select = $('<select>').attr({id:'select'+counter,name:'select'+counter});
$.ajax({
url: 'selects.php',
dataType: "html",
success: function(data) {
select.html(data);
}
});
select.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#select" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
//]]>
</script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='text' id='textbox1' >
</div>
<div id="TextBoxDiv2">
<label>Textbox #2 : </label><input type='text' id='textbox2' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
And this is the html code generated by select.php:
<option value="1">Uno</option>
<option value="2">Dos</option>
<option value="3">Tres</option>
<option value="4">Cuatro</option>
Use the wrap() function. :
Put this code just before the counter++;. :
$("#TextBoxesGroup > select").wrap ( function () {
return '<div id="wrap_' + this.id + '"></div>';
} );
See it in action at jsFiddle.