My PHP code looks like this -
for ($i=0;$i<=10;$i++) {
?>
<div id="">
<input type="text" id="GetCommentText-<?php echo $i;?>"></input>
<input type="hidden" id="GetPostID-<?php echo $i;?>" value="<?php echo $i;?>">
<button type="button" id="SelectPostComment-<?php echo $i;?>" >Submit</Submit>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
I want to get the data of these <input> elements using jquery dynamic id selectors. My jQuery looks like -
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("[id^=SelectPostComment-]").click(function(){
var $td = $(this).closest('input').next();
var CommentText = $td.find("[id^=GetCommentText-]").val();
var PostID = $td.find("[id^=GetPostID-]").val();
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: CommentText, PostID: PostID},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>
But I'm not getting value of ajax data CommentText and PostID in my test1.php file when i click <button>. Not sure what mistake I'm making. Please help.
try this:
for ($i=0;$i<=10;$i++) {
?>
<div id="">
<input type="text" id="GetCommentText-<?php echo $i;?>" />
<input type="hidden" id="GetPostID-<?php echo $i;?>" value="<?php echo $i;?>">
<button type="button" id="SelectPostComment-<?php echo $i;?>" >Submit</button>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
and js part:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('[id^="SelectPostComment-"]').click(function(){ // changed here
var $td = $(this).parent(); // changed here
var CommentText = $td.find('[id^="GetCommentText-"]:first').val(); // changed here
var PostID = $td.find('[id^="GetPostID-"]:first').val(); // changed here
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: CommentText, PostID: PostID},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>
Or You could use more efficient way (no need to make garbages in DOM Tree):
<?php
for ($i=0;$i<=10;$i++) {
?>
<div data-postId="<?php echo $i; ?>">
<input type="text" name="commentText" value="" />
<button type="button" class="submit-comment">Submit</button>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
and js part:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.submit-comment').click(function(){
var $parent = $(this).parent();
var postId = $parent.data('postId');
var commentText = $parent.find('input[name="commentText"]:first').val();
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: commentText, PostID: postId},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>
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
});
});
I have list with several inputs
<input type="hidden" id="elevens_id_ea" value="<?php echo $_GET['elev_id']; ?>" />
<input type="hidden" id="arskursen_ea" value="<?php echo $arskursen; ?>" />
<?php
if ($extraanpassning_hamta['atgard'] == true){
?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-red btn-sm" value="Ja">
<?php } else { ?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-green btn-sm" value="Nej">
<?php } ?>
The main problem is how to "catch" the value in the two latest inputs with:
id="knapp[<?php echo $amnets_id['amne_id']; ?>]"
If knapp[4] -> how do I get the 4?
The code above is a part of a button that changes value when the user presses it (without refreshing the page).
The JS
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var extraanpassningVal = $(this).attr("value");
var amne_id_ea = $(this).attr("id");
var elevens_id_ea = $("#elevens_id_ea").val(); //värdet av elev_id
var arskursen_ea = $("#arskursen_ea").val(); //värdet av elev_id
$.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
});
});
</script>
EDIT:
The main problem is how to get the key from a input with an id like knapp[4].
How do get the key within knapp[]?
Update (thanks to user:SpYk3HH)
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajax) this.ajax.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajax = $.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
})
});
</script>
I think I get it? You want the key when calling the button in JS? So like say: key = this.id.replace(/knapp|\[|\]/g, '')
Update, I didn't see the brackets before
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajx) this.ajx.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajx = $.ajax({/* options */});
})
Does that help?
FYI, $(this).attr("id") and this.id are the same thing
$('[name=test]').each(function(i) { $('#bob').text(this.id.replace(/knapp|\[|\]/g, '')) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="knapp4" name="test" value='my id is "knapp[4]"' />
<hr />
key: <span id="bob"></span>
Try this.
var amne_id_ea = "knapp[4]",
value = amne_id_ea.substring(amne_id_ea.lastIndexOf("[")+1,amne_id_ea.lastIndexOf("]"));
alert(value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Hope you are expecting this.
I need to perform another AJAX Form Post from within the first forms success function.
Example, this does 2 AJAX requests.
Search Movie => Pick Movie Wanted => View Specific Movie Details
I am able to load the results into a div <div id="results"></div> just fine but once I select a movie title it isnt performing another AJAX Request, the request goes to the main window.
Here is the initial search page that handles the results.
<script type="text/javascript">
$(document).ready(function(){
$("#searchtitle").submit(function() {
var id = $(this).children('input[name="thetitle"]').attr('value');
$.ajax({
type: "POST",
url: "s.php",
data: $('#searchtitle').serialize(),
cache: false,
success: function(data){
$('#status').html(data);
}
});
return false;
});
});
</script>
<form id="searchtitle">
<input type="text" name="thetitle" />
<input type="submit" name="submit" class="button expand postfix" value="Search" />
</form>
<div id="status"></div>
s.php which returns results within #results
<?php
if(empty($_POST['thetitle'])) {
?>
<div class="alert-box error">
<div class="alert-error"></div>
Error: Nothing Found
</div>
<?php
}
if(!empty($_POST['thetitle'])) {
$myid = strtoupper($_POST['thetitle']);
$searchReults = $tmdb_V3->searchMovie($myid,'en');
?>
<?php
foreach($searchReults['results'] as $result) {
?>
<form class="sform">
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
<h5><?php echo $result['title']; ?></h5>
<span class="mreleased">Year: <?php echo $result['year']; ?></span>
<input type="submit" class="button" value="Select">
</form>
<?php
}
}
?>
This is the code that will post the results from s.php
<script type="text/javascript">
$(".sform").submit(function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize();
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
}
</script>
I have tried putting this within s.php, within the bottom of the initial search page, in the head of the initial page and no luck, it submits fine just not the sx.php where it should.
In s.php the statement:
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
Should be:
<input type="hidden" name="mid" value="<?php echo $result['id']; ?>" /> //remove extra bracket
In your javascript code in s.php there are some typos:
data: $(this).closest("form").serialize(); // here should be comma not semicolon
After return false you should close the script properly } should be });.
And since you are trying to submit the dynamic content $(".sform").submit(function () will not work. You should use on for dynamic contents. So the correct script would be:
<script type="text/javascript">
$(document).on('submit', '.sform', function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize(),
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
});
</script>
I have checked and verified in my localhost (with a simple setup). It is making both ajax request. Hope this helps!
I’m using below a simple Jquery code to call a PHP page and get the button information back in a div:
<head>
<script>
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
myPHPfile.php
<?php
if( $_REQUEST["selectedButtonValue"] )
{
$buttonPHP = $_REQUEST['selectedButtonValue'];
echo "Value button is ". $buttonPHP;
}
?>
How can I get the PHP information inside JavaScript, as follows:
alert(<?php echo('buttonPHP'); ?>);
Note: The following code shows the alert box message, but I can’t use it since I need the $buttonPHP value:
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue}, function(data){ alert(data); });
I’ve tried $_SESSION in myPHPfile.php, and also all jQuery AJAX functions: load(), get(), post() and the ajax() method, none of them is giving the PHP value inside JavaScript.
I looked all over but I couldn’t find an answer.
You would be better with an $.ajax request. Don't echo the 'Value of button is' part, just echo the actual value. For example:
$.ajax({
url: "myPHPfile.php",
context: document.body
}).done(function(data) {
var buttonValue = data;
// Whatever you want to do with the data goes here.
});
See the jQuery docs http://api.jquery.com/jQuery.ajax/
Alternatively, if you are generating the page with PHP, just echo the PHP variable into the JavaScript
<script>
...
var buttonValue = "<?php echo $buttonPHP; ?>";
...
</script>
Encode it in JSON instead of trying to echo the data :
<?php
if( $_GET["selectedButtonValue"] )
{
$buttonPHP = $_GET['selectedButtonValue'];
header('Content-Type: application/json');
echo json_encode($buttonPHP);
}
?>
Then use jquery get json to grab the data
$.get('myPHPfile.php?selectedButtonValue='+buttonvalue, function(data){
console.log(data);
});
Try:
alert('<?php echo $buttonPHP; ?>');
As a temporary solution, you could quickly merge both into a dirty code like this:
index.php:
<?php
$buttonPHP = "10"; //Set up your default button variable
if( $_REQUEST["selectedButtonValue"] == 10 )
{
echo "Selected button value: 10"; //You can also print $_REQUEST["selectedButtonValue"] here directly, but what's the point if you can select it from DOM through jQuery?
exit;
} else if ($_REQUEST["selectedButtonValue"] == 20) {
echo "Selected button value: 20";
exit;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $buttonPHP ?>; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
index.php rendered in browser:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = 10; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
EDIT: Stored session
<?php
session_start();
if (isset($_REQUEST['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = $_REQUEST['selectedButtonValue'];
echo $_REQUEST['selectedButtonValue'];
exit;
} else if (!isset($_SESSION['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = 10;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?>;
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv"><?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?></div>
</body>
</html>
Also make sure you filter the $_REQUEST variable, because as of now, it will print anything. See http://en.wikipedia.org/wiki/Cross-site_scripting for details.
I have the following code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript">
</script>
<script type="text/javascript">
function displayTweet(){
var i = 0;
var limit = $("#twitter-results > div").size();
var myInterval = window.setInterval(function () {
var element = $("#twitter-results div:last-child");
$("#twitter-results").prepend(element);
element.fadeIn("slow");
i++;
if(i==limit){
window.setTimeout(function () {
clearInterval(myInterval);
});
}
},2000);
}
$("form#twittersearch").submit(function() {
twitterq = $('#twitterq').attr('value');
$.ajax({
type: "POST",
url: "search.php",
cache: false,
data: "twitterq="+ twitterq,
success: function(html){
$("#twitter-results").html(html);
displayTweet();
}
});
return false;
});
});
</script>
</head>
<div class="twitter_container">
<form id="twittersearch" method="post" action="">
<input name="twitterq" type="text" id="twitterq" />
<button type="submit">Search</button>
</form>
<div id="twitter-results"></div>
</div>
</html>
/***************THIS IS search.php***************************/
<?php
include('twitterapi.php');
if($_POST['twitterq']){
$twitter_query = $_POST['twitterq'];
$search = new TwitterSearch($twitter_query);
$results = $search->results();
foreach($results as $result){
echo '<div class="twitter_status">';
echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
$text_n = toLink($result->text);
echo $text_n;
echo '<div class="twitter_small">';
echo '<strong>From:</strong> <a href="http://www.twitter.com/'.$result->from_user.'">'.$result->from_user.'</a&glt;: ';
echo '<strong>at:</strong> '.$result->created_at;
echo '</div>';
echo '</div>';
}
}
?>
Why is it that when I do a var_dump($_POST['twitterq']) it is always NULL?
UPDATE:
firebug gave me this, not sure how to fix it though:
That is because you are not providing the data properly. It should be:
data: ({twitterq: twitterq}),
You are sending data in the form of JSON. You are not using URL parameters , so there is no need of '='. if you have more than one parameters, you will simply separate them with commas.