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.
Related
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 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.
Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );
I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});