I have an Ajax Request that is getting data from my database, specifically two columns from it, company_id and people_id,
I need to test the result that comes from the json result, I need to check if a specific people_id exists in the result,
Here is my Ajax Request
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'CompanyPeople',
method: 'secget',
data: Ext.encode({
people_id: Ext.getCmp('peopleGrid').selectedRecord.data.people_id
})
},
success: function (response) {
},
failure: function () {
}
});
I thought I could do this following code in the success function but it didnt work
if (data == 0) {
Ext.MessageBox.alert('Status', 'Person is not attached to anything bud!.');
}
else {
Ext.MessageBox.alert('Status', 'Person already attached to another company.');
}
Also here is my php
class CompanyPeople extends Connect {
function __construct() {
parent::__construct();
}
public function secget($vars) {
$sql = "SELECT * FROM CompanyPeople where people_id={$vars->data->people_id}";
$data = array();
$total = 0;
if ($result = $vars->db->query($sql)) {
while ($row = $result->fetch_assoc()) {
$data[] = array("people_id" => intval($row["people_id"]));
$total++;
}
$result->free();
}
echo json_encode(array("success" => true, "total" => $total, "topics" => $data));
}
}
I think something like this should work:
success: function( response ){
if(response.success === true) {
var personExist = false;
for(var i = 0; i < response.topics.lenght; ++i) {
// Your specific people_id in myValue
if(response.topics[i]['people_id'] === myValue) {
personExist = true;
break;
}
}
}
},
Related
I am new to ionic and I am trying to understand an app that has basic http query to communicate with the database, but I am facing a problem.
There is a page that show a list which has been taken from the database. There are two operations that can be performed on this list - insert and update. The problem occurres when I try to make an update. The record in the database is updated but not the list in the application is not. However, when I insert a new record the list got updated with the new record including all previous changes, that were not shown in the list.
Here is the type script for the list page:
export class CrudHttpListPage {
items: any;
constructor(public loading: LoadingProvider, private toast: ToastProvider, public modal: ModalController, private crud: CrudHttpProvider) { }
ionViewDidLoad() {
this.load();
}
load() {
this.loading.present();
this.crud.read.then(res => {
this.items = res;
if (res) this.loading.dismiss();
});
}
add() {
let modal = this.modal.create('CrudHttpDetailPage', { action: 1 });
modal.present();
modal.onDidDismiss(data => {
console.log(data);
if (data) this.load();
});
}
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
if (data) this.load();
});
}
Here is the typescript code for the add and edit page:
export class CrudHttpDetailPage {
private form: FormGroup;
action: number;
data: any = { title: '', text: '' };
constructor(private view: ViewController, private toast: ToastProvider, private loading: LoadingProvider, private crud: CrudHttpProvider, private fb: FormBuilder, public params: NavParams) {
this.action = params.data.action;
this.data = params.data && params.data.data || this.data;
console.log(params.data);
this.form = this.fb.group({
id: [this.data && this.data.id],
title: [this.data && this.data.title, Validators.required],
text: [this.data && this.data.text, Validators.required]
});
}
submit() {
this.loading.present();
console.log(this.form.value);
this.crud.save(this.form.value).then(data => {
// this.dataNotes.id = data;
console.log(data);
this.loading.dismiss();
this.view.dismiss(this.form.value);
}, err => {
console.log(err);
this.loading.dismiss();
this.toast.showWithClose(err);
this.close();
});
}
close() {
this.view.dismiss();
}
}
Here are the http operations:
const SERVER_URL: any = {
getNormal: ConstantVariable.APIURL + 'index.php/tbl_note',
getLimit: ConstantVariable.APIURL + 'limit.php',
};
#Injectable()
export class CrudHttpProvider {
limitData: number = 10;
datas: any = [];
constructor(public http: Http) {
this.datas = null;
}
get read() {
return new Promise(resolve => {
this.http.get(SERVER_URL.getNormal).map(res => res.json()).subscribe(data => {
console.log(data.dataNotes);
resolve(data.dataNotes);
});
});
}
save(item) {
let headers: any = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }),
options: any = new RequestOptions({ headers: headers });
if (item.id) {
return new Promise((resolve, reject) => {
this.http.post(SERVER_URL.getNormal + '/' + item.id, item, options).map(res => res.json()).subscribe((data) => {
console.log(data);
resolve(data.dataNotes);
}, (err) => {
reject(err);
console.log("error: " + err);
});
});
}
else {
return new Promise(resolve => {
this.http.post(SERVER_URL.getNormal, item, options)
.map(res => res.json())
.subscribe(data => {
// console.log(data);
resolve(data.dataNotes[0].id);
}, error => {
console.log("error " + error);
});
});
}
}
and last here is the PHP file:
<?php
header('Access-Control-Allow-Origin: *');
require_once('config.php');
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;
// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
if ($value===null) return null;
return mysqli_real_escape_string($link,(string)$value);
},array_values($input));
// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
$set.=($i>0?',':'').'`'.$columns[$i].'`=';
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
// create SQL based on HTTP method
if ($method == "POST" AND $key != "") { $method = 'PUT'; }
if ($method == "GET" AND $key != "") { $method = 'DELETE'; }
switch ($method) {
case 'GET':
$sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
case 'PUT':
$sql = "update `$table` set $set where id=$key"; break;
case 'POST':
$sql = "insert into `$table` set $set"; break;
case 'DELETE':
$sql = "delete from `$table` where id=$key"; break;
}
// excecute SQL statement
$result = mysqli_query($link,$sql);
// die if SQL statement failed
if (!$result) {
http_response_code(404);
die(mysqli_error());
}
// print results, insert id or affected row count
echo "{\"status\":\"ok\", \"dataNotes\":";
if ($method == 'GET') {
if (!$key) echo '[';
for ($i=0;$i<mysqli_num_rows($result);$i++) {
echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
}
if (!$key) echo ']';
} elseif ($method == 'POST') {
$set = '"id":"'.mysqli_insert_id($link).'"';
for ($i=1;$i<count($columns);$i++) {
$set.=($i>0?',':'').'"'.$columns[$i].'":';
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
echo "[{".$set."}]";
} elseif ($method == 'DELETE') {
echo '[{"id":"'.$key.'"}]';
} else {
echo mysqli_affected_rows($link);
}
echo "}";
// close mysql connection
mysqli_close($link);
The issue might be here:
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
if (data) this.load(); // <---- seems this.load() is not executing
});
}
Seems this.load() is not executing after modal.onDidDismiss:
- check modal is dismissing
- check if data is not null/undefined
- check running this.load(), with no if() statement, does it run?
you may be able to find the answer there
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
console.log('Modal has dismissed!!');
// if (data) this.load(); // comment for check
this.load();
});
}
i finally solved the problem. what cause the issue is that i have two files to make a connection to the database one for the website and the other is for the mobile application and it seems the one which i use in the mobile application is broken so i remove this file and connect to the old file and the problem solved
How to display name one by one using ajax. It seem that my FOR looping is not working to push name one by one. Is there any step that i miss? Can someone point me to where/what i did wrong.
var names = [];
var profiles = {};
var restURL = "fetch.php";
function refresh() {
$.ajax({
method: 'GET',
url:restURL,
success: function (result, status, xhr) {
for (var k in result) {
var name = result[k].name;
if (!profiles.hasOwnProperty(name)) {
names.push(name);
profiles[name] = result[k];
}
}
}
});
}
var namei = -1;
function nextName() {
namei++;
if (namei > names.length - 1) {
namei = Math.max(1, names.length - 10) - 1;
}
console.log(namei + '/' + names.length);
$('.texts li:first', '.jumbotron #atname').text(profiles[names[namei]].name);
$('.texts li:first', '.jumbotron #atdiv').text(profiles[names[namei]].division);
$('.jumbotron .tlt').textillate('start');
setTimeout(function () {
$('.jumbotron .tlt').textillate('out');
}, 5000);
}
fecth.php
$i=1;
while ( $row = mysql_fetch_assoc($rs) ) {
$response['result'][] = array(
'staffno' => $row['g_idm'],
'name' => $row['g_name'],
'division' => $row['g_div']
);
$i++;
}
echo json_encode($response);
I'm getting data through ajax who's function is:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
jQuery("div#result").show();
}
},
fail: function(res)
{
console.log(res);
}
});
});
});
The Controller function i have:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
// print_r($_POST);
// die();
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$arr = array(
'id' => $update_id,
'name'=> $update_name);
//This prints empty data
// print_r($arr);
// die();
$result = $this->model_season->edit_season($arr);
// $result = $result->row();
if ($result)
{
print_r($arr);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
And in Model through controller i have:
public function edit_season($data)
{
// I am getting right array of name and id
print_r($data);
die();
// but get empty variable if i try to assign value to it
$name = $data['name'];
$this->db->where('seasons', array('season_id ' => $data['id']));
$query = $this->db->update('seasons',array('names ' => $data['name'] ));
if ($query)
{
return $query;
}
else
{
return FALSE;
}
}
The ajax seem to work fine as its printing the values of id and name its getting i'm not even encoding it in json, but i'm unable to get its value in separate variable. I wonder if there is any different method to get values from ajax data ?
When i let it run the whole model function without making it die i have following error:
UPDATEseasonsSETnames= NULL WHEREseasons=Array``
Like array have nothing in it
There is error in your query, you are supplying array to where condition, where it should be string,
$this->db->where('season_id ', $data['id']);
Also, it is not good to have unnecessary spaces (though CI driver internally trims all spaces) in conditions like 'season_id ' should be 'season_id'
$this->db->where('season_id', $data['id']);
$query = $this->db->update('seasons', array('names' => $data['name']));
Check driver referance here: Queries in CI
$array1= array('season_id ' => $data['id']);
$array2= array('names' => $data['name']);
$this->db->where($array1);
$query = $this->db->update('seasons',$array2);
I need some help with the following code. I am trying to query my database using ajax and return the results within a table. The code is executing and I am not getting any errors - I'm just not getting a response. Any ideas? I have a feeling something is messed up with my jQuery function.
Thanks for any help you can give.
My function in my view:
$("#test").click(function() {
var form_data = {
Opportunity_Id: $('#Opportunity_Id').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('schedule/get_classes'); ?>",
type: 'POST',
data: form_data,
cache: false,
success: function(server_response) {
var data = $.parseJSON(server_response);
for(var i = 0; i < data.length; i++){
week = data[i];
$("table.table").append("<tr><td>" + week.Class_Number + "</td><td>" + week.Class_Date + "</td></tr>");
};
},
error: function(thrownError) {
alert(thrownError);
}
});
return false;
})
My controller:
function get_classes() {
$Opportunity_Id = $this->input->post('Opportunity_Id');
$this->ion_auth_model->get_classes($Opportunity_Id);
foreach ($classes as $class):
$results[] = array(
"Class_Number" => $class->Class_Number,
"Class_Date" => $class->Class_Date,
"Start_Time" => $class->Start_Time,
"End_Time" => $class->End_Time
);
endforeach;
echo json_encode($results);
}
My model:
function get_classes($Opportunity_Id) {
$this->db->select('*')->from('Classes')->where('Opportunity_Id', $Opportunity_Id);
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach($q->result() as $classes) {
$data[] = $classes;
}
return $data;
}
}
I think this maybe your problem, you are returning an array from get_classes($Opportunity_Id) but you have not captured that array when you call it :-
function get_classes() {
$Opportunity_Id = $this->input->post('Opportunity_Id');
$classes = $this->ion_auth_model->get_classes($Opportunity_Id); <--- changed here
foreach ($classes as $class):
$results[] = array(
"Class_Number" => $class->Class_Number,
"Class_Date" => $class->Class_Date,
"Start_Time" => $class->Start_Time,
"End_Time" => $class->End_Time
);
endforeach;
echo json_encode($results);
}
The script below works as far as i can tell:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#add').bind('keypress', function(e) {
if(e.keyCode == 13){
var add = $("#add").val();
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url("home/jsonAddData"); ?>",
data: add,
json: {title_posted: true},
success: function(data){
if(data.title_posted == true) { // true means data was successfully posted.
$("#success").append("Success").fadeIn(400);
} else if(data.title_posted == false) { // false means data failed to post.
$("#success").append('Failure').fadeIn(400);
}
}
});
}
});
});
</script>
The problem I'm experiencing with the code below is that the mysql insetion query just wont work. It creates the row in the table and auto-increments but for some odd reason it wont pass the 'var add' in the Javascript above to the Ci script below and perform an insertion in the db. Any thoughts or ideas?
<?php
class home extends CI_Controller {
function __construct() {
parent::__construct();
}
function index() {
$data = array();
$data['lists'] = $this->displayList();
$this->load->view('home', $data);
}
function displayList() {
$str = '';
$query = $this->db->query("SELECT * FROM data");
foreach ($query->result() as $row) {
$b = '<input name="completed" type="checkbox" />';
$a = $row->title . "<br>";
$str .= $b.$a;
}
return $str;
}
function jsonAddData() {
if($this->input->is_ajax_request()) {
$title = $this->input->post('title');
$query = $this->db->query("INSERT INTO data (title) VALUES ('$title')");
header('Content-type:application/json');
if($query) echo json_encode(array('title_posted' => true));
else echo json_encode(array('title_posted' => false));
}
}
}
?>
In
$.ajax({
...
data: {title: add}
Not just a string