call a function after multiple ajax request is performed - javascript

So in my program, i have two tabs i am performing a post ajax request using form.
On load of ajax two different kinds of json will appear
the code is as below:
$('#myForm').submit(function () {
$.ajax({ // create an AJAX call...
data : $(this).serialize(), // get formdata
dataType : "json",
//async : false,
//timeout : 55000,
type : $(this).attr('method'), // GET or
// POST
url : url.A, // the file to call
success : function ( json ) {
// on success..
$('.ajaxloader').css("visibility", "hidden");
Graph = json;
draw(Graph);
}
});
$.ajax({ // create an AJAX call...
data : $(this).serialize(), // get formdata
dataType : "json",
type : $(this).attr('method'), //POST
url : url.B, // the file to call
success : function ( json ) {
// on success..
table= json;
plot(table);
}
});
}
Now on josn s arrival i am first showing the table, to view my other tab, i am writing a onclick event this way..
$(init);
function init () {
$('body').on('click', 'a.all',function(){
plot(table);
})
.on('click', 'a.domain',function(){
draw(Graph);
});
}
Now my problem is if i click on domain, the json would have still not loaded hence throwing a error,
How do i resolve this..
So far i tried async:false (it works fine but it shows a deprecated warning)
AjaxStop, works well the first time then when switching tabs it just shows no response
I also tried when but since i am new to java script I didn't understand the usage at all

You could try to use an Ajax global event like ajaxComplete().
var ajaxCounter = 0;
$(document).ajaxComplete(function(){
ajaxCounter++;
if(ajaxCounter == 2){
$(init);
}
});

Related

Load json data after ajax submit success

i try to create tags form with textextjs
but i have a problem with ajax to call new data after another ajax success submit
this is my code to call json
var tagload = $('#textarea')
.textext({
plugins : 'autocomplete filter tags ajax',
ajax : {
url: "<?= base_url() ?>admin_ajx/tags_ajx/data_tags",
dataType : 'json',
cacheResults : true
}
});
and this is my code to submit new data to json
$(document).ready(function(){
$(".save_new_tags").click(function(){
var data = $('.add_new_tags').serialize();
$.ajax({
type: 'POST',
url: "<?= base_url() ?>admin_ajx/tags_ajx/add_tags",
data: data,
success: function() {
$(".add_new_tags")[0].reset();
alert("Post Success!");
tagload.ajax.reload();
}
});
});
});
how to load new data, after success submit new data
i thinks the problem is here
cacheResults : true
i'am still looking for solution
There is not AJAX property on the returned jQuery selection in tagload.
The example with cacheResults property set to true assumes that the backend is returning all possible results.
Since you're allowing for updates to the possible values, this isn't the situation any longer.
Removing cacheResults option or set it to false should have your tag suggestions updated.
You could also keep the cacheResults option set to true and update the suggestions on the Textext instance after fetching the tags using $.ajax.
var opts = {
url: "<?= base_url() ?>admin_ajx/tags_ajx/data_tags",
dataType : 'json',
cacheResults : true
}
var tagload = $('#textarea')
.textext({
plugins : 'autocomplete filter tags ajax',
ajax : opts
});
$(document).ready(function(){
$(".save_new_tags").click(function() {
//...
$.ajax(opts).done(function(suggestions) {
var textExts = $('#textarea').textext()[0]
textExts.ajax()._suggestions = suggestions
});
});
});

Wp_admin ajax request returns with response "0"

I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );

magento getting the whole page instead of just variables value via controller

I expect the controller to return variable's value from efund_2.phtml when the ajax request is made via controller but its returning the initiator's(efund.phtml) entire html.
/**
* Called using AJAX POST method.
*/
public function getEfundAction()
{
// Get post data.
$PostData = $this->getRequest()->getPost();
$Param1 = $PostData['param1'];
$Param2 = $PostData['param2'];
$ModelLayout = new Pteb_System_Model_Layout_Backend();
$ModelLayout->LoadLayout();
$Block = $ModelLayout->SetContentBlock( 'efund-block', 'Pteb_System_Block_Cms' );
$Block->setTemplate('adminpteb/efund/efund_2.phtml');
// Passing parameters to template file.
$Block->setData( 'MyPostData1', $Param1 );
$Block->setData( 'MyPostData2', $Param2 );
$ModelLayout->ShowLayout();//this getting the whole page html. But I just need the value returned by the variables in the page(efund_2.phtml).
}
PHP function in efund.phtml page.
function GetEFund()
{
var url='http://emall.3pteb.my/adminpteb/efund/getEfund';
var DivResult=jQuery('#DivResult');
var data = {
"action": "test"
};
$.ajax({
type:'GET',
url:url,
dataType: "html",
data: data,
success: function(data) {
alert(data);
DivResult.append(data);
}
});
}
And the above function is initiated by :
$('a').bind('click', function(){
GetEFund();
});
I'm getting this error:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
In the network tab (Chrome console), I see the call is made to the
function getEfund(). However when clicked on it, it shows the entire
html of efund.phtml page , in fact that was what returned by the
controller. How can I make efund_2.phtml return its variables?
Seems like you need to set JSON headers in your controller:
// Set our return json.
$sJson = json_encode( $aDataArray, 1 );
// Send it back to our ajax call.
$this->getResponse()->setHeader( 'Content-type', 'application/json' );
$this->getResponse()->setBody( $sJson );

how to use ajax in jQuery in javascript

I want to post javascript variable to another php file and I search using Ajax may help.I want to get back the data on another php file by "post" method.But I can't use $.ajax({}) directly inside javascript:
function input() {
$.ajax({
url : 'update_service.php',
type : 'POST',
data : {
name: name,
},
success : function(response) {
alert(response);
}
});
The error message said "unexpected function ajax()". How to fix it?
JQuery Version
$.post( "update_service.php", function( data ) {
alert( "Data Loaded: " + data );
});

Getting JSON response from the server but can't display as HTML with Jquery

I'm building a mobile app and i build a PHP API that renders data from a mysql db and encode it as JSON
i call this api with Jquery ajax to get to display the records from the json output as JSONP and render it in my document in the success function.
so far i get the JSON correctly when i do the request via $.ajax and i can see the data in the Response in my firebug but in the other side the ajax function fires the ERROR not the Success.
i have a demo code in here :jsfidle
this is my $.ajax Call:
$(document).on("pageinit","#myPage", function() {
$("#autocomplete").on("listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
var dataString = 'keyword='+value;
if (value.length > 2 ) {
$.mobile.loading("show");
$.ajax({
type: "GET",
url: "http://example.com/search.php",
dataType: "jsonp",
jsonpCallback: 'jsonpCallback',
cache:true,
data: dataString,
success: function(data) {
$.mobile.loading("hide");
alert(data);
}
})
}
});
});
if you check the net panel you 'll find it successful and there is data coming.
Kindly Advise.
Thanks A lot
Your response is not including the callback jsonpCallback() in the response, the response I'm seeing is simply
({"name": ... })

Categories

Resources