Set value in select2 option by data from database - php

I want to make edit from. In this form contain input form control using select2 option. This select2 option input form can't display selected data that return from the database. I want to make the select2 option can be change too. I've tried this but still can display the selected data. Thank You :)
Here's my view
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
<?php echo form_open('company2/do_update') ?>
<form>
<select id="Name" class="searching form-control" style="width:500px" name="company"></select>
<button type="submit" class="btn btn-info waves-effect waves-light">Save</button>
<?php echo form_close(); ?>
</form>
</body>
<script type="text/javascript">
$('.searching').select2({
placeholder: 'Masukkan Nama Company',
ajax:{
url: "<?php echo base_url('company2/select2'); ?>",
dataType: "json",
delay: 250,
processResults: function (param) {
return {
compClue: param.term,
};
},
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.Name,
text: item.Name,
value:item.Name
});
});
return{
results: results,
cache: true,
};
}
}
});
var response = {};
response.val = "<?php echo $row['Name'];?>";
$("#searching option[value='" + response.val +"']").attr("selected","selected");

I would just output the content you want for the select to a div using PHP and then get the div content and append somewhere using javascript if needed.
<div id="selectOptions">
<?php
foreach($option as $row){
$optionVal = $row->optionVal;
$optionLabel = $row->optionLabel;
echo "<option value='$optionVal'>$optionLabel</option>";
}
?>
</div>
Since you are already using jQuery you can then get the content of the div using:
var options = $('#selectOptions').html();

Related

PHP Jquery Ajax POST call, not work

As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>

Ajax call to same page is not working

I am getting records from database in WordPress then creating and adding value in select tag(HTML) dynamically.
<?php
global $wpdb;
$registeredUsers = $wpdb->get_results('SELECT * FROM wp_users where user_login != "Admin"',ARRAY_A);
$select='<select name="users" class="form-control" id="users">';
$select.= '<option value="Select User"> Select User</option>';
foreach($registeredUsers as $user)
{
$select.='<option value="'.$user['user_email'].'">'.$user['user_login'].'</option>';
}
$select.='</select>';
?>
I am using $select variable in Html and drop down is being displayed properly.
<form id="a" action="" method="post">
<div style="margin: 0 auto;width:500px;">
<?php echo $select ?>
</div>
</form>
I have written code to get selected drop down onchange event in jquery. It return success but I am not able to get selected value of dropdown.
<script type="text/javascript">
$(document).ready(function(){
$("select[name='users']").change(function () {
jQuery.ajax({
type: "POST",
data: $("form#a").serialize(),
success: function(data){
alert("SUCCESS");
}
});
});
});
</script>
Below code return nothing
if(isset($_POST['users'])) {
echo $_POST['users'];
}
Set url option to your page in your ajax function:)
<script type="text/javascript">
$(document).ready(function(){
$("select[name='users']").change(function () {
jQuery.ajax({
type: "POST",
url:"yourpage.php"
data: $("form#a").serialize(),
success: function(data){
alert("SUCCESS");
}
});
});
});
</script>
replace yourpage.php

Twitter bootstrap typeahead return multiple values and fillup the editbox

I'm new in bootstrap and i need some help please, i want to create a typeahead drop-down that return 3 values from my mysql database when the user search for a contact name in "ContactName" TEXTBOX and fill up 3 edit box with the information of
-contact name
-Telephone Number
-email address
thanks a lot on advance for all your effort
this is the code that i try it to return one value i need to modified to return all those tree value
Now when i try to search the contact name it will return with correctly with no question to ask but i don't know how to modify the code to bring 3 value like i mention above
enter code here
**php page: Customer.php**
-------------------------------------------
<?php
$host = "localhost";
$uname = "root";
$pass = "";
$database = "db34218";
$connection=mysql_connect($host,$uname,$pass) or die("connection in not ready <br>");
$result=mysql_select_db($database) or die("database cannot be selected <br>");
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysql_query ("SELECT ContactName, Telephone, Email FROM customer WHERE ContactName LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['ContactName'];
}
echo json_encode ($array); //Return the JSON Array
}
?>
**html and java page and some php: Customersearch.php**
------------------------------------------------
<body>
.
.
.
<div class="row-fluid">
<div class="span4">
<label>ContactName </label>
<input type="text" name="ContactName" value="<?php echo $row_Recordset_QuoteCustomer['ContactName']?>" data-provide="typeahead" class="typeahead input-xlarge" autocomplete="off">
</div>
<div class="span2">
<label>Telephone </label>
<input type="text" name="Telephone" value="<?php echo htmlentities($row_Recordset_QuoteCustomer['Telephone'], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
<div class="span2">
<label>Email </label>
<input type="text" name="Email " value="<?php echo htmlentities(row_Recordset_QuoteCustomer['Email '], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
.........
.
.
.
.
.
.
<script src="../js/jquery.js"></script>
<script src="../js/bootstrap-transition.js"></script>
<script src="../js/bootstrap-alert.js"></script>
<script src="../js/bootstrap-modal.js"></script>
<script src="../js/bootstrap-dropdown.js"></script>
<script src="../js/bootstrap-scrollspy.js"></script>
<script src="../js/bootstrap-tab.js"></script>
<script src="../js/bootstrap-tooltip.js"></script>
<script src="../js/bootstrap-popover.js"></script>
<script src="../js/bootstrap-button.js"></script>
<script src="../js/bootstrap-typeahead.js"></script>
<script src="../js/SpecWorkPages/getItemsList.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('input.typeahead').typeahead({
source: function (query, process)
{
$.ajax(
{
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data)
{
console.log(data);
process(data);
}
});
}
});
})
</script>
</body>
</html>
<?php
mysql_free_result($RecordsetQuote);
mysql_free_result($Recordset_QuoteStatus);
mysql_free_result($Recordset_QuoteCustomer);
?>
If I'm understanding you correctly, you are getting results back but unable to populate the input fields. Although I don't use Twitter Bootstrap typeahead I do something very similar with jQuery's autocomplete feature. The code below is untested and of course you'll need to modify it for yourself but hopefully will be of some help.
See this working jsFiddle demo for something similar.
PHP
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
array_push($array,array('ContactName'=>$row['ContactName'],'Telephone'=>$row['Telephone'],'Email'=>$row['Email']));
}
echo json_encode($array);
You can check what gets returned by manually entering the URL (ex: yoursite/Customer.php?query=SomeContactName). You should see something similar to this:
[{"ContactName":"Some Contact","Telephone":"5555555555","Email":"email#whatever.com"},
{"ContactName":"Some Other Contact","Telephone":"5555555555","Email":"anotheremail#whatever.com"}]
HTML/Javascript
<script>
$('input.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
// data: 'query=' + query,
data: 'query=' + $('#contactName').val(),
success: function(data)
{
var results = data.map(function(item) {
var someItem = { contactname: item.ContactName, telephone: item.Telephone, email: item.Email };
return JSON.stringify(someItem.contactname);
});
return process(results);
}
});
},
minLength: 1,
updater: function(item) {
// This may need some tweaks as it has not been tested
var obj = JSON.parse(item);
return item;
}
});
</script>
Here are a couple other posts that you might want to take a look at How to return the response from an AJAX call? and Bootstrap typeahead ajax result format - Example

Submit an AJAX FORM from within an AJAX Success

I need to perform another AJAX Form Post from within the first forms success function.
Example, this does 2 AJAX requests.
Search Movie => Pick Movie Wanted => View Specific Movie Details
I am able to load the results into a div <div id="results"></div> just fine but once I select a movie title it isnt performing another AJAX Request, the request goes to the main window.
Here is the initial search page that handles the results.
<script type="text/javascript">
$(document).ready(function(){
$("#searchtitle").submit(function() {
var id = $(this).children('input[name="thetitle"]').attr('value');
$.ajax({
type: "POST",
url: "s.php",
data: $('#searchtitle').serialize(),
cache: false,
success: function(data){
$('#status').html(data);
}
});
return false;
});
});
</script>
<form id="searchtitle">
<input type="text" name="thetitle" />
<input type="submit" name="submit" class="button expand postfix" value="Search" />
</form>
<div id="status"></div>
s.php which returns results within #results
<?php
if(empty($_POST['thetitle'])) {
?>
<div class="alert-box error">
<div class="alert-error"></div>
Error: Nothing Found
</div>
<?php
}
if(!empty($_POST['thetitle'])) {
$myid = strtoupper($_POST['thetitle']);
$searchReults = $tmdb_V3->searchMovie($myid,'en');
?>
<?php
foreach($searchReults['results'] as $result) {
?>
<form class="sform">
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
<h5><?php echo $result['title']; ?></h5>
<span class="mreleased">Year: <?php echo $result['year']; ?></span>
<input type="submit" class="button" value="Select">
</form>
<?php
}
}
?>
This is the code that will post the results from s.php
<script type="text/javascript">
$(".sform").submit(function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize();
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
}
</script>
I have tried putting this within s.php, within the bottom of the initial search page, in the head of the initial page and no luck, it submits fine just not the sx.php where it should.
In s.php the statement:
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
Should be:
<input type="hidden" name="mid" value="<?php echo $result['id']; ?>" /> //remove extra bracket
In your javascript code in s.php there are some typos:
data: $(this).closest("form").serialize(); // here should be comma not semicolon
After return false you should close the script properly } should be });.
And since you are trying to submit the dynamic content $(".sform").submit(function () will not work. You should use on for dynamic contents. So the correct script would be:
<script type="text/javascript">
$(document).on('submit', '.sform', function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize(),
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
});
</script>
I have checked and verified in my localhost (with a simple setup). It is making both ajax request. Hope this helps!

JQuery Post - Why I can't see response?

This is my HTML PAGE
I want to send some values with ajax then I want to get them with ajax response but I can't see any character in my div which called with id=result . Where is the problem?
<html>
<head>
<!-- JQuery v1.8.2 -->
<script src="theme/scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div class="row-fluid">
<div class="span4">
<input type="text" id="title"/><br>
<textarea rows="10" cols="50" id="content"></textarea><br>
<input type="submit" id="gonderBtn" name="gonderBtn" />
<div id="result"></div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#gonderBtn").click(function(){
var title = $("title").val();
var content = $("content").val();
$.ajax({
url: "deneme_action.php",
dataType: "html",
type: 'POST',
data: {
title: title,
content: content
},
success: function(data){
$("result").html(data);
}
});
});
});
</script>
</body>
</html>
deneme_action.php
<?php
if(isset($_POST["gonderBtn"])){
$result = "Sonuc:".$_POST["title"];
echo "Selam:".$result;
}
else{
echo "no post";
}
?>
Because you don't have a tag with class="result" but you have a tag with id="result".
Either change the jQuery selector to:
$("#result").html(data);
Or the div tag to:
<div class="result"></div>
and selector to:
$(".result").html(data);
And you are not sending gonderBtn with the POST - fix it too:
$("#gonderBtn").click(function(){
var title = $("#title").val();
var content = $("#content").val();
var gonderBtn = $(this).val();
$.ajax({
url: "deneme_action.php",
dataType: "html",
type: 'POST',
data: {
title: title,
content: content,
gonderBtn: gonderBtn,
},
I've also fixed the selectors for input and textarea too.
Check this line:
echo "Selam:"+$result;
Here the plus operator is an error so the php script is not returning anything.
Check this link that documents the use of + operator in php.
var title = $("title").val();
var content = $("content").val();
should be
var title = $("#title").val();
var content = $("#content").val();
You will also need to change:
$("result").html(data);
to
$("#result").html(data);
You should also wrap your inputs in a form.
Edit:
You might want to give your button input a value.
<input type="submit" id="gonderBtn" name="gonderBtn" value="go!" />
Edit 2:
You will also need to give your html elements a name.
<input type="text" id="title" name="title"/><br>
<textarea rows="10" cols="50" id="content" name="content"></textarea><br>
You're not selecting your #result div properly, add a # before
$("#result").html(data);
the same goes for all your selectors
var title = $("#title").val();
var content = $("#content").val();
Since your ajaxing your form you'll have to manually pass your button parameter, although an ajax parameter would be more appropriate.
data: {
title: title,
content: content,
gonderBtn: 'gonderBtn'
},
echo "Selam:"+$result;
In php use "." to concatenate strings.
echo "Selam:".$result;

Categories