i know this question has been asked in many another case in this site. But still, i dont have the right answer to solve my problem .
i want to make the ajax function for my combo box and textarea. So when i select an option in the combo box, text inside textarea will change depending on the combo box's selected value.
UPDATED: my textarea code
this is my combobox and textare code :
<select class="form-control" name="option_template" id="template" onchange="get_template(this.value);">
<option value="" selected="" disabled=""> -- Pilih Template --</option>
<?php foreach ($template as $template){
?>
<option value="<?php echo $template['id'];?>"><?php echo $template['nama'];?></option>
<?php }
?>
</select>
<div class="col-md-8 col-sm-8 col-xs-12">
<textarea id="template-content"></textarea>
</div>
this is my javascript function and the ajax
<script type="text/javascript">
// alert("hai");
function get_template(id){
alert(id);
$.ajax({
method:"POST",
url:'<?php echo base_url();?>broadcast/ajax_template',
data:{option:id},
succes:function(msg){
alert(msg);
$('#template-content').val(msg);
}
});
}
</script>
and the last , this is my php function that retrieve the post from ajax
public function ajax_template(){
$id=$this->input->post('option');
$q=$this->M_template->get_template($id)->row_array();
echo "Test output".$q['content'];
}
when i run the code above, the alert(id); in the javascript get_template() function syntax is working, so i get the option value everytime i select the option. But the problem is i cannot get the output data from the ajax's post. Can someone please help me with this? i know this is maybe a basic knowledge but i've spent hours to solve this problem , thank you :)
This is weird and i dont know why my previous code is not working. But i found a new way to do this by using change() function to the select syntax and use the get method instead of post.
this is my javascript and ajax function
$("#template").change(function() {
var e = document.getElementById("template");
var id = e.options[e.selectedIndex].value;
$.ajax({
url: '<?php echo base_url();?>Broadcast/ajax_template?option='+id,
success: function(msg){
$('#template-content').val(msg);
}});
});
i removed onchange attribute of my select syntax
and change the php function to get the id from post to get
$id=$this->input->get('option');
Change your ajax_template() method
You are getting response from M_template as an array. you cannot echo array as like that.
Use echo json_encode($arrayname). in your case echo json_encode($q['content']);
and make sure that in ajax you mention dataType:'json'
Could you please call your function
public function ajax_template(){
$id = $this->input->post('option');
$q=$this->M_template->get_template($id)->row_array();
echo "Test output".$q['content'];
exit;
}
Without using ajax and check it will display anything or not. Please pass static value on $id variable.
Related
I use Codeigniter Framework and there I use the dorm_dropdown.
<?php echo form_dropdown('wptypes', $wpstatuses, set_value('wptypes'), 'id="wptypes" class="form-select" onchange="this.form.submit()'); ?>
This is my code and when I add the onchange function then the first value of my options get lost. Without onchange everything is working. Why is this so?
Thank you and sorry for my bad english :)
it is because you are missing the closing double quote of the onchange event.
try it like this:
<?php echo form_dropdown('wptypes', $wpstatuses, set_value('wptypes'), 'id="wptypes" class="form-select" onchange="this.form.submit()"'); ?>
Code is below.... I have dropdown menu - that is using PHP to query SQL, in order to populate the dropdown menu options, which is working fine.
You will see below - the sql query is statically configured, I would like to make this more dynamic.
Ideally id like another drop down menu on the same page with statically configured country options, and then when the customer selects which country my PHP script updates with the country in the sql query that php is using....
So for example where in my script below it says;
WHERE country ='SE'
I want it to populate with which ever country the user has selected in the pull down menu, so it could be 'FR', 'DE' or whatever country code has been selected.
I suspect this may be javascript? or maybe php can do this...?
I'm very much a novice level - so if you can be of assistance as much detail, or script as possible please :)
<html>
<body>
<form name="search" action="\cgi-bin\eu.py" method="get">
<?php
require_once 'db.inc.php';
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$sqlSelect="SELECT * FROM clnts WHERE country ='SE' ORDER BY clnt_name";
$result = $mysqli -> query ($sqlSelect);
if(mysqli_num_rows($result)){
$select= '<select name="select">';
while($rs=mysqli_fetch_array($result)){
$select.='<option value="'.$rs['mgmt_ip'].'">'.$rs['clnt_name'].'</option>';
}
}
$select.='</select>';
echo $select;
?>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You can POST the selected dropdown value to the same page. You can do this automatically by using an 'onChange()' event on the dropdown menu.
Use this to POST to the same page and then get the value for the selected option and use that in your query...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
add this at the top of you PHP....
if(isset($_POST['select']))
{
$selected_country_var = " country = '" . $_POST['select'] . "' ";
}else
{
$selected_country_var = " ";
}
edit your query to ...
$sqlSelect="SELECT * FROM clnts WHERE" . $selected_country_var . " ORDER BY clnt_name";
now edit your option/dropdown to have the onChnange event...
<select name="select" onchange="this.form.submit()">';
Let me know if I should clarify or if you need additional functionality.
It's usually not a "clean" solution to put together both server and client side code on the same page.
It's actually a better practice to put the server code on a seprate file for example 'handler.php' or 'api.php' and then call it using XMLHttpRequest (more commonly known as AJAX) ...
then, when using ajax you can pass data to the server using POST or GET variables and have it process the data.
that way you can create client side which is more fluent, and communication between the server and the client will be more "tidy"
in your case if you have say 'handler.php' on the server and use jquery ajax you could do something like :
client.html
$.ajax({
url : 'path_to_handler.php',
method : 'POST',
data : { countryCode : 'IL', otherVar : 1 },
onSuccess : function(result){
// do whatever with the data
}
});
and on the server
handler.php
if( isset($_POST['contryCode']) ){
// query the db and have the result returned as json
echo json_encode($result_query);
}
I'm new to codiginiter and it's still developing.
I'm trying to send a JS value to codiginiter controller but I'm getting errors. Firebug says syntax error. But when I correct it, another syntax error is being shown.
I think the problem is with my script. Can anyone can figure out what's wrong? All I want is to send username value to method in controller. Following alert is triggered when I press the button (tested and working).
<script type="text/javascript">
$(function(){
$("#postAnswer").click(function(){ // passing down the event
alert("checked");
$.post('<?php echo base_url(); ?>homepage/postanswer', {
//username:document.getElementById('username').value
username:<?php $ques[0]->username ?>
});
});
});
</script>
Correct way to echo PHP variable would be to JSON encode it first (and use echo):
$.post('<?php echo base_url(); ?>homepage/postanswer', {
username: <?php echo json_encode($ques[0]->username); ?>
});
Depending on what the error is with FireBug, it's like an issue of needing to enclose the <?php $ques[0]->username ?> in quotes to make it a string.
username: "<?php $ques[0]->username ?>"
Use append('username',$query[0]->yourdataname)
This form is working perfectly fine, e.g. it stops the form submitting, there's no javascript errors in the console log. However, when I press submit, I get an alert with nothing in it. I have searched the internet for multiple solutions and they all give the same for me.
Here's my Javascript/Html
<script>
$(function(){
$("#submit").click(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"templates/process-token.php",
data:$("#form").serialize(),
success:function(response){
alert(response);
}
});
});
});
</script>
<form id="form" method = "post" action = "security_check">
<input type = "text" name = "fld1" id = "fld1" />
<input type = "text" name = "result1" id = "result1" value = "value_from_php_page" disabled />
<input type="submit" value="Submit" id="submit">
</form>
And here's the PHP, it's so simple but doesn't work:
<?php
echo $_POST["fld1"];
?>
Any help here would be appreciated. Thank you.
Change data from $('#form').serialize() to a one test variable so you can see if it is JS or PHP that is causing the issue.
On your PHP page:
<?php
isset($_POST["fld1"]) ? $myvar1 = $_POST["fld1"] : $myvar1 = 'No data passed...';
echo $myvar1;
?>
This confirms that there is infact an fld1 in the $_POST, and if not, says so, taking away the guess work...
You could do this with JSON both ways. Here's how I would implement this kind of thing in JavaScript and PHP.
There's a great function in jQuery that is a shortcut for getting JSON data. It's a shortcut for $.ajax specifically for simple calls.
$.getJSON( "templates/process-token.php?"+$("#form").serialize(), function( data ) { alert( data.reponse ) } );
PHP could return a json encoded string so it can be accessed from the JavaScript code more easily.
<?php echo json_encode( array('response'=>$_POST['fld1']) ); ?>
That can happen only if the text box #fld1 is empty. Type something in the text box and it will work.
I have two dropdown menus that read their data from a MySQL database. I use PHP for connecting to database. The second dropdowns should get populated based on the selection on the first dropdown. The process seems as below to me (correct me if I'm wrong):
PHP section connects to MySQL database and populates dropdown1.
user selects a value on dropdown1 and onchange event is called.
within the onchange function (which is Javascript), a query is sent to MySQL database to fetch values of dropdown2 based on the dropdown1 selection (here is PHP again, right?).
dropdown2 gets populated.
I don't know how to use Javascript and PHP together in order to do this task (number 3 above); or maybe this is not the way to do it at all. Please advise!
Here is my code. As you see below, I'm putting a Javascript function within a PHP code which I suppose is wrong. That's where I got stuck!
<php
$sql="SELECT distinct category FROM table1";
$result=mysql_query($sql);
$optionsCat="";
while($row = mysql_fetch_row($result)){
$optionsCat.="<option value=\"$row[0]\">$row[0]</option>";
}
function genSubCat($catID){
$sql="SELECT distinct subcategory FROM table1 where category=".$catID;
$result=mysql_query($sql);
$optionsSubCat="";
while($row = mysql_fetch_row($result)){
$optionsSubCat.="<option value=\"$row[0]\">$row[0]</option>";
}
}
?>
<select name="catDropDown" onChange="genSubCat(this)">
<option value="0">Select category</option>
<?php echo $optionsCat?>
</select>
<select name="subcategoryDropDown">
<option value="0">Select subcategory</option>
<?php echo $optionsSubCat?>
</select>
Here we have a simple page with input on it. Type a word into it and then click off of the input. Ajax will call the myphp.php script and return the same word you typed in below the original division.
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#faq_search_input").blur(function(){
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if(faq_search_input.length>1){
$.ajax({type: "GET", url: "myphp.php", data: dataString,
success: function(server_response) {
document.getElementById("searchresultdata").style.display = "block";
$('#searchresultdata').html(server_response).show();
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="searchholder">
<input name="query" class="quicksearch" type="text" id="faq_search_input" />
<div id="searchresultdata" class="searchresults" style="display:none;"> </div>
</div>
</body>
</html>
myphp.php:
<?PHP
echo $_GET['keyword'];
?>
I think you should first study yourself about using web based languages. The code that you've provided is completely wrong. You're trying to access PHP code through HTML? I mean come on!
First rule: Server based languages can't communicate with Client based languages.
You have to send requests and get responses and the way you want to do that dropdown thing is to send a request to a PHP code and get relevant data from it. As Trufa said in the comment, you may want to look at jQuery library, but before that I think you need to check AJAX.