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.
Related
I posted this question ealier today, however I recieved a fix (thank you) that works great against my RequestBin endpoint for testing, however when submitting to my AJAX script, its a different story.
Problem: I cant submit my jQuery toggle values to my PHP AJAX script because there is no form name associated with the POST request (so db never updates). I proven this by making a HTML form with the field names and the database updated right away. However this is not the case with this JS toggle method.
jQuery code
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: {
value: $this.hasClass("switchOn") ? 'pagination' : 'infinite'
},
success: function(data) {
console.log(data);
}
});
});
});
HTML
<div class="wrapper-toggle" align="center">
<label>
<div class="switch"></div>
<div class="switch-label">Use <b>Paged</b> results instead (Current: <b>Infinite</b>)</div>
</label>
</div>
PHP AJAX script
if (array_key_exists('pagination', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'pagination' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
} else if (array_key_exists('infinite', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'infinite' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I cant figure out how to assign a field name to this, as it is not a traditional post form. This is driving me nuts. So the previous solution was applying hasClass() and calling var $this outside of $ajax(), great (and RequestBin receives both requests), but when submitting to PHP its a dead end (no form names).
Given the code above fixed and revised twice, where do I even start without a form ??
We need:
name="pagination"
name="infinite"
But this toggle JS doesn't allow for this. prop() has been removed to get toggle submitting values over (just not my AJAX script).
Any solution appreciated. Thank you again.
You can set your values as Form Data. So the PHP Function will get it just like a traditional form submission:
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
var formdata = new FormData();
$this.hasClass("switchOn") ? formdata.append('pagination', 'name') : formdata.append('infinite', 'name');
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: formdata,
success: function(data) {
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
More info on JS Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData
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>
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);
}
I have a ajax function that would retrieve data from my database and display it in my textbox. I am using a JQuery Form Plugin to shorten the ajax process a little bit. Now what I want to do is to get the data back from the php script that I called from the ajax function.
The form markup is:
<form action="searchFunction.php" method="post" id="searchForm">
<input type="text" name="searchStudent" id="searchStudent" class="searchTextbox" />
<input type="submit" name="Search" id="Search" value="Search" class="searchButton" />
</form>
Server code in searchFunction.php
$cardid = $_POST['searchStudent'] ;
$cardid = mysql_real_escape_string($cardid);
$sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'") or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($sql);
return $row;
The ajax script that processes the php is
$(document).ready(function() {
$('#searchForm').ajaxForm({
dataType: 'json',
success: processSearch
});
});
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
In PHP, if I want to call the data, I would just simply create a function for the database and just for example echo $row['username'] it. But how do I do this with ajax? I'm fairly new to this so, please explain the process.
$('#Search').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/<SolutionName>/<MethodName>",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: processSearch,
});
});
function processSearch(data) {
var username= ($(data).find('#username'));
}
Change the input type submit to button. Submit will trigger the action in the form so the form will get reloaded. if you are performing an ajax call change it into button.
Everything seems to be fine, except this bit -
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
You need to change it to -
function processSearch(data) {
// data is a JSON object. Need to access it with dot notation
alert(data.username);
}
UPDATE
You also need to return a JSON response from your PHP file. Something like -
// Set the Content Type to JSON
header('Content-Type: application/json');
$data = [
"key" => "value"
];
return json_encode($data);
In your case you can directly encode the $row like so -
return json_encode($row);
I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}