I have select html tag, which value get from database, and the data will return to query and return an value to another dropbox.
My tag HTML like this:
And i want to give the value of data which is selected to another dropdown here:
And my javascript like this:
And the url direct to here:
And the model like this :
How i can change value to id sektor 20, when i have selecting a dropdown from sektor10?, and how to return value from controller and change value of sektor20?
A working sample what I have done for selecting from dropdown and display values as per the selected value.
In your controller-
function functionname($id){
$details = $this->your_model->get_details($id);
echo json_encode($details);
exit;
}
In Model-
function get_details($id){
$this->db->select('*');
$this->db->from('packages');
$this->db->where('package_id',$id);
$query = $this->db->get()->result();
return $query;
}
Javascript-
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#sector10").change(function() {
var selectedMark = $("#sector10").val();
if (selectedMark != "") {
jQuery.ajax({
type: 'POST',
dataType: "json",
async:false,
url: "<?php echo base_url() . 'loyalty/functionname/'; ?>" + selectedMark,
success: function(data)
{
$("#cards").html("");
$("#cards").append("<option value=''>Select a Card</option>");
var index=1;
$.each(data, function() {
$("#cards").append("<option value='" + this.card_id + "'>" + this.card_name + "</option>");
$("div#cards_chosen div.chosen-drop ul.chosen-results").append("<li class='active-result' data-option-array-index='"+index+"' >" + this.card_name + "</li>");
index++;
});
}
});
}
});
});
</script>
Related
I am appending items (articles) to a content with some originally existing articles, each article has a button for its deleting, editing, opening. I use jquery & ajax.
I want these appended articles' buttons to be able to pass each of their values to jquery click function, as well as produce all the logic there (same way as original articles' buttons do).
Is it possible to do something that way?
<!DOCTYPE html>
<html>
<head>
<title>Infinite Software Blog</title>
<meta name="viewport" content="width=device-width, scale=1.0">
<script type="text/javascript" src="/blog/jquery/jquery-3.2.0.min.js"></script>
<script>
$(document).ready(function () {
$('.del_btn').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = '/blog/helpers/delete_post.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function () {
alert("Post was successfully deleted");
});
});
$('.edit_btn').click(function () {
var clickBtnValue = $(this).val();
console.log(clickBtnValue);
var ajaxurl = '/blog/edit_post.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function () {
window.location.assign("/blog/helpers/updatePost.php");
});
});
$('.post_content_btn').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = '/blog/view/post.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function () {
window.location.assign("/blog/post.php");
});
});
$('.more_posts_btn').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = '/blog/helpers/show_more_posts.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (output) {
$(".content").append(output);
});
});
});
</script>
<link rel="stylesheet" href="/blog/styles/style.css" type="text/css"/>
</head>
show_more_post.php
<?php
if (isset($_POST['action'])) {
include($_SERVER['DOCUMENT_ROOT'] . "/blog/model/classes.php");
$post = new posts();
$postsToDisplay = $post->getPostsQty($_POST['action']);
$newRecordsIndex = $_POST['action'];
for ($i = 1; $i <= $postsToDisplay; $i++) {
$record = $post->getPost($newRecordsIndex);
$newRecordsIndex++;
$elementToAdd = '<article class="topContent"><header><h2><a href="#" title="' . $record[1] . '">' .
$record[1] . '</a></h2></header><footer><p class="post-author">Author: ' . $record[2] . '</p>' .
'</footer><content>' . $record[6] . '</content><footer><p class="post-date">Publish date: ' .
$record[3] . '</p>' . '<p class="post-time">Publish time: ' . $record[4] . '</p><form><button type="submit"
title="Delete post"' . ' value="' . $record[0] . '" class="del_btn">Delete post</button><button type="submit"
title="Edit post"' . ' value="' . $record[0] . '" class="edit_btn">Edit post</button><button type="submit"
title="Open post in a new tab" value="' . $record[0] . '" class="post_content_btn">Open Post</button>
</form></footer></article>';
echo($elementToAdd);
}
}
I will suggest you to go in a simple way, You can use live table update strategy where you can simply update the data directly from the UI and delete or add as well. Find the below code
$(document).ready(function(){
function load(){
$.ajax({
url:'db.php',
method: 'POST',
success:function(data){
$("#load").html(data);
}
});
};
load();
$(document).on('click', '.bton', function(){
var name= $(this).data("id");
if(confirm("Do you want to delete this row"))
{
$.ajax({
url: 'delete.php',
method: 'POST',
data:{id:name},
success: function(data){
alert(data);
load();
}
});
}
});
$(document).on('click','#add', function(){
var addName= $("#name").text();
var addComp= $("#company").text();
$.ajax({
url:'insert.php',
method:'POST',
data: {name:addName, company:addComp},
success:function(data){
alert(data);
load();
}
});
});
$(document).on('blur','.type', function(){
var editID=$(this).data('id1');
var editName= $(this).text();
alert(editName);
})
});
for reference click here, download file and use to understand better.
Use $(document).on('<event>', '<selector>', function() {}); to make available events on dom elements, that creates after script init.
I have this html:
<select id="test"></select>
And This ajax code:
<script>
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
//url: localhost/web/index.php?name='whatever'
var value = get('name');
$(document).ready(function(){
$('select').select2();
$.ajax({
type: "POST",
url: 'getValues.php',
data: {'test': $("#test").val(),'isAjax':true},
dataType:'json',
success: function(data) {
var select = $("#test"), options = '';
select.empty();
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";
}
select.append(options);
}
});
});
</script>
I need to set the value of select as taken from the url,which is (var value).
The value is working fine,as I tested it in alert.
Any help is appreciated
1) You can use .val() after appending options:
select.append(options);
select.val(value);
2)
or add attribute selected to option having same value while building the options html string.
options += "<option value='"+data[i].id+"' "+(data[i].id == value ? "selected" : "") +">"+ data[i].name +"</option>";
Chances are its the AJAX that is causing the issue. you need to trim() the response to remove a whitespace at the end of the returned data. Try the following :
success: function(data) {
var response = data.trim(), select = $("#test"), options = '';
select.empty();
for(var i=0;i<response.length; i++)
{
options += "<option value='"+response[i].id+"'>"+ response[i].name +"</option>";
}
select.append(options).val(value);
}
My problem is solved.
The problem was that the returned value has space,which is taken from url as +
So I replaced "+" by " "
Thanks all !
I have a search function that is suppose to search a name from the database, and then when the user clicks add, the item choosen has to appear below the search field, in short it has to be posted back so that the user can re-select his/her second option from the search element so that all the selected options can be saved in the database. The problem im facing is that after I click add im getting undefined value back instead of the one I choose and my response is a name instead of an Id number, here is my code and a picture below.
MODEL
public function getName($id)
{
$select = $this->select()
->where('service_provider_id LIKE "' . $id . '%"')
->order('service_provider_name');
return $this->fetchAll($select);
}
CONTROLLER
{
$id = $this->getRequest()->getParam('id');
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id);
$arr_rtn = array();
if (count($results) > 0){
foreach($results as $result)
{
$myarr = array( 'label' => $result->service_provider_name,
'value' => $result->service_provider_name,
'id' => $result->service_provider_id
);
array_push($arr_rtn, $myarr);
}
}
echo Zend_Json::encode($arr_rtn);
}
PHTML/AJAX
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
var row = '<tr><td>' + data["serviceprovider"] + '</td></tr>';
$('#t1').append(row);
//alert();
}
});
});
Thanks in advance
You can use data["value"] instead of data["serviceprovider"]:
var row = '<tr><td>' + data["value"] + '</td></tr>';
Since you've encoded the array which contains three keys: label, value and id. So there's no serviceprovider key at this moment for Zend to encode.
You are looking for a key that doesn't exist in the array you are returning try this
var row = '<tr><td>' + data['label'] + '</td></tr>';
Or this
var row = '<tr><td>' + data['value'] + '</td></tr>';
As those are the two keys you defined in your PHP page
Try
var row = '<tr><td>' + data[0].value + '</td></tr>';
Also try to put an alert() in the success function like,
alert(JSON.stringify(data));
and see what is included in it..
From what I see I think you are ruturning a multidimensional array from php so I would try something like this in javascript:
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
data.each(function(index, el){
var row = '<tr><td>' + el.label + '</td></tr>';
$('#t1').append(row);
//alert();
}
}
});
});
In your controller try:
$this->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
return $this->_helper->json(array('key1' => $val1, 'key2' => $val2, ...));
I am getting the results of a db query in php and return it thru ajax in a json array, but when I try to access the data it gives me data as 'undefined'
why is that happening?
Here is my php code:
<?php
$tipo_prod= $_POST['tipo_prod'];
$conn = oci_connect("admin", "admin", "localhost/XE");
$query = "SELECT COD_PRODUCTO, NOMBRE FROM PRODUCTO WHERE COD_TIPO_PROD=" . $tipo_prod;
$exec= oci_parse($conn, $query);
oci_execute($exec);
//Check connection!!!
$exec= oci_fetch_array($exec);
echo json_encode($exec);
?>
And my ajax code:
$.ajax({
url : "trae_producto.php",
type : "POST",
data: {"tipo_prod" : tipo_prod},
success : function(data){
data = JSON.stringify(data);
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}});
try doing::
$.ajax({
url : "trae_producto.php",
type : "POST",
data: {"tipo_prod" : tipo_prod},
dataType: "json",
success : function(data){
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}});
try adding Content-Type header in your PHP code, like:
header('Content-Type: application/json');
echo json_encode($exec);
Added:
do something like
while($data = oci_fetch_array($exec)) {
$out[] = $data;
}
echo json_encode($out);
$.ajax({
url : "trae_producto.php",
type : "POST",
dataType: "json",
data: {"tipo_prod" : tipo_prod},
success : function(data){
/* data = JSON.stringify(data); */
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}});
I don't know what's your real return from PHP script but if it assumed as correct, the AJAX seems have some flaws.
JSON.stringify will make your object to string type so the jQuery iterator won't work.
use "dataType" attribute to inform AJAX it will getting JSON object
You're trying to turn the result that it gives you into JSON. jQuery parses it already for you, just remove the line for JSON.stringify.
$.ajax({
url : "trae_producto.php",
type : "POST",
data: {"tipo_prod" : tipo_prod},
success : function(data){
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}
});
At first, debug through firebug whether you are getting a JSON object, as well as your server is sending data. Then, instead of data = JSON.stringify(data);, you can use data = JSON.parse(data);
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "XML/Website.xml",
dataType: "xml",
success: function (xml) {
var arr = new Array();
$(xml).find("board").each(function () {
var option = $(this).find('brand').text();
if ($.inArray(option, arr) > -1) {
// Do nothing
}
else {
$('#dropdown').append('<option>' + option + '</option>');
arr.push(option);
}
});
}
});
});
</script>
<form>
<select id="dropdown">
<option></option>
</select>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "XML/Website.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('board').each(function () {
var image = $(this).find('image').text();
var name = $(this).find('name').text();
var brand = $(this).find('size').text();
var brand = $(this).find('camber').text();
var price = $(this).find('price').text();
$('#table').append('<tr><td><img width="250px" src="' + image + '"/></td><td>' + name + '</td><td>' + brand + '</td><td>' + price + '</td></tr>');
});
}
});
});
</script>
<table id="table" border="1" cellspacing="5" cellpadding="20" class="center">
<tr><td></td><th>Name</th><th>Camber</th><th>Price</th><th>Size</th></tr>
</table>
</body>
</html>
My XML data is being displayed on the page, but when I use the drop down to select what specifics I want to be selected, It will not change anything. I do not know what I am doing wrong.
My XML tags are all correct I have made sure of it.
In the code you have posted, I don't see where you ask it to change anything when you select something in the drop down.What do you expect it to do? You will need to add a change listener to the drop down, and tell it what to do when it is changed, like this...
$("#dropdown").change(function() {
//Do what you want to do when the drop down is changed.
//You can get the text of the drop down like this...
var selected = $("#dropdown option:selected").text();
});
Also, as a side note, try refactoring your code so you only make the ajax call once, and use the output for both. Looks like your calling the same service twice for the same data which is extra work for no reason.