Set a value to HTML select while using Ajax and SweetAlert2 - html

I am building a form using SweetAlert2 + Ajax, but I have a problem with the <select> tag, so I will skip segments of the code that have nothing to do with the problem
The Ajax sends the email to the PHP code, then with the email I make a MySQL query to get the full information from the user (name, age and country), I storage the info in an array and returns it to the ajax with echo json_encode($arrayResult), then I print the data with SweetAlert2 but I have the problem that I dont know how to print it with the <select> tag, here is my code so you can understand me better...
The Ajax + SweetAlert2
$.ajax({
type: "POST",
url: "getuserdata.php",
data: {
email : emailX
},
success: function (response){
response = JSON.parse(response);
Swal.fire({
html:`<div>Insert your new information</div>
<div>
<span>Name</span>
<input id="name" type="text" value="${response.name}">
</div>
<div>
<span>email</span>
<input id="email" type="email" value="${response.email}">
</div>
<div>
<span>Age</span>
<input id="age" type="text" value="${response.age}">
</div>
<select id="country">
<option value="USA">USA</option>
<option value="England">England</option>
<option value="Canada">Canada</option>
</select>
`,
})
}
})
An just in case here is the PHP:
<?php
$mysqli = new mysqli("localhost","root","","store");
$mysqli->set_charset("utf8");
$email = $_POST['email'];
$sql = "SELECT * FROM clients WHERE email = '".$email."'";
$result = mysqli_query($mysqli, $sql);
$data = $result->fetch_assoc();
$count = mysqli_num_rows($result);
$arrayResult = [];
if($count > 0){
$arrayResult['name'] = $data['name'];
$arrayResult['age'] = $data['age'];
$arrayResult['country'] = $data['country'];
}else{
$arrayResult['name'] = '';
$arrayResult['age'] = '';
$arrayResult['country'] = '';
}
echo json_encode($arrayResult);
?>
Of course if this was a basic HTML code I would have solve it but it is inside a Javascript + Inside Ajax + inside a SweetAlert2 and I have try all the ways I know but dont work.
The country can be ONLY one of those 3 (USA, England and Canada), there is a ${response.country} that resturns one of those 3 countries.
So what I want is that depending of the country returned It will be the one selected in the <option> of the <select>

I guess you can just assign the return value to your select option!?
something like $("country").val(country);
also, maybe you can check this question, too.
link

Related

Display Data From Selected Value On the Select Tag to another Text Field

I want to call 2 values from database, to be placed on select "dropdown" and on input type text.
This might be considered as illustration :
When I select a vendor ID, I want attribute of selected value to be shown in Vendor Name field.
How I should do?
This is the code that i have to call the value for the tag :
in model :
function getAllGroups(){
$query = $this->db->query('SELECT idvendor, vendorname FROM tbvendor');
return $query->result();
//echo 'Total Results: ' . $query->num_rows();
}
in Controller :
public function addshipment(){
$data['title']= 'Vendor ID';
$data['groups'] = $this->m_shipment->getAllGroups();
}
in View :
<div class="form-group">
<label>Vendor ID:</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-institution"></i>
</div>
<select class="form-control input-box" name="idvendor">
<?php
foreach($groups as $row)
{
echo '<option value="'.$row->idvendor.'">'.$row->idvendor.'</option>';
}
?>
</select>
</div>
</div>
And this is table on my database
I'm already succeed to call the idvendor to place it on Select dropdown field, but i still can't get a way to place the vendorname into input type text when I select the idvendor.
Hope someone can gimme an answer.
Thanks
Basically imho this is a pretty simple task - since you've posted no code i'll give you an example
your select box
<select name="">
<option value="" data-vendor-name="your vendor name">Vendor Name</option>
</select>
your input field
<input type="text" name="data-vendor-name" value="" />
and the jquery code
$( document ).ready(function() {
$('option[data-vendor-name]').on('change', function() {
$('input[name="data-vendor-name"]').val($(this).attr('data-vendor-name'));
});
});

Send data to the server with AJAX

I want some help with the following issue. The following code is not working for me. Is there anyone who can help me with that? I've watched this in a youtube video and i can't find why it is not running..
I want to inform you that i am running a WAMP Server at 127.0.0.1 and it is very weird that the browser does not give me any response for errors, etc..
Here is my PHP code:
<?php
$host="127.0.0.1";
$username = "root";
$password = "";
$db = "data";
$conn = mysqli_connect($host, $username, $password, $db);
if (isset($_POST['fname'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$gender = $_POST['slct'];
$query = "Insert into users (firstname, lastname,gender) Values(?,?,?))";
$stmt = $conn->prepare($query);
$stmt->bind_param('sss', $fname, $lname, $gender);
$stmt->execute();
if(mysqli_affected_rows($conn) > 0){
echo "insert";
}
else{
echo "no";
}
}
?>
Here is my html code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h3> Insert Data into Database</h3>
<form id="form1" method="post">
<p> Enter FirstName</p>
<input type="text" name="fname" class="form-control">
<br>
<p> Enter lastName</p>
<input type="text" name="lname" class="form-control">
<br>
<p>Enter Gender</p>
<select class="form-control" name="slct">
<option value="Male">Male </option>
<option value="Female">Female</option>
</select>
<br><br><br>
<button class="btn btn-primary" onclick="insertData()">Submit</button>
</form>
</body>
<script>
function insertData(){
var formData = $('#form1').serialize();
$.ajax({
url:'http://127.0.0.1/PHP/insert.php',
data:formData,
type:'Post',
success:function(response){
console.log(response);
},
error:function(err){
console.log(err);
}
})
}
</script>
</html>
Any help will be appreciate.
Thank you in advance!
Your insert-command is incorrect. Change ...(?,?,?))"; to ...(?,?,?)";
Better use an IDE like netbeans, because they would highlight such errors. Also you should switch from mysqli to PDO. And you don't need to check affected rows. The $stmt->execute() returns a boolean

angularjs how to retrieve data from mysql and show in ng-select and ng-options

i was trying to populate data in html form using ng-select and ng-options.but cannot figure it out.my code looks like this:
function get_areanames() {
$qry = mysql_query('SELECT * from tbl_area');
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"areaid" => $rows['areaid'],
"areaname" => $rows['areaname']
);
}
print_r(json_encode($data));
return json_encode($data);
}
$scope.get_areanames = function($scope,$http){
$http.get("library/function.php?action=get_areanames").success(function(data)
{
$scope.areaname = data;
});
}
<select class="form-control select2me" data-placeholder="Choose Area Name" name="areaname" ng-model="areaname" required> <option></option></select>
You need to use ng-options, consider:
<select ng-options="item.areaid as item.areaname for item in areaname track by item.areaid"
ng-model="selectedArea"
class="form-control select2me"
name="areaname"
required>
<option value="">Choose Area Name</option>
</select>
You need to add the ng-options attribute to your select:
<select ng-options="areaitem.areaname for areaitem in areaname" ....
This will populate the options from the areaname array in your scope.

Select Drop Down with only one option as a link

I am trying to figure out how to make one of the options in my select drop down a link that redirects to that page. So far from researching this I have only found a way to make all the options links that are redirected to (Load page on selection from dropdown form) but I only want one of the options to be a link. Also I need the link to work without hitting the submit button.
EDITED USING #VLADIMIR'S SUGGESTION:
<form method="get" id="searchform" name="searchform" action="<?php echo home_url(); ?>/">
<select name="posttype" id="selection">
<option name="Product" value="Product">Legal Documents</option>
<option name="videos" value="videos">Legal Advice - Videos</option>
<option value="http://www.testing.com">An Attorney</option>
</select>
<input name="s" id="s" class="s" type="text" onfocus="if(this.value=='<?php _e('');?>') this.value='';" onblur="if(this.value=='') this.value='<?php _e('');?>';" value="<?php _e('');?>" />
<button tabindex="2" type="submit" class="search_btn">
</button>
<?php wp_dropdown_categories( 'taxonomy=videoscategory&show_option_all=All Practice Areas' ); ?>
<?php wp_dropdown_categories( 'taxonomy=states&show_option_all=All U.S States' ); ?>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#selection").change(function() {
var curVal = $("#selection option:selected").val();
if (curVal.indexOf('http://') === 0) {
location = $("#selection option:selected").val();
}
});
});
</script>
Also is there a way to have one option with multiple values?
You can adapt solution from the Load page on selection from dropdown form
Replace JS code with
$(document).ready(function() {
$("#selection").change(function() {
var curVal = $("#selection option:selected").val();
if (curVal.indexOf('http://') === 0) {
location = $("#selection option:selected").val();
}
});
});
The idea is that you check the option value and if it begins with 'http://', then you set new location.

AUSU jquery-Ajax Autosuggest Multiple values

I have a form which has the following fields:
Company Name,
Address,
City
Using the AUSU jquery autosuggest scripts I am able to populate the address field based on the search done in the company field but what I can't seem to be able to accomplish is also populating the city field with the appropriate value. All data is stored in a mysql database.
I've gotten as far as being able to have the address and city populate the address field but I need these 2 values to go into their respective fields (shiptoaddress and shiptocity).
Any suggestions?
This is my php to obtain data from mysql database:
<?php
$con = mysql_connect("localhost","userid","password");
if (!$con){ die('Could not connect: ' . mysql_error()); }
mysql_select_db("dbase", $con);
$id = #$_POST['id']; // The id of the input that submitted the request.
$data = #$_POST['data']; // The value of the textbox.
if ($id && $data)
{
if ($id=='clients')
{
$query = "SELECT shiptoaddress,company, shiptocity
FROM Clients
WHERE company LIKE '%$data%'
LIMIT 5";
$result = mysql_query($query);
$dataList = array();
while ($row = mysql_fetch_array($result))
{
$toReturn = $row['company'];
$dataList[] = '<li id="' .$row['shiptoaddress'] .$row['shiptocity'] . '">' . htmlentities($toReturn) . '</li>';
}
if (count($dataList)>=1)
{
$dataOutput = join("\r\n", $dataList);
echo $dataOutput;
}
else
{
echo '<li>No Results</li>';
}
}
}
?>
And this is part of the html form code:
<script>
$(document).ready(function() {
$.fn.autosugguest({
className: 'ausu-suggest',
methodType: 'POST',
minChars: 2,
rtnIDs: true,
dataFile: 'data.php'
});
});
</script>
</head>
<body>
<div id="wrapper">
<form action="index.php" method="get">
<div class="ausu-suggest">
<input type="text" size="100" value="" name="clients" id="clients" autocomplete="off" />
<input type="text" size="100" value="" name="shiptoaddress" id="shiptoaddress" autocomplete="off"/>
<input type="text" size="100" value="" name="shiptocity" id="shiptocity" autocomplete="off"/>
</div>
</form>
I solved my problem by using the Jquery autocomplete widget.