I made a form using radio button (for poll).
And I use $.ajax to submit the form.
but when I use $("#polling").serialize() for the data, there is nothing sent/requested...
Are there any problem with the radio button?
$(function(){ $("input[name=vote]").click(function(){
var id_polling = $("input[name=id_polling]");
$("div[class=poll-content]").text("Loading");
$.ajax({
type: "POST",
url: BASE_URL + "/processes/polling.php",
data: $("#polling").serialize(),
success: function(msg){
document.getElementById("poll-content").innerHTML = msg;
}
});
});
and this is the HTML code :
<div class="poll-content" id="poll-content">
<form action="#" id="polling">
<?php
$poll = Polling::_find_by_id($id);
$view = "<h4 class=\"polling\">" . $poll->nama . "</h4>";
$options = explode(",", $poll->opsi);
foreach ($options as $i => $option) {
$view .= "<input type=\"radio\" class=\"option\" name=\"option\" value=\"" . $option . "\" />";
$view .= $option;
$view .= "<br />";
}
$view .= "<input type=\"hidden\" name=\"id_polling\" value=\"" . $poll->id_polling . "\">";
echo $view;
?>
<input type="button" name="vote" value="Vote" />
</form>
</div>
At first look it appears you are missing a closing });
$(function() {
$("input[name=vote]").click(function() {
var id_polling = $("input[name=id_polling]");
$("div[class=poll-content]").text("Loading");
$.ajax({
type: "POST",
url: "/echo/html/",
data: $("#polling").serialize(),
success: function(msg) {
document.getElementById("poll-content").innerHTML = msg;
}
});
});
}); //<-Missing this to close out dom ready
Edit, after looking at your markup, doing $("div[class=poll-content]").text("Loading"); will destroy the form so your call to $("#polling").serialize() will fail.
Try to capture the form before you call .text()
$(function() {
$("input[name=vote]").click(function() {
var id_polling = $("input[name=id_polling]");
var formData = $("#polling").serialize();
$("div[class=poll-content]").text("Loading");
$.ajax({
type: "POST",
url: "/echo/html/",
data: formData,
success: function(msg) {
document.getElementById("poll-content").innerHTML = msg;
}
});
});
});
Example on jsfiddle
Side note, you can use the class selector instead of the attribute selector $("div.poll-content").text("Loading");
Related
I new in term of using jQuery.
I practice using native php ajax, but for this time I need to learn jQuery for the current technology and demand.
I sent "types" value method POST to other page (ajaxInfo.php) when the tag change.
After the select tag change, it should show the result at <div id="showList"> that come from database (MySQL). But nothing happen.
Below are the source code.
Body
<select id="form-types" class="col-xs-10 col-sm-5" name="types">
<option value="">PLEASE CHOSE</option>
<option value="STATE">STATE</option>
<option value="FACULTY">FACULTY</option>
<option value="PROGRAME">PROGRAME</option>
</select>
<div id="showList"></div>
jQuery AJAX
<script type = "text/javascript" >
$(document).ready(function () {
$("select#form-types").change(function () {
var types = $("select#form-types").val();
if (types != null) {
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function (response) {
$("#showList").html(response);
}
}
});
});
});
</script>
Post Page (ajaxInfo.php)
<?php
if (isset($_POST["types"]) === TRUE){
$types = $_POST["types"];
}
else{
$types = null;
}
include '../dbco.php';
$query = $dbc -> query ("SELECT child FROM infobase WHERE parent='$types'");
if ($query -> num_rows > 0){
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc()){
echo "$count" . $result['child'] . "<br />";
count++;
}
}else{
echo "NO " . $types . " REGISTERED";
}
?>
Thank You.
You are using id (form-types) for your select input field. but your are tying to targeting another id (form-jenis).
use same named id for select input field and in your jquery selector.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(e){
e.preventDefault();
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'show.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
You have a missing bracket
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
}); // add this
</script>
I found out that my ajax jQuery function do not have close pair, so i decide to add it and it work.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}); // Add This
}
});
});
</script>
After the code running good, i also found out the error at ajaxInfo.php, the count inside the loop missing $ symbol
if ($query -> num_rows > 0)
{
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc())
{
echo "$count" . $result['child'] . "<br />";
$count++; //HERE
}
}
Thanks for the people that help.
here i have written the code for a functionality using jquery-ajax in CODEIGNITER where i need to pass the value of the drop down to the database using 'ajax post method' execute a query and get and display the results/data in the same view page using onChange, but the problem is onChange no change is visible.
Please help me out on this.
view.php
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" name="ProductCategoryID" id="item_code" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="'.$row->ItemCode.'">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group" id="description">
</div>
<script src="<?php echo base_url("assets/js/jquery-1.10.2.js"); ?>" type="text/javascript"></script>
<script type="text/javascript">
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#item_code').append('<textarea value="' + id + '">' + name + '</textarea>');
}
});
$('#item_code').trigger('chosen:updated');
});
</script>
Controller.php
<?php
class Ajax extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('Gst_model');
$this->load->model('User_model');
$this->load->model('Report_model');
$this->load->helper('url');
}
function get_description()
{
$id = $this->input->post('id');
echo(json_encode($this->Report_model->get_description($id)));
}
}
Model.php
function get_description($item_code)
{
$result = $this->db->where('ItemCode', $item_code)->get('gst_itemmaster')->result();
$id = array('0');
$name = array('0');
for ($i=0; $i<count($result); $i++)
{
array_push($id, $result[$i]->ItemDescription);
array_push($name, $result[$i]->ItemDescription);
}
return array_combine($id, $name);
}
Your problem is that updating chosen-select dropdowns is a bit tricky. After you've updated your option list you have to call something like $('.my_select_box').trigger('chosen:updated'); Take a look at the chosen-select docs here.
Just put this after your ajax call at the end of your change() function:
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#state').append('<textarea value="' + id + '">' + name + '</option>');
}
});
$('#item_code').trigger('chosen:updated');
});
I am looping through data form a database to a form that makes a Ajax request to add an item to a shopping basket/cart. Everything works fine except that only the first item in the array is added? I have tried using classes as apposed to id's(unique
echo "<div class='col-100 border-temp bg-orange'>";
echo "<div class='col-50 border-temp'>";
foreach ($result as $key => $result) {
$m = $result["model_no"];
$q = $result["qty_available"];
echo "<form method='post' action='/stock-clearance' class='stock_clearance bg-blue'>";
echo "<label for='model_no'><h2>Model No</h2></label>";
echo "<input id='model_no' name='model' type='text' placeholder='Paste model no... ' value='$m' />";
echo "<span id='model_error'></span>";
echo "<label for='quantity'>Quantity</label><br />";
echo "<input id='quantity' name='quantity' value='1' type='number' min='1' max='$q'>";
echo " <span id='quantity_error'></span>";
//echo "<input id='sc_add_to_cart' name='' value='$key' type='button'>";
echo "<input id='sc_add_to_cart' name='sc_add_to_cart' value='Add to Basket' type='submit'>";
echo "</form>";
} // End foreach loop
echo "</div>";
)
My JS code is as follows:
$('#sc_add_to_cart').on('click', function(e) {
e.preventDefault();
var form = $('.stock_clearance');
hideStockClearanceMessages(form);
var request = $.ajax({
beforeSend: function() { form.css({ opacity: 0.4 }); },
url: 'ajax.php',
cache: 'false',
data: {
action: "sc-add-to-cart",
model: $('input[name="model"]').val(),
quantity: $('input[name="quantity"]').val()
}
});
enter image description here
You can not have the same one ID for a different inputs. ID must be UNIQUE. Instead of ID use CLASS attribute
1- Sometimes because of caching problem it will not work so you have to add seed to your call.
seedrandom()
function seed() {
return Math.floor((Math.random() * 10000) + 1);
}
$('#sc_add_to_cart').on('click', function(e) {
e.preventDefault();
var form = $('.stock_clearance');
hideStockClearanceMessages(form);
var request = $.ajax({
beforeSend: function() { form.css({ opacity: 0.4 }); },
url: 'ajax.php?sid=' + seed(),
cache: 'false',
data: {
action: "sc-add-to-cart",
model: $('input[name="model"]').val(),
quantity: $('input[name="quantity"]').val()
}
});
Please use IDs only for one element. They must be unique. You can use CLASS instead.
Using ajax, I'm trying to display what is being selected on a div, and it's working, but everything after the div gets replaced by the div's output. I don't know why it's happening or how to fix it. If you know, please let me know.
test1.php
<?php
include('ajax.php');
echo "<select name = 'select' onchange = 'ajax(\"test2.php\",\"select\",\"select\",\"output\")'>";
echo "<option value = '1'> one </option>";
echo "<option value = '2'> two </option>";
echo "<option value = '3'> three </option>";
echo "</select>";
echo "<div id = 'output'>";
echo "text";
?>
test2.php
<?php
$select = $_POST['select'];
echo $select;
?>
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
I testing your code in my pc and it worked. But after change this echo "<div id = 'output'>"; into this echo "<div id = 'output'></div>";, the output only show inside div block and everything after the div gets not replaced.
If you want something similar to onload, just use trigger function to trigger the onchange event after page load like so :
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
$(function(){
$('select[name="select"]').trigger('change');
});
You are missing the closing div tag.
I have a question I can't figure out.
<?php
$killtheboy = 0;
if($killtheboy == 1){
echo "<input type=\"text\" name=\"dwanummer\" id=\"dwanummer\">";
}else{
echo "<div id=\"dropdowndwa\">
<select name=\"dwanummer\" id=\"dwanummer\" class=\"dwanummer\">
<option selected=\"selected\">Kies uit lijst</option>";
include("config/instellingen.php");
$query = "SELECT DISTINCT `Klantvraag`,`Wensweek` FROM `DWA` WHERE `Status DWA` = 'DBAA' OR `Status DWA` = 'DBAP' OR `Status DWA` = 'DIUI' ORDER BY wensweek - '$wensweekber' ASC";
if ($result = mysqli_query($connect, $query)) {
while ($get = mysqli_fetch_assoc($result)) {
$week = date('W', strtotime("this week"));
$jaar = date('Y', strtotime("this week"));
$wens = ''. $jaar . ''. $week. '';
$wensweek = $get['Wensweek'];
$wensweekber = $wensweek - $wens;
echo '<div class="selectBlock"><option value="' . $get['Klantvraag'] . '" name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option></div>';
}
}
echo "</select></div><br />";
}
?>
The above code (PHP) fetches a list of numbers on pageload and I have to select one in order to fetch that information through JS.
<script type="text/javascript">
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax
({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
}
});
});
});
</script>
Basically I have a search system and u can find all 'cases' there and if you see one you want then you click it it goes to the above page with code and it auto selects that ID instead of still having to select it. (like additem.php?id=125533 or something)
Can someone please explain me how I can solve this.
Can you try this, You need to use selected attribute in select element
$Selected ='';
if(isset($_GET['id']) && ($get['Klantvraag'] == $_GET['id'])){
$Selected =" selected='selected' ";
}
echo '<option value="' . $get['Klantvraag'] . '" '.$Selected.' name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option>';
Javascript:
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
Populate();
});
Populate();
});
function Populate(){
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
removeAllNameSelectBoxes();
var selected = $("#dropdowndwa option:selected").map(function (i, el) {
return el.value;
}).get();
getNamesFromSelectIds(selected);
}
});
}