jQuery/AJAX: Fetching the customer details when surname's are common - javascript

here is an issue that I am facing. As you can see in the question I need to get the customer details of a particular customer when their surnames are common.
Currently on selecting the customer's surname I get a popup with the list of all common surnames. While selecting a particular customer I get some completely different customer details.
I am using codeigniter. I will post my code of the mvc below. Any help will be greatly appreciated.
VIEW (AJAX):-
$('.lname').on("select2-selecting", function(e) {
$.ajax({
url: '<?php echo base_url('index.php/agent/customer/customersByLastname'); ?>',
data: {q:e.val},
success: function(data){
var obj = $.parseJSON(data);
if(obj.length>1) {
var items = [];
$.each(obj, function (key, val) {
items.push("<li onclick='showSearch("+val.customer_id+")' value='"+val.customer_id+"'>"+val.name+" "+val.lname+"</li>");
});
$("#lnm").html(items);
$('#listmodal').modal('show');
}
}
});
});
function showSearch(id_cust) {
$.ajax({
url: '<?php echo base_url('index.php/agent/customer/getCustomer'); ?>',
type:'POST',
data: {cid:id_cust},
success: function(data){
var obj = $.parseJSON(data);
$('#customer_id').val(obj[0].customer_id);
$('#select2-chosen-1').text(obj[0].customer_id);
$('#select2-chosen-2').text(obj[0].name);
$('#select2-chosen-5').text(obj[0].phone);
$('#select2-chosen-4').text(obj[0].zip_code);
$('#listmodal').modal('hide');
}
});
}
CONTROLLER FUNCTIONS:-
public function customersByLastname ()
{
$customers = $this->customer_m->getCustomerByLastname();
echo json_encode($customers);
}
public function getCustomer ()
{
$customer_id = $this->input->post('cid');
$this->load->model('customer_m');
$customer = $this->customer_m->getCustomerById($customer_id);
echo json_encode($customer);
}
MODEL:-
public function getCustomerByLastname(){
$search_term = $this->input->get('q');
$this->db->like('lname', $search_term);
$this->db->select('customer_id');
$this->db->select('name');
$this->db->select('lname');
return $keywords = $this->customer_m->get();
}
public function getCustomerById($customer_id){
$query = $this->db->query("SELECT * FROM naturescrm_customers WHERE id='".$customer_id."'");
return $query->result();
}
That is pretty much the code that I have done for this. If anything else is required. Kindly let me know. Thanks

Related

How to insert multiple values to database table using php?

Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}
Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);

Using AJAX to post data into API

I have a script that uses AJAX to comunicate with PHP based API.
First part loads trade history:
$(document).ready(function () {
var orders = $('#History ul');
var user = "<?php echo $user; ?>";
$.ajax({
type: "GET",
url: "api.php",
data: {
user: user
},
success: function (response) {
console.log(response);
var res = JSON.parse(response);
$.each(res, function (index, value) {
console.log(value);
if(value['PL']>=0){
orders.append("<li style=\"color:green;\">" + value['User'] + "</li>");
}else{orders.append("<li style=\"color:red;\">" + value['User'] + "</li>");}
});
}
});
Second part posts a trade to database:
$("#submit").click(function(){
//event.preventDefault();
var oPrice = newOrder.elements["oPrice"].value;
var cPrice = newOrder.elements["cPrice"].value;
var oType = newOrder.elements["oType"].value;;
var oSymbol = newOrder.elements["oSymbol"].value;
var oAmount = newOrder.elements["oAmount"].value;
var json ={
'user': user,
'oPrice': oPrice,
'cPrice': cPrice,
'oType': oType,
'oSymbol': oSymbol,
'oAmount': oAmount};
alert(JSON.stringify(json)); //---check zda je naplněný
$.ajax({
type: "POST",
url: "api.php",
data: json,
success: function (response) {
alert(response);
}
});
});
The problem is, that when i press the button and send json, its missing the 'user' data and looks like this:
TraderBook.php?oPrice=1&cPrice=1&oType=LONG&oSymbol=1&oAmount=1
I have no idea why does ajax exclude it. The json variable has it filled out
I think your problem might be here
$(document).ready(function () {
var user = "<?php echo $user; ?>";
var is the JS scoping declaration. So you're limiting your user value to just the anonymous function being triggered by the page DOM load completing. What you should do is try scoping it outside the function
var user; //global scope
$(document).ready(function () {
user = "<?php echo $user; ?>";
This way, when your $("#submit").click(function() fires, there's a value to feed into your script.
I was wrongchecking the problem a mistook data from a form for the json. Problem was inside the API --> There was a tabulator in a SQL command..
Thanks to everyone for suggestions.

Magento insert data into database through ajax

I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",

Plot marker for each users location from database IP

I have a users table in my database that stores an ip address.
I have an api that gets the users latitude and longitude.
Firstly, I need to get every users lang and long.
At the moment, my code is only returning the last user in my database's lang and long.
This is my code for trying to return every clients long and langs:
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {
$username_ = $users_['username'];
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
}
Then I return this to my home PHP page using:
$response = array('client_latitude'=>$client_latitude,'client_longitude'=>$client_longitude);
echo json_encode($response);
I recieve the AJAX request with the following JS / JQUERY code:
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
var data = JSON.parse(value);
$('#lat').html(data['client_latitude']);
$('#long').html(data['client_longitude']);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
})
}
$(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
And then finally, I try and display these in div's for testing.
Eventually, I want them to go in to the jVectorMap Markers JS code so It can plot markers on my map from each users lang and long.
But for now, It's not getting each users lang and long. Only the last user in my database's.
UPDATED CODE
The code Sumarai posted below isn't working.
It is not updating the div id - all-the-coordinates.
Does anyone know what's wrong with my version ?
I am using some different code to the question I asked. I have been using it from the start but didn't post it here because I didn't think it would be this difficult.
My new script is the same but I am calling them in separate files now because I am already calling an array in my other file (get_dash_settings).
This is my script in my main PHP file:
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
var data = JSON.parse(value);
$('#totalUsers').html(data['totalUsers']);
$('#totalOnline').html(data['totalOnline']);
$('#freeModeStatus').html(data['freemode']);
$('#bypassesStatus').html(data['bypasses']);
$('#isOnline').html(data['client_is_online']);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
});
$.ajax({
url: "includes/get_dash_map.php",
context: document.body,
type: 'POST',
data: {get_data_:true},
success: function(value_) {
const data_ = JSON.parse(value_);
const $parent = $('#all-the-coordinates');
for (const row of data) {
const $element = $('<span></span>');
$element.text(`${data_['client_latitude']}, ${data_['client_longitude']}`);
$parent.append($element);
}
},
complete:function(){
setTimeout(fetchOnline,5000);
}
});
}
$(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
My get_dash_map.php:
$user_grab = mysqli_query($con, "SELECT * FROM users");
$response = [];
while($users_ = mysqli_fetch_array($user_grab)) {
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
$response[] = ['client_latitude' => $client_latitude,'client_longitude' => $client_longitude];
}
echo json_encode($response);`
Since you want to get a bunch of coordinates back, it makes sense to return them in an array of sorts. You are currently only getting the last one, because you are overwriting the values. Make an entry, then add that entry to the response as an array item. You can easily create a new array item with the [] suffix. $response[] = $x will add an array item to $response containing $x.
$user_grab = mysqli_query($con, "SELECT * FROM users");
$response = [];
while($users_ = mysqli_fetch_array($user_grab)) {
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
$response[] = [
'client_latitude' => $client_latitude,
'client_longitude' => $client_longitude
];
}
echo json_encode($response);
You obviously need to change your javascript too, as it currently expects an Object back with two keys, but you now get an Array of Objects back.
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
const data = JSON.parse(value);
const $parent = $('#all-the-coordinates');
for (const row of data) {
const $element = $('<span></span>');
$element.text(`${row['client_latitude']}, ${row['client_longitude']}`);
$parent.append($element);
}
}
})
}
$(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
with in the html
<div id="all-the-coordinates"></div>

Ajax not getting only json output data (it print whole loaded view code.).? codeigntier

Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)

Categories

Resources