How to visualize a codeigniter array from a query on my view? - javascript

On my model I have the following function which is a query to inner join 3 tables
function get_all_listaproveedorfamilia($clave)
{
$this->db->select('proveedor.razonSocial, proveedor.nombre1, proveedor.telefonoFijo1, proveedor.telefonoMovil1, proveedor.correoElectronico1, proveedor.tipo, familia.clave');
$this->db->from('proveedor');
$this->db->join('relacionproveedorfamilia', 'relacionproveedorfamilia.idProveedor = proveedor.id', 'inner');
$this->db->join('familia', 'familia.id = relacionproveedorfamilia.idFamilia', 'inner');
$this->db->where('familia.clave', $clave);
$this->db->order_by('proveedor.razonSocial');
$query = $this->db->get();
if($query->num_rows() > 0){
return $query->result_array();
}
}
The $clave value is a string retrieved from a select dropdown, and I send it to my controller using ajax
Jquery function in my view to send $clave value
$('#idFamilia').change(function(){
var clave = $("#idFamilia option:selected").text();
if (clave != "Seleccione"){
$.ajax({
url: '<?php echo base_url(); ?>index.php/Proveedor/obtenerListaProveedorFamilia',
method: 'POST',
data: {
clave: clave
}
});
}
});
Here is the code from my controller, where I use the clave value and call the function in my controller
function obtenerListaProveedorFamilia(){
$this->load->model('Proveedormodel');
$clave = $_POST['clave'];
$data['listaproveedorfamilia'] = $this->Proveedormodel->get_all_listaproveedorfamilia($clave);
$data['_view'] = 'proveedor/index';
$this->load->view('layouts/main',$data);
}
I want to visualize the array returned by the function to check if the query is working and getting the values i want to retrieve. I have already tried the following methods to visualize the array adding addtional code to my jquery function $('#idFamilia').change(function(){});
-Get the array from the view and check it on the browser's console
var test = <?php echo json_encode($listaproveedorfamilia); ?>;
console.log(test);
-Trying to append print_r to a pre tag
$('#prueba').append('<?php print_r($listaproveedorfamilia) ?>');
With both options I get the following PHP error on my view
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: listaproveedorfamilia
Filename: proveedor/index.php
This error appears as soon as the page loads, but it should wait for the user to select an option from the select dropdown and then use that option to build the query. How can I fix this and check the content of my array?

You need to add the success method to your ajax call. This is where the data created at the server will be sent.
$('#idFamilia').change(function () {
var clave = $("#idFamilia option:selected").text();
if (clave != "Seleccione") {
$.ajax({
url: '<?php echo base_url(); ?>index.php/Proveedor/obtenerListaProveedorFamilia',
method: 'POST',
data: {
clave: clave
},
success: function (returned) {
console.log(returned);
}
});
}
});
You can use your browser's web dev tool to see what the javascript console has logged.
Because we don't know what the view file contains it's hard to comment on what to expect.
Typically ajax calls are used to return html that return is put into the DOM using $("some_selector").html() or a variety of other DOM manipulation methods to update the current browser screen.
Another way to "visualize" the return would be to simply append it to what is already on the screen. This is not likely what you'll eventually want. But you'll be able to see what came back.
Change the success function to this
success: function (returned) {
$('body').append(returned);
}

Related

How to bring a json result into PHP

I have some results from a fetch.php using json and I successfully brought all results to my bootstrap modal HTML screen.
When the Modal is being shown, I would like to run a MYSQL query using a value coming from the same json I used for the modal, however I can't put this value into a PHP variable to run the SQL query.
How can I get this?
I am trying to bring the same value I input into the HTML textbox (modal), but it is not working. I also tried to use the value from json '$('#PCR').val(data.PCRNo);)', but nothing happen.
This is the script to collect information from database using fetch.php file:
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
</script>
This is the PHP code
<?php
//trying to get the value I have included on #PCR (textbox) which has ID='PCR' and name ='PCR' **
$PCR= $_POST['PCR'];
//running now the code to check if the database has the value and return the desired response to be shown **
$sql1 = mysqli_query($dbConnected,"SELECT * FROM change_management.tPCN");
while ($row1 = mysqli_fetch_array($sql1)) {
if ($row1['PCRNo']==$PCR){
echo $row1['PCNNo'];
echo "<br/>";
}else{
}
}
?>
I would like include value from this val(data.PCRNo) json return into the $PCR variable, so the MYSQL query is going to work
There are a number of quite basic logical issues with your code which are preventing it from working.
1) data: { pcr_number: pcr_number}- the name pcr_number doesn't match the value PCR which the server is searching for using $_POST['PCR'];. The names must match up. When making an AJAX request, the name you gave to the form field in the HTML does not matter (unless you use .serialize()) because you are specifying new names in the data parameter.
2) Your SQL query doesn't make sense. You seem to be wanting to read a single row relating to a PCR number, yet your query makes no usage of the input PCR value to try and restrict the results to that row. You need to use a SQL WHERE clause to get it to select only the row with that ID, otherwise you'll fetch all the rows and won't know which one is correct. (Fetching them all and then using an if in a PHP loop to check the correct one is very inefficient.) I wrote you a version which uses the WHERE clause properly, and passes the PCR value to the query securely using prepared statements and parameters (to project against SQL injection attacks).
3) Your output from the PHP also makes no sense. You've told jQuery (via dataType: "json" to expect a JSON response, and then your code inside the "success" function is based on the assumption you'll receive a single object containing all the fields from the table. But echo $row1['PCNNo']; echo "<br/>"; only outputs one field, and it outputs it with HTML next to it. This is not JSON, it's not even close to being JSON. You need to output the whole row, and then use json_encode() function to turn the object into a JSON string which jQuery can parse when it receives it.
Here's a version of the code containing all the above changes:
JavaScript:
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
$.ajax({
url: 'fetch.php',
method: 'post',
data: { pcr: $(this).attr('id'); },
dataType: "json",
success: function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
PHP:
<?php
$PCR = $_POST['pcr'];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt->bind_param('s', $PCR);
$stmt->execute();
$result = $stmt->get_result();
//an "if" here will cause a single row to be read
if ($row = $result->fetch_assoc()) {
$output = $row;
}
else
{
$output = new StdClass();
}
$stmt->free_result();
$stmt->close();
//output the result
echo json_encode($output);
?>
N.B. I would potentially suggest studying some tutorials on this kind of subject, since this is a fairly standard use case for AJAX/JSON, and you should be able to find samples which would improve your understanding of all the different parts.
P.S. Currently the PHP code above will return an empty object if there is no matching row in the database. However, this is probably an error condition (and will cause your JavaScript code to crash due to trying to read nonexistent properties), so you should consider how you want to handle such an error and what response to return (e.g. 400, or 404, and a suitable message).
You need to first return json from php by using json_encode.
Inside this loop
while ($row1 = mysqli_fetch_array($sql1)) {
$data = array('PCRNo' => 'itsvalue', 'PCC' => 'itsvalue', 'Creation_Date' => 'itsvalue')
}
print json_encode($data)
store all the data in an associative array and then convert it into json using json_encode and return the json.
Use json data in you ajax file
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
var data = JSON.parse(data);
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
Below is the changed script to store different values in $PCR variable
<script>
$(document).ready(function(){
var i = 1;
$('#table').on('click', '.fetch_data', function(){
if(i == 1) {
var pcr_number = $(this).attr('id');
} else {
var pcr_number = $('#PCR').val();
}
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
i++;
}
});
});
});
</script>

load() function won't allow scripts on page to execute

I have a php script which has a select box which allows user to filter some data.And I have used change event on select box to trigger jquery's load function to load a div of another page which will show that filtered data.Now the problem is I have a javascript function which is being called from that page upon some check in php , and this is resulting in that javascript function not getting called at all.Is there any work around in this scenario?I tried using $.get() but I'm not sure if it will allow me to load only part of page.
This is the load() function's call
$('document').ready(function() {
$('#topic-filter-select').on('change' , function(e) {
$.ajax({
type: 'GET',
url: templateUrl+"/ajax/custom_ajax_functions.php",
data : {
functionName : 'load_topic_filter',
topic_id : e.target.value
},
success: function(result) {
for(var i=0;i<result.length;i++)
result[i] = parseInt(result[i]);
result = JSON.stringify(result);
$('#activity-container').empty();
$('#activity-container').load("/topic-filter-template?result="+result+" #topic-page");
},
error: function(error) {
$('#post-0').empty();
$('#post-0').append("<div id='filtered-activities'><h4>Something went wrong , please try again.</h4></div>");
}
});
});
});
And the php check which gives call to javascript function is
<?php $result = has_user_voted($poll_id , $current_user_id);?>
<?php if($result[0] == true) :?>
<?php echo '<script type="text/javascript">animatePollEffect('.json_encode($result).','.$poll->ID.')</script>';?>
<?php endif; ?>
there your question and code snippet creating a lots of confusion. Please, correct it properly to understand what you want exactly.

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

Codeigniter: How to pass array from controller to view without refresh

Basically I have a form in the view with one input enabled, and multiple inputs disabled (only to show information derivated from the unique input).
Now, I need to send this input to the controller to make a query, and send back to the view an array with the fields information but without refresh the site (because I cant loose the progress that I have in this page).
Maybe the solution is to use javascript to send the controller the input field, and in the function return the array of values to refresh the form, but how?
EDIT: Sorry for my bad english.
var input = $('#input').val();
$.ajax({
type:"POST",
url: <?php echo base_url().'controllername/action'?>
data: {input : input},
success: function(data){
// this data should be contain an arra
$('#where_to_insert_array').html();
}
});
In controller action and in action
function action()
{
$data = $this->input->post('input');
get data from database on $data
make its array and then echo it
echo array();
}
Finally I understand how to pass the array from the controller to the view dynamically, this is the code:
The view javascript:
function getClient(){
if($('#cedula_cliente').val()){
$.ajax({
type : "post",
url: "<?php echo base_url().'index.php/clientes/getClienteFactura'?>",
cache: false,
data : {cedula : $('#cedula_cliente').val()},
success : function(json){
var obj=jQuery.parseJSON(json);
if(obj[0]){
$('#nombre_cliente').val(obj[0].nombre);
$('#apellido1_cliente').val(obj[0].apellido1);
$('#apellido2_cliente').val(obj[0].apellido2);
$('#dir_cliente').val(obj[0].dir);
}else{
alert("Usuario no encontrado");
}
},
});
}else{
alert("Debe ingresar una cédula de usuario");
}
}
Im using obj[0] because "cedula" is the primary key and It never will return more than 1 row.
And this is the controller function:
public function getClienteFactura(){
$cedula = $this->input->post('cedula');
$query = $this->Client_model->getClientByCedula($cedula);
echo json_encode($query);
}
Thanks for the answers, maybe I should have looked better on google, the key to solve the problem was Json.

AJAX call working on local server but not online

When a user goes to one of the pages (let's call it page1), the PHP loads the HTML content for an array containing data about the users.
Once the page is loaded (DOM ready), I use jQuery to perform an AJAX call to retrieve the HTML for that array of data. I do this to get the benefit of using separate PHP template files. In this way, PHP will call the PHP template for every array in the bi-dimensionnal array and return the HTML.
page1.php:
<script type="text/javascript">
var globalArray = <?php echo json_encode($freres); ?>;
jQuery(function($) {
liste(); // Ajax call to get HTML for the data in "globalArray"
});
</script>
AJAX call:
function liste() {
$.ajax({
data : {
array : globalArray,
dataName : 'someName',
file : 'templates/t_item_file'
},
dataType : 'html',
success : function(data, textStatus, jqXHR) {
var table = $('table');
var rows = $('<table>' + data + '</table>').find('tr');
rows.each(function(i, e) { // insert with fade-in animations
var row = $(e);
row.hide();
table.append(row);
row.delay(i * 15).fadeIn(250);
});
},
type : 'GET',
url : config.site + 'ajax/view' // configured in header
});
}
Somewhere in t_header.php:
<script type="text/javascript">
var config = {
base : "<?php echo base_url(); ?>",
site : "<?php echo site_url(); ?>"
};
</script>
The config route that redirects to ajax/view/...
$route['ajax/(:any)'] = 'c_ajax/$1';
The method of the controller c_ajax that handles the AJAX call:
public function view() {
$file = $this->input->get('file');
$array = $this->input->get('array');
$dataName = $this->input->get('dataName');
foreach ($array as $vars) {
$data[$dataName] = $vars;
$this->load->view($file, $data);
}
}
When I do this using EasyPHP on localhost, everything works fine, and I receive the HTML as expected, something like :
<TR>
<TD>...</TD>
//...
</TR>
<TR>
//...
And then I insert it into a table. But, when I try to do it on my website in FireBug, I can see that the AJAX response is not 200, but 302 Moved Temporarily.
Can anyone help me to figure out what to do to get it to work, because I spend almost the last four days learning jQuery and AJAX, and it doesn't work (online only).
Instead of
file : 'templates/t_item_file'
give full path of the controller
eg:"http://www.yourdomain.com/---/templates/t_item_file"
Problem solved. I load the HTML data in PHP and pass it to JavaScript, and then use jQuery to animate DOM Elements.
Previously, I didn't pass HTML but raw data in a PHP array, and then tried to get the HTML for all the elements of thie array via Ajax (HTML for all elements in only one call). I think there was too many parameters in the request and that's probably was caused the error.

Categories