Ok here is a strange little problem:
Here is a test page, which user clicks to open:
When user clicks view results I have 3 selectboxes inside the modal box.
box1 => populates =>Box 2 => populates Box 3
My problem
When user clicks submit, instead of results being displayed from the query based on selectbox selections, the test page opens again inside the modalbox... as you can see in below image
On submit
Any idea why when form is submitted current page opens inside modalbox?
Submit Form
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) { $('#resultForm').append(data); }
});
}
});
</script>
Populate Textboxes
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
<label>Sport :</label>
<form method="post" id="resultForm" name="resultForm" action="result.php">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
<?php
Display result
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $sport=$_POST['sport'];
echo $tour=$_POST['tournament'];
echo $round=$_POST['round'];
$sql="Select * FROM Multiple_Picks WHERE tournament ='$tour' AND round='$round' GROUP BY member_nr";
$result = mysql_query($sql);
?>
<?php
while($row=mysql_fetch_array($result)){
$memNr = $row['member_nr'];
$pick = $row['pick'];
$score = $row['score'];
?>
echo $memNr;
echo $pick;
echo $score;
}
}
?>
It would appear that:
success: function(data) { $('#resultForm').append(data); } you are telling it to put the ajax response in the resultForm, which appears to be inside your modal. Is that not what is happening. Hard to tell from your question and code what SHOULD be happening vs what IS happening now.
Related
I am submitting form using ajax in the while loop but because of loop the same form id is using many times , so as a result the form is submitting only once . I think i have to make unique id every time in the loop for the form but don't know how.
Here is my code so far,
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while($row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC)){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?>
<form id="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php } ?>
<script src="jQuery v2.1.1"></script>
<script>
$("#subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
submit_subcmt.php
<?php
$comtr_id =$_POST['comtr_id'];
$comment_id =$_POST['comment_id'];
echo $comtr_id;
echo $comment_id;
?>
Try this.
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while($row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC)){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?>
<form class="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php } ?>
<script src="jQuery v2.1.1"></script>
<script>
$(".subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
To illustrate the comment I made above you could try something similar to this perhaps.
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while( $row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC) ){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?> <!-- use a class attribute here -->
<form class="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php
}//end loop
?>
<script src="jQuery v2.1.1"></script>
<script>
/* and assign event handlers to form objects with this class as per above */
$("form.subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
I got two pages:
Page 1:
<input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/>
<input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/>
<script>
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$('#mR-RateableFramePicture').dblclick(function () {
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: {"rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function() {
}
});
});
</script>
Page 2:
<?php
session_start();
$userID = $_SESSION["ID"];
$ratedUserID = $_POST['rateableUserID'];
$ratedPictureID = $_POST['rateablePictureID'];
include '../../scriptMysqli.php';
$sql = $conn->query("UPDATE styles SET savedByUser = '$userID' WHERE userID = '$ratedUserID' AND pictureID = '$ratedPictureID'");
?>
<script>alert("success");</script>
But the $sql variable never gets executed and the part with the alert is not being shown on the original page (page 1) eiher :/
What am I doing wrong here?
From the comments the changed code:
<input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/>
<input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/>
<script>
$('#mR-RateableFramePicture').dblclick(function () {
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: {"rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function(scriptCode) { $('body').append(scriptCode); }
});
});
</script>
The important line is the success handler. It takes the response from your ajax call (echoed by your php script) and add it to the DOM, so it will executed in case of javascript code.
I have created dynamically multiple select list. On click of channel name it should get its type. The problem is once click on select list its repetitively calls java script function causing ajax to load multiple times.
HTML CODE:
<td>
<SELECT name="channel_name[]" onclick ="get_type(this)"; required class='channelname'>
<option value="">Select...</option>
<?php foreach($channel_list as $row) {
$channelid = $row['channelid'];
$channelname = $row['channelname'];
if($U_channelid==$channelid)
{
$s = "selected = selected";
}
else
{
$s = "";
}
echo "<option value='$channelid' $s>".$channelname."</option>";
?>
<!-- <OPTION value='<?php echo $channelid ?>' $s ><?php echo $channelname?></OPTION> -->
<?php } ?>
</SELECT>
</td>
Javascipt code:
function get_type()
{
$(".channelname").live("change", function() {
var channel_id = $(this).find("option:selected").attr("value");
var _this = $(this); //Save current object
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});
}
remove onclick ="get_type(this)" from select tag // because you already using $(".channelname").live("change", function() { in javascript
put this
<SELECT name="channel_name[]" required class='channelname'>
and javascript
$(".channelname").change(function() {
var channel_id = $('.channelname').find("option:selected").attr("value");
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});
I want to make step input with select option, in this case, i make 3 step, when select first option then will show next option 2, then option 3. i am using ajax and i set $config['csrf_protection'] = TRUE; in Codeigniter config file. In first select option (#kategori) is work and show next value in second select option, but in step 3 select option (#sub1 or secon function of javascript) n't work. thank before.
This is my view:
<?php echo form_open_multipart('',array('class'=>'form-horizontal'));?>
<?php echo form_label('Kategori','id_kategori',array('class'=>'col-sm-2 control-label'));?>
<select id="kategori" name="id_kategori">
<option value=""></option>
<?php
foreach($kategori as $kategori_umum)
{
echo '<option value='.$kategori_umum->id.'>'.$kategori_umum->nama_kategori.'</option>';
}
?>
</select>
<select id="sub1" name="id_kategori_sub1"> //step 2
<option value=""></option>
</select>
<select id="sub2" name="id_kategori_sub2"> //step 3
<option value=""></option>
</select>
Ajax :
<script type="text/javascript">
$('#kategori').change(function(){
var kategori_id = $('#kategori').val();
//alert(state_id);
if (kategori_id != ""){
var post_url = "<?php echo base_url();?>masuk/produk/get_sub1";
$.ajax({
type: "POST",
url: post_url,
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>','kategori_id':kategori_id},
dataType: 'json',
success: function(kategori_sub1, dataType) //calling the response json array 'kategori_sub1'
{
$('#sub1').empty();
$('#sub1').show();
$.each(kategori_sub1,function(id,sub1)
{
var opt = $('<option />'); // creating a new select option for each group
opt.val(id);
opt.text(sub1);
$('#sub1').append(opt);
$('#sub2').hide();
});
},
error:function(xhr)
{
alert("Terjadi Kesalahan");
}
}); //end AJAX
} else {
$('#sub1').empty();
$('#sub2').empty();
}});
$('#sub1').mouseout(function(){
var sub1_id = $('#sub1').val();
if (sub1_id != ""){
var post_url = "<?php echo base_url();?>masuk/produk/get_sub2";
$.ajax({
type: "POST",
url: post_url,
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>','sub1_id':sub1_id},
dataType: 'json',
success: function(kategori_sub2, dataType)
{
$('#sub2').empty();
$('#sub2').show();
$.each(kategori_sub2,function(id,sub2)
{
var opt = $('<option />');
opt.val(id);
opt.text(sub2);
$('#sub2').append(opt);
});
},
error:function(xhr)
{
alert("Kesalahan");
}
}); //end AJAX
}});</script>
I suspect your problem is using wrong event mouseout.
You should be using change the same way the first one that works does.
Beyond that more information is needed about the actual requests by inspecting in browser dev tools
I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
And, another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
You can use ajax. See example below
$(function(){
$('#brand').on('change', function(){
var brand = $(this).val();
$.ajax({
type : 'post',
url : '<?php echo base_url();?>controller_name/function_name',
data : 'brand='+brand,
dataType : 'json',
success : function(msg){
// here you can populate data into category select option
var options;
for(var i = 0; i<msg.length; i++)
{
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options); // your html part for category should look like this <select id="category"></category>
}
});
});
});
php code in controller part(function name showCategory)
function showCategory(){
$brand = $this->input->post('brand');
$data['category'] = $this->your_model->your_function_to_select_data();
echo json_encode($data);
}
<?php
?>
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
<p>Category:</p>
<select name="category">
<!--Content will be popullated from ajax call-->
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"> </script>
<script type="text/javascript">
(function($){
$(function(){
$(document).on('change' , '[name=brand]', function(){
var brand_selected = $(this).val();
$.ajax({
url: '[your url to fetch category based on categoryid]' ,
dataType:"json",
data: {brand : brand_selected},
success: function(r){
/**
* your response should be in json format
* for easy work
{catd_id: catname, cat_id :catname}
*/
var html = '';
if(r && r.length){
$.each(r, function(i, j){
html +='<option value="'+i+'">'+j+'</option>';
})
}
/**
* finaly populat ethe category data
*/
$('[name="category"]').html(html);
}
})
})
})
})(jQuery)
</script>
Change the portion as per yours...
Use this approach to detect changing value of select tag.
$( "#brand" ).change(function() {
var myOption = $(this).val();
// use ajax to get data for 'category' select by using "myOption"
});
then when you get ajax response add new select tag with
for (var i = 0 ; i < response.length; i++)
{
$('#category').append('<option>'+response[i]+'</option>')
}
I still don't get the required answer. Below is my view.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
My Controller:
function showCategory() {
if($this->session->userdata('success')) {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
$this->load->helper('url');
}
}
My category table contains: category_id, category_name, brand_id.