Retrieve data using Ajax Php laravel 5.3 - ajax

According to my scenario when I select a doctor whose id is #slmc, I want to retrieve data relevant to the doctor I have chosen..
This is my blade File -> Admin/channel.blade
<label id="lslmc" for="slmc" class="control-label">Choose a Doctor </label><br />
<select class="form-control" id="slmc" name="slmc" onchange=" getPatient()" >
<option value="">----Select the Doctor----</option>
#foreach($Doctors as $Doctor)
<option value ="{{$Doctor-> slmc}}">{{$Doctor->fname}} {{$Doctor->sname}} </option>
#endforeach
</select>
</div>
<div id ="dd"></div>
Then this is my getPatient() function in the controller
public function getPatient($slmc){
$patients = DB::table('channel')->where('slmc', $slmc)->get();
return $patients;
}
This is the Ajax call in the script function.
function getPatient() {
var patient = $("#slmc").val();
$.ajax(
{
type: 'get',
url: ('/Admin/channel/getPatient'),
data: {'patients': patient},
success: function (data) {
$('#dd').html("");
$('#dd').html(data);
}
}
);
}
This is web.php
Route::get('/Admin/channel/getPatient{slmc}', 'channelController#getPatient' );
Is there something wrong with my Ajax call. I'm new to it.

Route :
Route::get('/Admin/channel/getPatient', 'channelController#getPatient' );
Controller :
ChannelController.php :
use Illuminate\Http\Request;
class ChannelController extends Controller
{
public function getPatient(Request $request){
$patients = \DB::table('channel')->where('slmc', $request->patients)->get();
return $patients;
}
}

I was able to do it
The ajax function goes like this
function getPatient() {
var patient = $("#slmc").val();
$.ajax({
type: 'get',
url: ('/Admin/channel/getPatient'),
data: {'slmc': patient},
success: function (data) {
$('#dd').html("");
var divHtml = "";
divHtml += "<table class='table table-bordered table-hover'>";
divHtml += "<tr>";
divHtml += "<td>" + data[0].pname + "</td>";
divHtml += "<td>" + data[0].address + "</td>";
divHtml += "</tr>";
divHtml += "</table>";
$('#dd').html(divHtml);
console.info(data);
},
error: function (data) {
console.error(data);
}
});
}
And my controller function is
public function getPatient(Request $request) {
$slmc = $request->get('slmc');
$patients = \DB::table('channel')->where('slmc', $slmc)->get();
return $patients;
}
web.php
Route::get('/Admin/channel/{slmc}', 'channelController#getPatient' );

Related

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

How to check email aleady exist using ajax in magento 2

Controller
Email.PHP
`
public function execute()
{
$customerEmail=$this->getRequest()->getParam('email');
$objectManager=\Magento\Framework\App\ObjectManager::getInstance();
$CustomerModel = $objectManager->create('Magento\Customer\Model\Customer');
$CustomerModel->setWebsiteId(1);
$CustomerModel->loadByEmail($customerEmail);
$userId = $CustomerModel->getId();
if ($userId) {
return 1;
} else {
return 0;
}
}`
j Query
jQuery(function() {
var emailAddress = jQuery('#email_address');
emailAddress.on("change", function () {
var mail=emailAddress.val();
jQuery.ajax({
type: "POST",
url: "/customer/email/",
dataType: "json",
data: {email: mail},
success: function (exist) {
if (exist == 1) {
alert("exist");
} else if (exist == 0) {
alert("exist");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error " + jqXHR.status + " " + jqXHR.statusText);
}
});
});
});
I want to check email before clicking create an account button using Ajax, i am not getting to do that, please help me out to solve this issue, thanks in advance.
It seems like you are trying to validate email address as customer enter his email address. For this you just need minor change in the email address field.
<input type="email" name="email" id="email_address" autocomplete="off" value="<?php echo $block->escapeHtml($block->getFormData()->getEmail()) ?>" title="<?php /* #escapeNotVerified */ echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true, 'remote':'<?php echo $this->getUrl('customcustomer/index/uniqueemail', ['_secure' => true]); ?>'}"/>
Create a controller and add you logic in execute method.
<?php
namespace Gaurav\CustomCustomer\Controller\Index;
use Magento\Framework\App\Action\Action;
class Uniqueemail extends Action
{
/**
* #var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;
/**
* #var \Magento\Customer\Model\Customer
*/
protected $_customerModel;
/**
* #param \Magento\Framework\App\Action\Context $context
* #param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Customer\Model\Customer $customerModel
) {
$this->resultJsonFactory = $resultJsonFactory;
$this->_customerModel = $customerModel;
parent::__construct($context);
}
public function execute()
{
$resultJson = $this->resultJsonFactory->create();
$email = $this->getRequest()->getParam('email');
$customerData = $this->_customerModel->getCollection()
->addFieldToFilter('email', $email);
if(!count($customerData)) {
$resultJson->setData('true');
} else {
$resultJson->setData('That email is already taken, try another one');
}
return $resultJson;
}
}
I hope this will be helpful to you.
Simple call a ajax like this
var mail = 'test#.com';
jQuery.ajax({
type: "POST",
url: "/module/checkemail/",
dataType: "json",
data: {email: mail},
success: function (exist) {
if (exist == 1) {
// js for email exists
} else if (exist == 0) {
// js for not
}
},
error: function (jqXHR, textStatus, errorThrown) {
// error handling
}
});
Than make a controller and load customer by email
$CustomerModel = $objectManager->create('Magento\Customer\Model\Customer');
$CustomerModel->setWebsiteId(1); **//Here 1 means Store ID**
$CustomerModel->loadByEmail($customerEmail);
$userId = $CustomerModel->getId();
if ($userId) {
return 1;
} else {
return 0;
}
i
if you get true than email exists.

populating dropdown based in first selection

My COntroller
public function gettestRecieve() {
$test = array('recieve' => $this->input->post('recieve'));
$data = $this->test->getrecieve($test);
echo json_encode($data);
}
My Model
function getAcademic($test) {
$this->db->select('a_y');
$this->db->where($test);
$this->db->distinct();
$result = $this->db->get('table');
$return = array();
if($result->num_rows() > 0){
$return[''] = 'select';
foreach($result->result_array() as $row){
$return[$row['a_y']] = $row['a_y'];
}
}
return $return;
}
My view
$(document).ready(function () {
$('#test').change(function () {
var add = $(this).val();
//console.log(add);
$.ajax({
url: "<?php echo base_url();?>getAcademic",
method: "POST",
data: {testing: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
//alert(data[0].Ayear);
$('#good').html('<option value="'+ Ayear +'" >'+ Ayear +'</option>');
}
})
});
});
this gives me an error object HTMLSelectElement what does it mean, when i tried to look at my console it gives me a right value {"": "A & Y", 2014-2015: "2014-2015"} but in frontend gives an error, how could i fix this! can someone know this error, thanks and advanced

Mvc-Ajax: Submit button not working, display returned result in existing html table

I have the controller below with the Methods. One takes a parameter and the other does not.
I want to be able to do a search.
When I click on submit button. Nothing happens. My ajax call is not hit.
If question 1 is solved, I want to be able to type in my search criteria and have it
return data in the existing table used in my index view.
Please assist. New to Ajax and mvc.
public class HomeController : Controller
{
public ActionResult Index()
{
//List<Product> myProductList = GetAllProducts();
//return View(myProductList);
//List<Product> myProductList = GetAllProducts();
return View();
}
public ActionResult About()
{
return View();
}
public List<Product> GetAllProducts()
{
string myConnect = ConfigurationManager.ConnectionStrings["ConnectSir"].ConnectionString;
List<Product> prdResults = new List<Product>();
SqlConnection con = new SqlConnection(myConnect);
SqlCommand cmd = new SqlCommand("select * from products",con);
using (con)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Product newProduct = new Product();
newProduct.Id = Convert.ToInt16(reader["Id"]);
newProduct.Name = reader["Name"].ToString();
newProduct.Description = reader["description"].ToString();
newProduct.Price = Convert.ToDecimal(reader["Price"]);
newProduct.UnitsInStock = Convert.ToInt16(reader["UnitsInStock"]);
prdResults.Add(newProduct);
}
}
return prdResults;
}
[HttpPost]
public JsonResult GetAllProducts(string searchName)
{
string myConnect = ConfigurationManager.ConnectionStrings["ConnectSir"].ConnectionString;
List<Product> prdResults = new List<Product>();
string sqlcmd = #"select * from products where name = #name";
SqlConnection con = new SqlConnection(myConnect);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = sqlcmd;
cmd.Parameters.Add("#name", SqlDbType.NVarChar);
cmd.Parameters["#name"].Value = searchName;
cmd.Parameters["#name"].Direction = ParameterDirection.Input;
using (con)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Product newProduct = new Product();
newProduct.Id = Convert.ToInt16(reader["Id"]);
newProduct.Name = reader["Name"].ToString();
newProduct.Description = reader["description"].ToString();
newProduct.Price = Convert.ToDecimal(reader["Price"]);
newProduct.UnitsInStock = Convert.ToInt16(reader["UnitsInStock"]);
prdResults.Add(newProduct);
}
}
//return prdResults;
return Json(prdResults);
}
}
*********************************
Html
#model IEnumerable<MvcAjax.Models.Product>
<script src="../../Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<form>
<div>
<input type="text" name="search" id="searchItem" />
<input type="submit" value="Retrieve" id="btnSearch"/>
</div>
<div>
</div>
<table id="items">
<tr>
<th></th>
<th>
Name
</th>
<th>
Description
</th>
<th>
Price
</th>
<th>
UnitsInStock
</th>
</tr>
</table>
<script type="text/javascript">
$('#btnSearch').click(function () {
$.ajax({
url: 'Home/GetAllProducts/',
type: 'POST',
dataType: 'json',
data: { searchName: $('#searchItem').val() }
}).done(function (data) {
if (data && data.length) {
for (var i = 0; i < data.length; i++) {
var newTR = '<tr>';
//create your TR, such as
newTR += '<td>' + data[i].Name + '</td>';
newTR += '<td>' + data[i].Description + '</td>';
newTR += '<td>' + data[i].Price + '</td>';
newTR += '<td>' + data[i].UnitsInStock + '</td>';
//and so on...
newTR += '</tr>';
$('#items > tr:last').append(newTR);
}
}
});
});
</script>
</form>
Send ajax with data and change content type to application/json; charset=utf-8", like this:
$('#btnSearch').click(function () {
$.ajax({
data: '{searchName:' + $('#searchItem').val() + '}'
url: 'Home/GetAllProducts/',
contentType: 'application/json; charset=utf-8"',
type: 'Get',
dataType: 'html'
})
});
Change
data: { Name: mysearchName }
in your ajax call to
data: { searchName: mysearchName }
as your action method is accepting searchName
[HttpPost]
public JsonResult GetAllProducts(string searchName)
{...
}
Let's focus on your first question. Your action is probably not being called because you're using a non-default route. Also, having actions with the same name and verb is not a good practice.
So, let's change your action signature to:
[HttpPost]
public JsonResult GetAllProducts(string searchName)
HttpPost to change the verb, and JsonResult because we want to use your data with javascript, and that's the best approach.
Final change to your action, let's modify the return statement:
return Json(prdResults);
On your view, we must modify the ajax call:
$('#btnSearch').click(function () {
$.ajax({
url: 'Home/GetAllProducts/',
contentType: 'application/html; charset-ut',
type: 'POST',
dataType: 'json',
data: { searchName: $('#searchItem').val()}
});
});
As soon as we get this working, I'll move to the next question.
Now, the 2nd part. We'll add the lines using javascript.
First of all, let's give an id to your table. Let's call it items
<table id="items">
Let's add a handler to your ajax promise:
$('#btnSearch').click(function () {
$.ajax({
url: 'Home/GetAllProducts/',
type: 'POST',
dataType: 'json',
data: { searchName: $('#searchItem').val()}
}).done(function(data){
if(data && data.length){
for(var i = 0; i < data.length; i++){
var newTR = '<tr>';
//create your TR, such as
newTR += '<td>' + data[i].Name + '</td>';
//and so on...
newTR += '</tr>';
$('#items > tr:last').append(newTR);
}
}
});
});
And that's it
For debugging puporses, let's replace the code within done(data){...} with this:
if (data && data.length) {
for (var i = 0; i < data.length; i++) {
var newTR = '<tr>';
//create your TR, such as
newTR += '<td>' + data[i].Name + '</td>';
newTR += '<td>' + data[i].Description + '</td>';
newTR += '<td>' + data[i].Price + '</td>';
newTR += '<td>' + data[i].UnitsInStock + '</td>';
//and so on...
newTR += '</tr>';
alert(newTR);
$('#items > tr:last').append(newTR);
}
}
else{
alert('empty response. Please set a breakpoint at the action and make sure that something is returning');
}

$ajax is being send but is missing a value

Ok, so my script tries to request from php results from mysql and load them into a div. The results are based on nid value which is has to send this value is extracted from id="record-#" the record- is removed and the # is left to be used by ajax as id for the nid.
here is the ajax data function
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "_class/view.php",
data: "ajax=1&nid=" + parent.attr('id'),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {$("#note_utm_nt").html(errorThrown);}
});
});
$("#note_utm_con_cls").click(function() {
$("#note_utm_con").hide();
});
});
and here is the rest of the page
<div id="note_utm_con" style="display: none;">
<button id="note_utm_con_cls" style="width: 20px;float: right; padding: 2px;clear: both;">X</button>
<div id="note_utm"></div>
<div id="note_utm_nt"></div>
</div>
<?php
class notes {
var $host;
var $username;
var $password;
var $table;
public function display_notes() {
$q = "SELECT * FROM `notice` ORDER BY nid ASC LIMIT 12";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
if($type == 1) {
$type = "posted a comment."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/megaphone.png";
} elseif($type == 2) {
$type = "raised a support ticket."; $icon = "http://cdn1.iconfinder.com/data/icons/basicset/help_16.png";
} elseif($type == 3) {
$type = "added new photo."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/photo.png";
} elseif($type == 4) {
$type = "updated profile details."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/user_info.png";
} else { }
$entry_display .= <<<ENTRY_DISPLAY
<ul class="list">
<li id="$nid">
<a href="javascript:;" id="$nid" onClick="retun false;" class="note">
<img src="$icon" />
$author,
$type
</a>
</li>
</ul>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<ul class="list">
<li>
<p>
<img src="http://cdn1.iconfinder.com/data/icons/basicset/monitor_16.png" />
Nothing to display
</p>
</li>
</ul>
ENTRY_DISPLAY;
}
return $entry_display;
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this;
}
private function note_type() {
if($type == 1) { $type = "posted a comment!"; } elseif($type == 2) { $type = "raised a support ticket!"; } else { }
return $type;
}
}
?>
so when a LI with a class="note" is clicked it triggers AJAX call. The call then uses the ID in the href to extract the $nid from the id="record-
In my case it seems as AJAX is sending the request since view.php returns the fields where the data should be but it does not seem to pass much needed nid so PHP is uable to select proper nid from MySQL to use.
Can some one tell me whats wrong with it and how it can be fixed to get the id?enter code here
Your quotation marks are wrong. Try this:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),
Edit: Unless you haven't posted the full code still, you don't actually set parent anywhere. This means that you will use the window.parent object, which surprisingly enough doesn't have an id. You should use this.parentNode.id instead:
data: "ajax=1&nid=" + this.parentNode.id,
From what you've written it looks as if you're passing the parent.attr("id") replace call as a string rather than extracting the variable:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),

Resources