Return multiple strings from AJAX - ajax

With AJAX post i'm sending a data and on other page, according to this data i'm retrieving two different column values of mysql database by query. And i need to get back these two different values as a result of AJAX and show in two different inputs.
var mus_barkod = document.getElementById('mus_barkod').value;
var dataString = "mus_barkod="+mus_barkod;
$.ajax({
type: "POST",
url: "musteri_indir.php",
data: dataString,
success: function(result){
$("#indirim").val(result.mus_indirim);
$("#mus_isim").val(result.mus_isim);
This is the part of AJAX and below the (OLD) query for fetching data:
$mus_barkod = $_REQUEST['mus_barkod'];
$mus_cek = mysql_query("SELECT * FROM musteriler WHERE mus_barkod =
'".$mus_barkod."' AND sub_id = '".$per_sube."' ");
while ($mus_al=mysql_fetch_array($mus_cek)){
$mus_isim = $mus_al['mus_isim'];
$mus_indirim= $mus_al['mus_indirim'];
}
$mus_isim1 = 'Kayıtlı Müşteri Değil';
$mus_indirim1 = '0.00';
if($mus_barkod == '10' || $mus_barkod == '100090'|| $mus_barkod ==
'100237')
{
echo
$mus_indirim,$mus_isim;
}else{
echo
$mus_indirim1,$mus_isim1;
}
So how can i get back mus_indirim and mus_isim seperately and show in different inputs?
NOTE: Don't mind mysql_, this is an old system. PDO Forever :)

Fixed it by checking my codes more carefully. Here is the result for those need the same solution:
var mus_barkod = document.getElementById('mus_barkod').value;
var dataString = "mus_barkod="+mus_barkod;
$.ajax({
type: "POST",
url: "musteri_indir.php",
data: dataString,
dataType: "json", => the little thing i forgot to write :)
success: function(result){
$("#indirim").val(result.mus_indirim);
$("#mus_isim").val(result.mus_isim);
The Old PHP:
$mus_barkod = $_REQUEST['mus_barkod'];
$mus_cek = mysql_query("SELECT * FROM musteriler WHERE mus_barkod =
'".$mus_barkod."' AND sub_id = '".$per_sube."' ");
while ($mus_al=mysql_fetch_array($mus_cek)){
$mus_isim = $mus_al['mus_isim'];
$mus_indirim= $mus_al['mus_indirim'];
}
if($mus_barkod == '10' || $mus_barkod == '100090'|| $mus_barkod ==
'100237')
{
echo json_encode(array("mus_indirim" => $mus_indirim, "mus_isim" =>
$mus_isim));
}else{
echo json_encode(array("mus_indirim" => '0.00', "mus_isim" => 'Kayıtlı
Müşteri Değil'));
}

Related

Bootstrap Select 'refresh" continues to add new options instead of removing the old ones

Any help here would be appreciated as I can't see what I'm doing wrong.
I have an empty select picker:
<select class='selectpicker' name='new_teamid' id='new_teamid' style='width:200px;margin-left:-5px;margin-top:0px;' required></select>
This is being populated via AJAX call when another select box option has changed
var query_parameter = document.getElementById("new_deptid").value;
var dataString = 'dept=' + query_parameter;
// AJAX code to execute query and get back to same page with table content without reloading the page.
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('refresh');
}
});
As you can see, its calling another php page which returns an HTMl string for the options. This works, if i inspect the element, the HTML options are updated correctly. im using = not +=. Problem is, the selectpicker is not removing the previous items. It just keeps adding the new items.
Any idea what I may be doing wrong here?
If you are curious, this is the populateteams.php
$theHTML = "";
$theHTML .= '<option value="" selected>Please Select</option>';
$sql = "SELECT * FROM tool_teams WHERE (dept_id=?) ORDER BY teamname asc";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $dept_id);
if ($stmt->execute() === TRUE) {
$result = $stmt->get_result();
if(!empty($result) && $result->num_rows)
{
while ($row = mysqli_fetch_array($result))
{
$theHTML .= '<option value="'.$row['team_id'].'">'.$row['teamname'].'</option>';
}
}
}
echo $theHTML;
resolved this myself. This is dumb, but this is how you need to do it:
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('destroy');
$('#new_teamid').selectpicker('render');
},
complete: function(html) {
}
});
You need to destroy and render instead of refresh. This is stupid. But it works

How to remove dublicate values using codeigniter and ajax?

I return passports from my database when I select user using codeigniter and I'm getting these data using ajax.
This is my php code in the controller:
public function contactsPassports(){
// POST data
$this->load->model('contacts/contacts_international_pass_m');
$data = $this->input->post();
$passports = array();
$where = array('contact_id'=>$data['selected_id']);
$passports = $this->contacts_international_pass_m->where($where)->order_by('id','DESC')->get_all();
if(!empty($passports)) {
foreach($passports as $item)
{
$item->pass = $this->contacts_international_pass_m->get($item->nat_passport_num);
}
}
$this->data->passports = $passports;
echo json_encode($this->data);
}
And this is my ajax code:
$.ajax({
url:'/companies/ajax/contactsPassports',
method: 'post',
data: {"selected_id": contactID},
dataType: 'json',
async: true,
success: function(data){
var html = '';
$.each(data.passports, function(key, value) {
console.log(data);
html += '<div class="nationality_name" style="float:left">'+ value.nat_passport_num + '</div>' + '<div class="nationality_name_delimiter" style="float:left">'+', '+'</div>';
});
$('#passport').html(html);
}
});
But I want to remove the dublicate passports for every user. For example now I am getting this:
User 1
12345678, 1234, 1234, 123456, 123456
And I want to getting this:
User 1
12345678, 1234, 123456
You can use distinct query builder to select only distinct values:
$passports = $this->contacts_international_pass_m->distinct()->select('nat_passport_num')->where($where)->order_by('id','DESC')->get_all();

How to show array result in ajax success using codeigniter?

I am fetching values from data using where in() mysql query and I got the correct result, but I don't know how to display the result in ajax success.
How do I display company name and email id from result data set?
my ajax code
<script type="text/javascript">
$('#ok').on('click', function() {
var vals = $('#show').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: { vals:vals },
datatype: 'json',
success: function (data) {
alert(data);
$("#result").html(data);
var result = JSON.parse(data);
}
});
});
</script>
my controller code:
function get_company()
{
$vals = $this->input->post('vals');
$query = $this->db->query("SELECT * FROM customer` where company_id IN ($vals) ")->result();
echo json_encode($query);
}
my result:
[{"company_name":"xyz Ltd","company_email":"123#gmail.com"},{"company_name":"wer Jit","company_email":"2222#gmail.com"}]
assuming you get this json in your ajax success:
const json = '[ {
"company_name": "xyz Ltd",
"company_email": "123#gmail.com"
},
{
"company_name": "wer Jit",
"company_email": "2222#gmail.com"
}]
';
const obj = JSON.parse(json);
// you don't need this line, if you have set ajax datatype:'json'
you can get results for a single data set:
console.log(obj[0].company_name);
// this is how to get the first company name of the data set
// expected output: "xyz Ltd"
or you can loop through the whole data set
obj.forEach(element => $("#result").append(element.company_name + '<br>'));
see a working example
conclusion: your ajax function could look just simply like this:
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: {
vals: vals
},
datatype: 'json',
success: function(data) {
obj.forEach(data => $("#result").append(data.company_name + '<br>'));
}
})

AJAX failing to upload blob image

I have a problem with uploading a blob using ajax. I have tried many options and they are not working.
I must say that the same variables (albeit with different names) work when using php in the standard sense but not when using ajax.
Please help
The ajax code is:
$(function() {
$("#upload").click(function() {
// validate and process form here
var username = $("input#username").val();
var title = $("input#title").val();
var image = $("#image").get(0).files.item(0);
var information = tinymce.get('blogcontent').getContent();
var dt = new Date();
// variable for blog date and time
var dateandtime = dt.toLocaleString();
var dataString = 'username=' + username + '&title=' + title + '&image=' + image + '&information=' + information + '&dateandtime=' + dateandtime;
$.ajax({
type: "POST",
url: "functions/insertblogpost.php",
data: dataString,
success: function() {
$('#writeblog').html("<div id='message'></div>");
$('#message').html("<h2>User account created!</h2>")
.append("<p>Please go back to login.</p>")
.hide()
.fadeIn(1000, function() {
$('#message').append("<a href='../../Mobileapptemplate.php'>Back</a>");
});
}
});
return false;
});
});
And the php script is:
$connection = mysqli_connect($dbserver, $dbusername, $dbpassword, $database);
$username = $_POST[ 'username' ];
$blogTitle = $_POST["title"];
$blogContent = $_POST["information"];
$blogpicturename = $_FILES["image"]["name"];
$blogpicdata = mysqli_real_escape_string( $connection, file_get_contents($_FILES["image"]["tmp_name"]));
$blogpictype = $_FILES['image']['type'];
$dateAndTime = $_POST["dateandtime"];
$result = "INSERT INTO ct5006ho_users.$username ( postnumber, user, title,
picturename, picture, blogpost, dateandtime ) VALUES ( '', '$username', '$blogTitle','$blogpicturename',
'$blogpicdata','$blogContent', '$dateAndTime');";
//if (
mysqli_query($connection, $result);
The connection IS established fine and all other data uploads to the phpmyadmin created database. I have omitted those details from the code.
Here is the answer:
$(function() {
$("#upload").click(function() {
// validate and process form here
tinyMCE.triggerSave();
var form = $('form')[0]; //
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "functions/insertblogpost.php",
data: formData, // Data sent to server, a se
contentType: false,
cache: false, // To unable request pages to be cached
processData:false,
success: function() { ....................
If anybody has a similar issue please use this experience to help you.
Note - tinyMCE.triggerSave(); - sends the tinyMCE data. and this was my original issue with the - data: formData,
Ah well, shoot me down for asking!

how to determine the URL for ajax

As stated in the title...I am having trouble determining whether I'm actually performing the post operation properly or if the operation is properly performed then why is the value empty since I checked the value before passing it in the post operation...here is my code:
script:
$.ajax({
url: "<?php echo base_url();?>/Index/viewDayDocuments",
type: 'post',
data: {currentDay: 'currentDay', currentMonth: 'currentMonth', currentYear: 'currentYear'},
success: function(result){
$('.list').text('');
$('.list').remove();
$(".listIncoming").html("<p class = 'list'>This is the: "+ result +"</p>");
$("#myform").show(500);
}
});
controller code which throws back a return value:
$data['day'] = $_POST['currentDay'];
$data['month'] = $_POST['currentMonth'];
$data['year'] = $_POST['currentYear'];
$date = $data['year']."-".$data['month']."-".$data['day'];
$this->load->model('search_form');
$output['details'] = $this->search_form->searchDateRetrievedIncoming($date);
return $data;
Your ajax request needs a string echoed as a string.
$data['day'] = $_POST['currentDay'];
$data['month'] = $_POST['currentMonth'];
$data['year'] = $_POST['currentYear'];
$date = $data['year']."-".$data['month']."-".$data['day'];
$this->load->model('search_form');
$output['details'] = $this->search_form->searchDateRetrievedIncoming($date);
echo json_encode($data);
An array cannot be echoed out correctly if it's not in a data format, such as JSON.
Now we, take the data in your javascript
$.ajax({
url: "<?php echo base_url();?>/Index/viewDayDocuments",
type: 'post',
data: {currentDay: 'currentDay', currentMonth: 'currentMonth', currentYear: 'currentYear'},
success: function(result){
$('.list').text('');
$('.list').remove();
date = JSON.parse(result);
$(".listIncoming").html("<p class = 'list'>This is the: "+ date.month +"/"+date.day+ "/"+date.year +"</p>");
$("#myform").show(500);
}
});
In this module, I transformed the STRING from your PHP file into a JSON object so it can be read properly.

Resources