AJAX call each() and find() application - ajax

The message alert does not appear after the post call under ajax.
Given the following ajax call:
var val= 1;
$.post("ajax.php", { information: val }, function(result)
{
$(result).find("div").each(function()
{
if($(this).text()=="OK")
{
alert("OK");
}
});
});
and the ajax.php file:
<?php
if($_POST['information']==1)
{
?><div>You must fill all the fields</div><?php
?><div>The title must be between 10 and 30 characters</div><?php
?><div>Please insert your email in the field</div><?php
?><div id="answer">OK</div><?php
}
?>
Thanks for your help!
EDIT: corrected errors found by Benny. corrected post syntax and $(result) syntax

In your example you have faulty $.post syntax.
$.post("ajax.php"), { information: $val }, function(result){
// Callback code
});
The correct syntax would be.
$.post("ajax.php", { information: $val }, function(result){
// Callback code
});
Also using $ as part of the $val variable name is confusing. It can trick developers into thinking that it has something to do with the jQuery variable, even though it's just part a local variable name. I would recommend doing just...
var val = 1;

Related

Pass DataTable reference to the callback function on load

My current code is:
var CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: ajaxurl + '?action=pos&post_action=get_commissions'
},
'initComplete': function (settings, json){
//possible to access 'this'
this.api().columns(1);
}
});
I improved the code above as below with help :
var CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: ajaxurl + '?action=pos&post_action=get_commissions'
},
'initComplete': function(settings, json){
callbackFunction(settings);
}
});
function callbackFunction(settings){
var api = new $.fn.dataTable.Api( settings );
// api is accessible here.
}
Update :
Now I can access api from callback function. But I want use same callback with load() as below code.
CommissionLogs.ajax.url( newAjaxURL ).load( callbackFunction(), true);
But settings param is not accessible in load function.
I can clear and destroy datatable and re initialize always. But what will be the right way.
I think you need settings:
https://datatables.net/reference/type/DataTables.Settings
$('#example').dataTable( {
"initComplete": function(settings, json) {
myFunction(settings);
}
});
function myFunction(settings){
var api = new $.fn.dataTable.Api( settings );
// Output the data for the visible rows to the browser's console
// You might do something more useful with it!
console.log( api.rows( {page:'current'} ).data() );
}
Other option is re-use your var CommissionLogs variable throughout the code without using this, I recommend strongly this last option.
The dataTable.ajax.url().load() has not access to settings.
So can not call a callback function with settings.
But possible to use callback function without settings.
So here is an alternative way to use settings.
CommissionLogs.clear();// clear the table
CommissionLogs.destroy();// destroy the table
CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: newAjaxUrl
},
'initComplete': function (settings, json){
callbackDatatableFunciton(settings);
}
});

jQuery wait for an AJAX request to be completed before refreshing the page

I've got the following jQuery:
$("#delete_products").click(function() {
$(":checkbox:checked").each(function() {
var pid = $(this).val();
$.get('delete_product.php',{pid: pid});
});
location.reload();
});
There is a problem with this since the page doesn't wait for the AJAX request to be completed (MULTIPLE AJAX REQUESTS), and refreshes the page immediately and makes the AJAX request to not run and fail.
How can I do that the page will only refresh when it done loading?
I've been given this code:
$("#delete_products").click(function () {
var promises = [];
$(":checkbox:checked").each(function () {
var pid = $(this).val();
promises.push($.get('delete_product.php', {
pid: pid
}));
});
$.when.apply($, promises).done(function () {
location.reload();
});
return false;
});
But this solution just doesn't work.
any suggestions?
your code seems like it should work, but i would recommend to delete all products with one call by passing array of ids.
less work for the browser, less work for the server, faster results.
UPDATED ANSWER
$("#delete_products").click(function () {
var ids = [];
$(":checkbox:checked").each(function () {
ids.push($(this).val());
});
$.post('delete.php', { 'ids': ids } }).done(function() {
alert('hells yeah!');
});
return false;
});
and as for the server side:
$commaSeperatedIds = explode(',', $_POST['ids']);
mysql_query('DELETE FROM products WHERE id IN('.mysql_real_escape_string($commaSeperatedIds).')');
Use "success" parameter of "get"
EDIT: add counter of requests.
total_requests = $(":checkbox:checked").length;
total_success = 0;
...
$.get('delete_product.php',{pid: pid}, function (data, status, xx) {
...
total_success++;
if (total_success >= total_requests) {
location.reload();
}
});
...
Possible Solution #1:
The async parameter could help. Set it to false.
Since you`re using the $.get() function, this is done with:
$.ajaxSetup({
async: false
});
 
With the $.ajax() function, you'd simply set it like:
$.ajax({
url: ...,
async: false,
success: function(data) {}
});
More info on this can be found here.
 
Possible Solution #2:
Use the .success() callback hook OR .complete() if you want to refresh the page no mather if the request failed or not.
$.get('delete_product.php',{pid: pid}).success(function(response)
{
location.reload();
});
 
Happy coding!
 
Edit:
The questioner seems to prever sUP's answer. I'd like to provide an example of how to achieve the desired functionality with jQuery:
$("#delete_products").click(function()
{
var products = [];
$(":checkbox:checked").each(function()
{
var pid = $(this).val();
products.push(pid);
});
$.post('delete_products.php', {'products': products}).done(function()
{
location.reload();
});
});
 
If you prefer to use JSON for the post data, try:
$('#delete_products').click(function()
{
var products = [];
$(':checkbox:checked').each(function()
{
products.push($(this).val());
});
// Convert the products array into JSON
products = JSON.stringify(products);
$.post('delete_products.php', {'products': products}).done(function()
{
location.reload();
});
});
In PHP you need to parse the json string as follows:
<?php
// This creates an associative array from the JSON string
$delete_products = json_decode($_POST['products'], true);
// Use explode to make a comma separated string from the array
// for use in a SQL SELECT query:
$delete_products = explode(',', $delete_products);
Info about json_decode can be found in the PHP Manual.
JSON.stringify is not supported in older browsers. Include JSON-js if you need cross browser support.
I too believe that the desired result can probably be achieved best by collecting the product IDs and then sending a single Ajax call to take care of them all.
But since the OP put the interesting question forward of how to handle multiple Ajax requests and wait for them all to be finished I have looked at the when() method again and it seems to me that the original syntax is still faulty.
According to the jQuery manual when() is a method and therefore requires to be called with one or more argument(s) in parentheses. I have not worked with promises yet and I have not tested anything but I assume that something like the following might bring at least a different result:
$("#delete_products").click(function () {
var promises = [];
$(":checkbox:checked").each(function () {
var pid = $(this).val();
promises.push($.get('delete_product.php', {
pid: pid
}));
});
$.when(promises).done(function () {
location.reload();
});
return false;
});
As I said before, I still have not quite grasped the promises mechanisms/syntax yet ...
In the original version $.when does not have any meaningful context to work on, The apply() method does provide context but only after when has done its (unseccessful) work already.

Basic implementation of ajax in magento

I am a newbie in magento and trying to implement ajax,but can't find a proper tutorial to follow. Could anyone provide me some reference or guide me to where i would be able to find it?
Don't know a tutotial but I can explain you bit what I implemented in a project a month back.
I created a controller on which we can fire an AJAX request on a specific action. In this case the getoptionsAction in the IndexController of our custom Offerte module.
The getoptionsAction in my controller takes a product_id and loads the options for the product. It builds the HTML and echo's this on function end.
In phtml file I have following code to invoke the AJAX request and update html-object in frontend:
function get_options(prod_id){
var product_options = $('product_options');
var prod_id = $('product').getValue();
new Ajax.Updater('product_options',
'<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); ?>offerte/index/getoptions',
{ method: 'get',parameters: {prod_id: prod_id, type: 'get_regular_options' } ,
onCreate: function(){
$('loading-img-options').show();
},
onComplete: function (t) {
$('loading-img-options').hide();
$('product_options').show();
}
});
}
the above function uses Ajax.Updater. You can also use Ajax.Request to get the result to juggle with.
function stripslashes(str) {
return str.replace(/\\'/g,'\'').replace(/\"/g,'"').replace(/\\\\/g,'\\').replace(/\\0/g,'\0');
}
function get_products(){
product = $('product');
cat_id = $('category').value;
new Ajax.Request('<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); ?>offerte/index/getproducts',
{method: 'get', parameters: {cat_id: cat_id, mode: 'offerte'},
onCreate: function(){
$('product-loading').show();
$('product_options').hide();
},
onSuccess: function(t) {
resp = jQuery.parseJSON(t.responseText);
$('prod-container').innerHTML = resp.options ? stripslashes(resp.options) : '<?php echo $this->__('No options found') ?>';
$('product-loading').hide();
}
});
}
(please note I use JQuery to parseJSON. You can also use String.evalJSON, but I was lazy here :-)
Using Ajax.Request you need to return the result from the controller as JSON. I used the code below in my controller to return JSON to our phtml to use in the onSuccess Callback function above:
$this->getResponse()->setBody(Zend_Json::encode($result));
Hope this is of any help

AJAX recognizing if the result call is an error or a success

multiple request to fill different containers?
ajax/javascript example:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$.post("ajax.php", {request : $var}, function()
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
});
});
});
ajax.php example:
<?php
if($_POST['request']==1) // or several complicated conditions
{ ?><div>This is a success</div>
//if success I would like to load another piece of html inside an id="container2".
<?php }
if($_POST['request']==0)
{ ?><div>This is a disaster</div> <?php }
?>
That's the question if the response is 1 (or This is a success) I would like to load another piece of html code inside a container (container2) with a different id from the original container id used for the request within the post method(in this case "container1").
Is there a way to do it?
Thanks for your thoughts and answers!
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$.post("ajax.php", {request : $var}, function(a,b)
{
if(b=="error"){
Do Somthing...
} else{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
});
});
});

How to make Dajax callback into scoped object

I cant seem to find a way to make django-dajaxice have its callback inside same scoped object from which made the initial call.
MyViewport = Ext.extend(MyViewportUi, {
initComponent: function() {
MyViewport.superclass.initComponent.call(this);
},
LoadRecordsCallback: function(data){
if(data!='DAJAXICE_EXCEPTION')
{ alert(data); }
else
{ alert('DAJAXICE_EXCEPTION'); }
},
LoadRecords: function(){
Dajaxice.Console.GetUserRecords(this.LoadRecordsCallback);
}
});
var blah = new MyViewport();
blah.LoadRecords();
I'm on django, and like the calling syntax to django-dajaxice. I'm using Extjs 3.2 and tried passing a Ext.createCallback but Dajax's returning eval seems to only want a string for the callback.
BozoJoe, this should work.
MyViewport = Ext.extend(MyViewportUi, {
initComponent: function() {
MyViewport.superclass.initComponent.call(this);
},
LoadRecordsCallback: function(data){
if(data!='DAJAXICE_EXCEPTION')
{ alert(data); }
else
{ alert('DAJAXICE_EXCEPTION'); }
},
LoadRecords: function(){
Dajaxice.Console.GetUserRecords('blah.LoadRecordsCallback');
}
});
var blah = new MyViewport();
blah.LoadRecords();
I'm not familiar with django at all, but I think I understand the problem.
It seems that the API mandates that you pass a string which will be eval'd as a function call, so you must pass the name of the function, rather than the function itself.
This in turn means that it must be a name that is meaningful at the window scope - either a function defined outside of an Ext class (e.g. "myGlobalFunction"), or a member function of an Ext class that is accessible as a variable (e.g. "window.blah.LoadRecordsCallback")

Resources