Ajax with Symfony3 - ajax

I want to display a list of users dynamically but it doesn't work. I tested the query by itself and it works just fine yet it still doesn't show anything. This is the script
<script>
function showUser() {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("user-list-div").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","{{ path('ajax_update')}}",true);
xmlhttp.send();
}
</script>
This is the controller action:
public function searchUsersAction(Request $request)
{
/*$em = $this->getDoctrine()->getManager();
$request = $this->get('request');*/
$projectName = $request->get('projectName');
echo($projectName);
//$projectId=$this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findName($projectName);
//echo(count($projectId));
//foreach($projectId as $pId) {
//$projectId->getPId();
$pus = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUsers($projectName);
//}
$response = "<select class=\"select2_multiple form-control\" multiple=\"multiple\">";
foreach($pus as $user){
$response . "<option>" . $user . "</option>";
}
$response = $response."</select> ";
return new Response($response);
//return($pus);
//call repository function
}
and this is the query
public function findProjectUsers($projectName){
$query=$this->getEntityManager()
->createQuery(
"SELECT u.firstName FROM SocialProDefaultBundle:User u, SocialProProjectBundle:Project p, SocialProProjectBundle:ProjectUser pu WHERE u.id = pu.user AND p.id=pu.project AND p.name='$projectName'");
return $query->getResult();
}

Your query is incorrect. You need to concatenate the $projectName like so:
public function findProjectUsers($projectName){
$query=$this->getEntityManager()
->createQuery(
"SELECT u.firstName
FROM SocialProDefaultBundle:User u,
SocialProProjectBundle:Project p,
SocialProProjectBundle:ProjectUser pu
WHERE u.id = pu.user AND p.id=pu.project AND p.name=:name"
)->setParameter('name', $projectName);
return $query->getResult();
}
I'm not sure if that will fix everything, but at least it will get the query working properly.

I am not very clear your problem, but see upstairs friend said there was a problem in your query, so I'm thinking, you can put the controller, the query do breakpoint debugging. Then the error precision lock down position. I the train of thought to solve the problem is so commonly.

Related

How to stay on previous page after signin in codeigniter framework

Hii guys i'm new in stackoverflow , if this question is very long please pardon me, This is a Consumer complain website here is a view page called separate_user_admin_reply2.php in this page i want to apply a functionality, If a user without login click on the replay button then Signin.php view page will appear then after login the user come back to the previous page, the previous page link is : http://localhost/A2Zcomplainboard/index.php/Complain/Separate_single_complain_user/COMP008
So what i can do ..please help me (thanks in advance)
The controller is :
public function Separate_single_complain_user($cid)
{
//$cid = $this->input->get('compid');
$this->load->model('Complain_model');
$res = $this->Complain_model->getSingleComplain($cid);
$this->load->model('Replay_Model');
$res1 = $this->Replay_Model->Separate_single_complain_replay($cid);
if($res){
$this->load->view('separate_user_admin_reply2',['res'=>$res,'res1'=>$res1]);
}
}
The model is:
public function getSingleComplain($cid)
{
$complain = $this->db->query("SELECT comp_id,comp_title,comp_description,post_datetime,status,publish_status,comp_catagory,posted_by,id,first_name,email FROM log_tbl l INNER JOIN comp_tbl c ON l.id = c.posted_by WHERE comp_id = '$cid'");
$res = $complain->result_array();
if($res)
return $res;
else
return false;
}
public function Separate_single_complain_replay($cid){
$rep = $this->db->query("SELECT first_name,rep_id,rep_description,rep_datetime,rep_by,rep_against,rep_flag,rating FROM log_tbl l INNER JOIN reply_tbl r ON l.id = r.rep_by WHERE r.rep_against = '$cid 'AND rep_flag = '1'");
$res = $rep->result_array();
if($res)
return $res;
else
return false;
}
enter image description here
This is the view page image
separate_user_admin_reply2.php
And the signin controller is :
public function index()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->load->model('Login_Model');
$data = $this->Login_Model->isvalidate($email,$password);
if($data)
{
$this->load->library('session');
$this->session->set_userdata('email',$data['email']);
$this->session->set_userdata('type',$data['type']);
$this->session->set_userdata('id',$data['id']);
if($data['type']=='User' ){
return redirect('User/index');
}
else
{
return redirect('Admin/adminDashboard');
}
}else{
echo "<script>alert('Details not matched')</script>";
header("refresh:1");
return redirect('Complain/login');
}
}
model:-
public function isvalidate($email,$password)
{
$q = $this->db->where(['email'=>$email,'password'=>$password])
->get('log_tbl');
if($q->num_rows()){
$x = $q->row()->email;
$y = $q->row()->type;
$z = $q->row()->id;
$userData = array('email' => $x, 'type' => $y, 'id' => $z);
return $userData;
}else{
return false;
}
}
signin view page image:
Store the previous page url in session data. You can find a detailed description of how to do that in the codeigniter documentation. When the user successfully logged in, check if the previous page data is set, if so flush it and redirect to it.

Getting data by ajax in Codeigniter

I am adding record to database by ajax in CI , so i was trying to return the id of the new record but it's not working , the record has been added but no id is returned .(in ajax code am trying to alert the new record id but it's alerting undefined)
Below is the ajax code:
$.ajax({
type:'post',
url: baseURL+"admin/Products/add_product",
data:postData,
success:function(data){
alert(data[0].id);
$('#register_form')[0].reset();
} });
This is the controller,
notice that am returning id from create_product method and put it in get_by_id method, and then return result
if($id=$this->Products_model->create_product($data)){
$result = $this->Products_model->get_product_by_id($id);
return $result;
}
This is my model methods
public function create_product($data){
$query = $this->db->insert('products',$data);
if($query){
$id = $this->db->insert_id();
return $id;
}else{
return false;
}
}
//////////get_by_id_method
public function get_product_by_id($id){
$this->db->where($id,'id');
$query = $this->db->get('products');
if($query){
return $query->result();
}
}
Hope this will help You :
Your ajax should be like this :
$.ajax({
type:'post',
url: baseURL + "admin/Products/add_product",
data:postData,
success:function(data)
{
var response = JSON.parse(data);
alert(response.id);
$('#register_form')[0].reset();
}
});
Your controller should be like this :
$id = $this->Products_model->create_product($data);
if($id)
{
$result = $this->Products_model->get_product_by_id($id);
echo json_encode($result);
exit;
}
Your model method get_product_by_id should be like this :
public function get_product_by_id($id)
{
$this->db->where($id,'id');
$query = $this->db->get('products');
if($query->num_rows() > 0)
{
return $query->row();
}
}
You may need to echo a JSON with a proper Content-type in your Controller:
$result = [];
$id = $this->Products_model->create_product($data);
if ($id) {
$result = $this->Products_model->get_product_by_id($id);
}
header("Content-type: application/json");
echo json_encode($result);
So that the response can be an empty object or the query result.

codeigniter : Commands out of sync; you can't run this command now

I applied all the possible answers but still same problem.
also tried
$this->db->reconnect();
there is no problem in my query
MyCode:
public function GetdistributorsDetails($username){
$sql = "SELECT u.FirstName, u.Email, u.Telephone, u.MobileNumber, u.AlternateMobileNumber, ud.Address1, ud.Pincode,ud.City,s.Statename FROM users u JOIN userdetails ud ON ud.UserId = u.UserId JOIN states s ON s.StateId = ud.StateId WHERE u.Username = ? ";
$result = $this->db->query($sql,array($username));
return $result->result_array();
}
add following code into /system/database/drivers/mysqli/mysqli_result.php
function next_result()
{
if (is_object($this->conn_id))
{
return mysqli_next_result($this->conn_id);
}
}
then in model when you call Stored Procedure
$query = $this->db->query("CALL test()");
$res = $query->result();
//add this two line
$query->next_result();
$query->free_result();
//end of new code
return $res;
you can use this after call
mysqli_next_result( $this->db->conn_id );
Here is example if you don't want change any thing in mysqli drivers files
$sql = "CALL procedureName(IntParam,'VarcharParm1','VaracharParm2','VarcharParm3');";
$query = $this->db->query($sql);
mysqli_next_result( $this->db->conn_id );
$query->free_result();
these are important line place after to remove the error
mysqli_next_result( $this->db->conn_id );
$query->free_result();
Just use this one if you use multiple query make in same function:
$this->db->close();
If your stored procedure returns more than one result, try to add this code between the queries:
$storedProcedure = 'CALL test(inputParam, #outputParam)';
$this->db->query($storedProcedure);
$conn = $this->db->conn_id;
do {
if ($result = mysqli_store_result($conn)) {
mysqli_free_result($result);
}
} while (mysqli_more_results($conn) && mysqli_next_result($conn));
$sql = 'SELECT #outputParam;';
$this->db->query($sql);
Just add next_result function in
system\database\drivers\mysqli\mysqli_result.php file
public function next_result(){
if(is_object($this->conn_id) && mysqli_more_results($this->conn_id)){
return mysqli_next_result($this->conn_id);
}
}
To call query function
$result = $this->db->query("CALL {$Name}({$Q})",$Param);
$result->next_result();
return $result;

Check grocery crud state

I want to check the from the controller if I am rendering an add form or just a view. I want to do something like this..
public function clients()
{
try{
if ($_SERVER["REQUEST_URI"] == "/data/clients")
{
$data['client'] = $this->db->query("select * from clients");
$this->load->view('cview/client',$data);
}
else
{
$crud = new grocery_CRUD();
//$crud->set_theme('datatables');
$crud->set_table('clients');
$crud->set_subject('Clients');
crud->required_fields('city');
//$crud->columns('city','country','phone','addressLine1','postalCode');
$output = $crud->render();
$this->load->view('/crud/users',$output);
}
}catch(Exception $e){
show_error($e->getMessage().' --- '. $e->getTraceAsString());
}
}
This would work well except I'm using an Iframe and this doesn't work if the url doesn't change :P
$state = $this->grocery_crud->getState();
this will get the what state it is in.
if (($state == "list" || $state == "success"))
{
$data['client'] = $this->db->query("select * from clients");
$this->load->view('cview/client',$data);
}
else
{
$crud = new grocery_CRUD();
//$crud->set_theme('datatables');
$crud->set_table('clients');
$crud->set_subject('Clients');
$crud->required_fields('city','phone');
//$crud->columns('city','country','phone','addressLine1','postalCode');
$output = $crud->render();
$this->load->view('/crud/users',$output);
}
In this example above "list" will work on cancel button and "success" works on save and update button on the add screen or edit screen.

How to prevent code duplication for CodeIgniter form validation?

This is sample of function in the Staff controller for this question
function newStaff()
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
function add_newStaff()
{
//when user submit the form, it will call this function
//if form validation false
if ($this->validation->run() == FALSE)
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
else
{
//submit data into DB
}
}
From the function add_newStaff(), i need to load back all the data from database if the form validation return false. This can be troublesome since I need to maintain two copy of codes. Any tips that I can use to prevent this?
Thanks.
Whats preventing you from doing the following
function newStaff()
{
$data = $this->_getData();
$this->load->view('staff/newstaff', $data);
}
function add_newStaff()
{
//when user submit the form, it will call this function
//if form validation false
if ($this->validation->run() == FALSE)
{
$data = $this->_getData();
$this->load->view('staff/newstaff', $data);
}
else
{
//submit data into DB
}
}
private function _getData()
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
return $data;
}
Alternately you change the action your form submits to so that it points to the same service you use for the initial form request with something like the following. This would also mean that you'd have the POST values retained between page-loads if you wanted to retain any of the submitted values in your form.
function newStaff()
{
// validation rules
if ($this->validation->run() == TRUE)
{
//submit data into DB
}
else
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
}

Resources