This code submits a form and an ID # to addBand.php. The php inserts the form data into a DB, and then echos an array that houses 2 arrays: 1 is an array of ids, the other is a string to update an HTML select element. I've only included the PHP that generates and echos the arrays.
i keep getting "Uncaught TypeError: Cannot read property 'selectRestults' of undefined" with the following code. what am I doing wrong?
javascript/jquery:
$(function() {
$("#addBandForm").submit(function(event) {
event.preventDefault();
var globalShowID = '&id=' + window.globalShowID;
$.ajax({
url: "womhScripts/addBand.php",
type: "POST",
data: $('#addBandForm').serialize() + globalShowID,
success: function(msg) {
var actArray = msg['actIDArray'];
var bandArray = msg['bandSelectArray'];
var result = bandArray['selectResults'];
window.globalShowID='';
$("#band1").html(result)
},
error:function(errMsg) {
console.log(errMsg);
}
});
});
});
addBand.php
$bandSelectArray = array();
$actIDArray = array();
$bandResults = "";
if (isset($_POST['id']))
{
$ShowID = $_POST['id'];
$actSQL = mysqli_query($link, "SELECT actID FROM Act WHERE showID=".$ShowID."");
while($actRow = mysqli_fetch_array($actSQL))
{
$actIDArray[] = array(
'actID' => $actRow['actID'],
);
}
}
$selectBandSQL = mysqli_query ($link, "SELECT bandID, bandName FROM Band");
while ($row = mysqli_fetch_array($selectBandSQL))
{
$bandID = $row['bandID'];
$bandName2 = $row['bandName'];
$bandResults .= '<option value="'.$bandID.'">'.$bandName2.'</option>';
}
$bandSelectArray['selectResults'] = $bandResults;
$resultArray = array();
$resultArray['actIDArray'] = $actIDArray;
$resultArray['bandSelectArray'] = $bandSelectArray;
echo json_encode($resultArray);
Related
I have a laravel 9 controller method that returns recently inserted ids. The method returns one id at a time.
public function product_images(Request $request)
{
//echo asset('storage/3fb80245e9beb3ce6cbbf68be25a0d0b.jpg');
//http://localhost:8000/storage/uploads/3fb80245e9beb3ce6cbbf68be25a0d0b.jpg
$all_ids = [];
$file = new User_files;
if ($request->file('file')) {
$filePath = $request->file('file');
$fileName = $filePath->getClientOriginalName();
$path = $request->file('file')->storeAs('uploads', $fileName, 'public');
}
$md5Name = md5_file($request->file('file')->getRealPath());
$guessExtension = $request->file('file')->guessExtension();
$file->file_name = $filePath->getClientOriginalName();
$file->file_category = 'user_files';
$file->file_path = $request->file('file')->storeAs('uploads', $md5Name.'.'.$guessExtension, 'public');
$file->user_id = auth()->user()->id;
$file->file_ai_description = 'ai desc';
$file->save();
$lid = $file->id;
array_push($all_ids,$lid);
$csv_ids = implode(', ', $all_ids);
return $csv_ids;
}
The method returns ids like
100
101
Dropzone js
success: function (file, response) {
var arr = [];
var id = JSON.parse(response);
arr.push(id);
var csv = arr.join(", ")
console.log('csv', csv);
},
is there a way i can combine individual ids returned into one comma separated list?.
I have a page with ajax pagination on it, I am currently able to check if the session exists and process accordingly. However, I cannot seem to remove the menu or reload the page properly if the session has expired. Only the menu remains and the login page shows in the small area where the table was.
Controller code
public function index()
{
$conditions = array();
$data = array();
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search(array('limit'=>$this->get_per_page()));
$data['user'] = $this->AccountModel->get_person($this->get_person_id());
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('layout/admins/common/header');
$this->load->view('layout/admins/common/navigation');
$this->load->view('layout/admins/common/title');
$this->load->view('layout/admins/common/errors');
$this->load->view('layout/admins/common/search');
$this->load->view('admins/documents/index',$data);
$this->load->view('layout/admins/common/footer');
}
public function search(){
if($this->input->is_ajax_request()){
if(!$this->logged_in()){
$this->index();
}else{
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('admins/documents/ajax_pagination', $data, false);
}
}
}
My JS Code that is placed in the view
<script>
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (html) {
$('#list').html(html);
$('.loading').fadeOut("slow");
}
});
}
function changeStatus(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/ChangeStatus/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
console.log(result);
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
function deleteDocument(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/Delete/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
</script>
i am assuming $('#list').html(html); code loads the html in the dom. instead of directly sending the html from php you can send a json containing the html as well the login status. like this.
$data = [
'login_status' => 1 // or 0,
'html' => $html // full html your are sending now
];
echo json_encode($data);
then in ajax success.
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (response) {
var data = $.parseJSON(response);
if(data.login_status == 0)
{
window.location.href = 'redirect to login page';
}
if(data.login_status == 1)
{
$('#list').html(data.html);
}
$('.loading').fadeOut("slow");
}
});
}
controller method :
public function search(){
if($this->input->is_ajax_request()){
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$html = $this->load->view('admins/documents/ajax_pagination', $data, true);
$res['html'] = $html;
$res['login_status'] = ($this->logged_in()) ? '1' : '0';
echo json_encode($res);
}
This is my ajax call
function exportCSV(){
var sampleid = $("#sampleid").val();
var scheme = $("#scheme").val();
var v = $("#v").val();
var date = $("#date").val();
var assignedvalue = $("#assignedvalue").val();
var units = $("#units").val();
var assayvalue = $("#assayvalue").val();
var analyte = $("#analyte").val();
var filename=$("#filename").val();
var sample_error=$("#sample_error").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "import/validate_file",
dataType: 'json',
data: {
sampleid: sampleid,
scheme: scheme,
v: v,
date: date,
assignedvalue: assignedvalue,
units: units,
assayvalue: assayvalue,
analyte: analyte,
filename:filename,
sample_error: sample_error
},
success: function (data) {
console.log(data); //as a debugging message.
}
});
}
and this is my controller
<?php
if (!empty($unit_check) and !empty($analyt) and !empty($sch) and count($sample_id) == count(array_unique($sample_id)) and $assigned_check == '1' and $assay_check == '1') {
for ($row = 2; $row <= $lastRow; $row++) {
$data['sample_id'] = $worksheet->getCell($sampleid . $row)->getValue();
$data['scheme'] = $worksheet->getCell($scheme . $row)->getValue();
$data['v'] = $worksheet->getCell($v . $row)->getValue();
$data['units'] = $worksheet->getCell($unit . $row)->getValue();
$data['date'] = $worksheet->getCell($date . $row)->getFormattedValue();
$data['assay_value'] = $worksheet->getCell($assayvalue . $row)->getValue();
$data['assigned_value'] = $worksheet->getCell($assignedvalue . $row)->getValue();
$data['analyte'] = $worksheet->getCell($analyte . $row)->getValue();
$data['trace_id'] = $insert_id;
$this->import_model->insert_data($data);
$response['success'] = true;
}
} else {
$data['sample_id'] = '';
$data['analyte'] = '';
$data['unit_check'] = '';
$data['sch'] = '';
$data['assigned_value'] = '';
$data['assay_value'] = '';
if (count($sample_id) != count(array_unique($sample_id))) {
$data['sample_id'] = '1';
}
if (empty($analyt)) {
$data['analyte'] = '1';
}
if (empty($unit_check)) {
$data['unit_check'] = '1';
}
if (empty($sch)) {
$data['sch'] = '1';
}
if ($assigned_check == '') {
$data['assigned_value'] = '1';
}
if ($assay_check == '') {
$data['assay_value'] = '1';
}
$data['file_name'] = '';
}
?>
I have to show the errors and success message on ajax call.
Right now I'm succeeded in valuating the data and putting it in the database.
But I want to show the success message at the end of the page by clicking the submit button.
And if there is validations error it must shows the errors in that fields at the end of the page
Any help would be appreciated.
Here inside your success method of ajax
success: function (data) {
$("#resultDiv").html(data)
}
Return some real data from your controller in both case success and failed. and based on your data inside success method show your message.
Like:
success: function (data) {
$("#resultDiv").html(data.success) //this requires string to convert your result in string if neccessary
//But you should return a JSON data as msg from your controller
}
You should put a result HTML element for example:
<div id='resultDiv'></div> <!-- to match with #resultDiv -->
Put response data in both condition if success=true and else success=false
In your controller
if(.....){
//what ever check you wanna do
..........
..........
$response['msg']='success';
header('Content-Type', 'application/json');
echo json_encode($response);
}
else{
$response['msg']='failed';
header('Content-Type', 'application/json');
echo json_encode($response);
}
In your ajax
success: function (data) {
$("#resultDiv").html(data.msg)
}
Try something like:
$response = array(
'errCode' = 0,
'errMsg' = 'msg'
);
return this kind of array by json_encode() from php to ajax() call and use it in ajax() success like:
var data = JSON.parse(response);
alert(data.errMsg);
You can also put a check on errCode like:
if(errCode == 0) { something }
if(errCode == 1) { something }
Can you please take a look at This Demo and let me know why I am getting empty array?
I have a jquery ajac request as:
$( "#appinfo" ).on( "submit", function( e ) {
var eTraget = $(".opacity").html().replace(/\D/g,'');
var senario = current;
if(qtype =="econo"){
var col = senario +"_"+eTraget;
var data='column='+col;
$.ajax({
type:"POST",
url:"assets/econo.php",
data:data,
dataType : 'json',
success:function(html) {
coords = html;
console.log(data);
st = map.set();
for (var i = 0; i < coords.length; i++) {
var circle = map.circle(coords[i][0], coords[i][1], 6);
st.push(circle);
}
e.preventDefault();
});
and econo.php as:
<?PHP
include 'conconfig.php';
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$collm = $_POST['column'];
$query = "SELECT x, y FROM econo WHERE".$collm."=1";
$results = $con->query($query);
$return = array();
if($results) {
while($row = $results->fetch_assoc()) {
$return[] = array((float)$row['x'],(float)$row['y']);
}
}
$con->close();
echo json_encode($return);
?>
As you can see I console.log(data); and the console display the result like column=ce_3000 but the $collm = $_POST['column']; is empty because whrn tried to dump it I just got an empty []. Can you please let me know why this is happening?
I want a user to input a country, then it will output its population. My javascript is suppose to look up the country that the user input when the button is clicked, then goes through the PHP file and gets the country's population.
my HTML is:
<label>
Country:
<input name="country" type="text" id="country"></label>
<input type="button" value="Find population" id="findPop">
<p id="output"></p
and javascript:
var countryFound = function(data) {
var theCountry = $("#country").val();
var population = data["country"];
if (data["country"])
{
$("#output").html(theCountry + " population is " + population);
}
else {
$("#output").html(theCountry + " is not found");
}
};
$("#findPop").click(function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.getJSON("countrylookup.php", "country="+theCountry , countryFound);
});
my PHP code is:
if (isset($_GET['country'])) { // get the parameters country
$column = 'country';
$value = $_GET['country'];
else {
print -1; // an error code
return;
}
$data = array( 'country'=>'Peru', 'capital'=>'Lima', 'area'=>'1285220', 'population'=>'29907003', 'continent'=>'South America' ),
array( 'country'=>'Philippines', 'capital'=>'Manila', 'area'=>'300000', 'population'=>'99900177', 'continent'=>'Asia' );
function findData ( $whichColumn, $data, $searchValue)
{
$result = array();
foreach ($data as $row) {
if ($row[$whichColumn] == $searchValue)
$result[] = $row;
}
return $result;
}
print json_encode ( findData($column, $data, $value) );
but for some reason, when I input Peru as the country, it says Peru is not found. Am I not retrieving the correct data from the php or what? I'm pretty sure that my php code is correct.
Here's how I'd do it :
$(function() {
$("#findPop").on('click', function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.getJSON("countrylookup.php", {country: theCountry}, function(data) {
var population = data[0] != "false" ? data.population : false,
msg = population ? (" population is " + population) : " is not found";
$("#output").html(theCountry + msg);
});
});
});
PHP
$value = isset($_GET['country']) ? strtolower(trim($_GET['country'])) : false;
$result = false;
if ($value) {
$data = array(
'peru' => array(
'capital'=>'Lima',
'area'=>'1285220',
'population'=>'29907003',
'continent'=>
'South America'
),
'philippines' => array(
'capital'=>'Manila',
'area'=>'300000',
'population'=>'99900177',
'continent'=>'Asia'
)
);
if (array_key_exists($value, $data)) $result = $data[$value];
}
echo json_encode($result);
For the jQuery side, I recommend using the .get() function.
$("#findPop").click(function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.get("countrylookup.php", function(data) {
if(data) {
// Do whatever you want to do with the data, e.g.:
var population = data.population,
theCountry = $("#country").val();
// Do more magic
$("#output").html(theCountry = " population is " + population)
} else {
// Error handling
}
});
});
There is a } missing before the else in the fourth line of the PHP code.