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

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.

Related

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

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);
}

Is it possible to load content of page without Refreshing the whole page

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" );

Cannot call external function using ajax [duplicate]

This question already exists:
Deleting a specific node based on dropdown selection in XML [duplicate]
Closed 7 years ago.
Here's my jquery code
<script>
$(function () {
$('#deleteform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'delete.php',
success: function () {
alert('Worked');
}
});
});
});
</script>
And my PHP code (I'm just trying to test it out, so I added a simple function)
<?php
header("Location: http://www.google.com/");
?>
And nothing happens when I click the button (when the form submit) except that "Worked" alert box. But whatever I put in that PHP file (delete.php), nothing happens. What am I doing wrong? My "delete.php" file will have a script to delete data in a XML file, just in case it changes something. (for now Im trying with a simple php line)
EDIT
The real PHP code that will go in the PHP file is this :
<?php
$xml = simplexml_load_file("signatures.xml");
$name = $_POST['nom'];
$signs = $xml->xpath('//Signature[Nom = "'.$name.'"]');
$xml -> SignaturesParent -> removeChild($signs);
?>
Nothing happens when I try that.
Try this.
The ajax call now alerts whatever is sent to it from the delete.php
The ajax call does a POST and not a GET so that it matches the fact that you are using $_POST[''] and send some data i.e. smith you are going to have to change that to something that actually exists in your XML file
The delete.php actually returns something
The delete.php saves the changed xml document back to disk to a file with a different name, so you can see if it actually did anything. just while you are tesing.
<script>
$(function () {
$('#deleteform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'delete.php',
data: {nom:"smith"},
success: function (data) {
alert(data);
}
});
});
});
</script>
<?php
$xml = simplexml_load_file("signatures.xml");
$name = $_POST['nom'];
$signs = $xml->xpath('//Signature[Nom = "'.$name.'"]');
$xml -> SignaturesParent -> removeChild($signs);
$result = $xml->asXML("signatures2.xml");
echo $result ? 'File Saved' : 'File Not Saved';
?>

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.

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