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);
}
});
}
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.
Please help, I am trying to get the value of input field after ajax success, I don't know why is it always undefined?
ajax.js
$(document).on('click','.modify',function(){
var modId = $(this).attr('id');
var event_id = $(this).attr('class').split(' ')[1];
$.ajax({
cache: false,
url: '../ajax/paraphernalia/ajax_get_edit.php',
type: 'post',
data: { modId: modId, event_id: event_id},
success:function(data){
var mod_name = $(data).find('input#hidden_headerName').val();
alert(mod_name);
$('#display_modal_edit').html(data);
$('#judge_name_header').html(mod_name);
}
});
});
ajax_get_edit.php
session_start();
require ("../../global.php");
if (isset($_POST['modId']) && isset($_POST['event_id'])) {
$modId = $_POST['modId'];
$event_id = $_POST['event_id'];
$output = '';
$sql = mysql_query("SELECT * FROM tbl_judges WHERE judge_id = ".$modId." AND event_id = ".$event_id."");
$soc_sql = mysql_fetch_assoc($sql);
$output .= '<input type="text" value="GetThisvalue" id="hidden_headerName">';
$output .= '.....';//bunch of codes here
$output .= '</div>';
echo $output;
}
You can Return a JSON from PHP and Create the Divs you need/dont Need on the Client, further its also simpler if you just Need some values
I am loading a list of customers and I want to load a second dropdown for locations based on which customer gets selected. For some reason my code isn't working. Here's my code:
<span style="display:inline-block;">
<select name="sCustomer" id="sCustomer" onChange="findLocations(this.value)">
<option value="0">- Select Customer -</option>
</select>
</span>
<span style="display:inline-block;">
<select id="sLocation" name="sLocation">
<option value="0">- Select Location -</option>
</select>
</span>
<script type="text/javascript">
function findLocations(custID) {
$('#sLocation').empty();
$('#sLocation').append("<option value='0'>- Select Location -</option>");
$.ajax({
type:"POST",
url:"getLocations.php",
contentType:"application/json; charset=utf-8",
data: { custID : custID },
dataType:"json",
success: function(data){
$.each(data,function(i, item){
$('#iTest').val("bobby");
$('#sLocation').empty();
$('#sLocation').append("<option value='0'>- Select Location -</option>");
$('#sLocation').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
});
},
complete: function(){
}
});
}
</script>
and the page it calls has this code
<?php
include_once(INCLUDE_DIR.'class.error.php');
include_once(INCLUDE_DIR.'class.role.php');
include_once(INCLUDE_DIR.'class.passwd.php');
include_once(INCLUDE_DIR.'class.user.php');
include_once(INCLUDE_DIR.'class.auth.php');
include_once(INCLUDE_DIR.'class.location.php');
function getLocations() {
$custID = 0;
if (isset($_POST['custID'])) {
$custID = $_POST['custID'];
}
$sql = 'SELECT l.location_id, l.site_name FROM ' . CUST_LOCATION_TABLE
. ' AS l JOIN ' . CUST_TABLE . ' AS c ON c.cust_id=l.cust_id'
. ' WHERE c.cust_id='.$custID;
$locations = array();
if (($res=db_query($sql)) && db_num_rows($res)) {
while(list($id,$name)=db_fetch_row($res)) {
$columns = array (
'locID' => $id,
'locName' => $name,
);
$locations[] = $columns;
}
}
return $locations;
}
?>
Why isn't this working and is there anyway to test what part is breaking? I can't echo out anything because the page doesn't postback (since it's ajax) and I can't do javascript alert in the ajax function. Bear in mind I didn't add the code that was filling the customer dropdown because I know it's working right, populating everything and giving me the correct values.
Okay I found this which at least helps me start debugging. It's failing but I found this
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
Replace your code in php file with this one
if (($res=db_query($sql)) && db_num_rows($res)) {
$str = "";
$str .= "<option value='0'>Select Location</option>";
while(list($id,$name)=db_fetch_row($res)) {
$str .= "<option value=".$id.">".$name."</option>";
}
}
echo $str;
Now Modify your javascript function
function findLocations(custID) {
$('#sLocation').empty();
$.ajax({
type:"POST",
url:"getLocations.php",
contentType:"application/json; charset=utf-8",
data: { custID : custID },
dataType:"json",
success: function(data){
document.getElementById("sLocation").innerHTML = data;
},
complete: function(){
}
});
}
replace
data: { custID : custID },
with
data: { 'custID' : custID },
in javascript
function findLocations(custID) {
$('#sLocation').empty();
$.ajax({
type:"POST",
url:"getLocations.php",
contentType:"application/json; charset=utf-8",
data: { custID : custID },
dataType:"json",
success: function(data){
document.getElementById("sLocation").innerHTML = "<option value='0'>- Select Locationss -</option>"; // + data;
},
complete: function(){
}
});
}
and the php page is
<?php
include_once(INCLUDE_DIR.'class.error.php');
include_once(INCLUDE_DIR.'class.role.php');
include_once(INCLUDE_DIR.'class.passwd.php');
include_once(INCLUDE_DIR.'class.user.php');
include_once(INCLUDE_DIR.'class.auth.php');
include_once(INCLUDE_DIR.'class.location.php');
$custID = 0;
if (isset($_POST['custID'])) {
$custID = $_POST['custID'];
}
$sql = 'SELECT l.location_id, l.site_name FROM ' . CUST_LOCATION_TABLE
. ' AS l JOIN ' . CUST_TABLE . ' AS c ON c.cust_id=l.cust_id'
. ' WHERE c.cust_id='.$custID;
$locations = array();
if (($res=db_query($sql)) && db_num_rows($res)) {
$str = "";
$str .= "<option value='0'>Select Location</option>";
while(list($id,$name)=db_fetch_row($res)) {
$str .= "<option value=".$id.">".$name."</option>";
}
}
echo $str;
?>
i got a problem when i try to use ajax in a php file, which calls to another php file.
Here is the code of the php file:
<script>
function obtenerProductos(cat) {
parametros = {"idCat": cat};
$.ajax({
data: parametros,
url: '/bin/getProductos.php',
type: 'post',
beforeSend: function() {
$(".prods > form").html("Procesando, espere por favor...");
},
success: function(respuesta) {
$(".prods > form").html(respuesta);
}
});
}
function obtenerProducto(prod) {
parametros2 = {"idProd": prod};
$.ajax({
data: parametros2,
url: '/bin/getProducto.php',
type: 'post',
beforeSend: function() {
lista = $(".cPreview").html() + "<br/> AƱadiendo...";
$(".cPreview").html(lista);
},
success: function(respuesta) {
lista = $(".cPreview").html()+ respuesta.nombre + "\t" + respuesta.precio + "<br/>" ;
$(".cPreview").html(lista);
precio = parseFloat($(".precioT").html()) + respuesta.precio;
$(".precioT").html(precio);
}
});
}
</script>
In the first function of this script i call to the first PHP (getProductos.php) to get all the products of a category and receive a html which print in a form.
The second function calls to another php (getProducto.php) to get all the information of the selected product and print it in another div.
Here you have the PHP files named.
getProductos.php (This works)
<?php
include '../funciones.php';
$recibido = $_POST['idCat'];
echo obtenerProductosCategorias($recibido);
?>
getProducto.php (Dont Works)
<?php
include '../funciones.php';
$recibido = $_POST['idProd'];
echo obtenerProductos($recibido);
?>
And the 2 functions of this code:
function obtenerProductosCategorias($idCat) {
conectDB();
$string = "";
$sql = 'select * from Productos where id_categoria="' . $idCat . '";';
$resultado = mysql_query($sql);
while ($row = mysql_fetch_array($resultado)) {
$string = $string . "<input type='button' onclick='obtenerProducto(" . $row["id_producto"] . ");return false;' value='" . $row['nombre_producto'] . "' />";
}
return $string;
closeDB();
}
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}
I have alerts inside the PHP to check that everything is going fine but the second function doesnt enter in his PHP and it returns undefined undefined without show any alert of the PHP thats why i think that the second function have some problems to reach his PHP but the URL is correct and the file is located in the right place.
Thanks for reading and sorry for my English.
Try defining $resultado as an array prior to assigning anything too it. Not sure but in some configurations this does break PHP.
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
$resultado = array();
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}
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");