Calling ajax inside ajax - php

This is my first day and first question here, hope you will forgive me if my question is very trivial for this platform.
I am trying to call ajax inside ajax, One ajax call is going to call one cotroller action in which it will insert a record in the database, The action for the 1st ajax call is
public function createAction(Request $request){
if ($request->isXmlHttpRequest()) {
$name = $request->get("gname");
$description = $request->get("desc");
$portfolio_id = $request->get("PID");
$portfolio = $this->getDoctrine()
->getRepository('MunichInnovationGroupPatentBundle:PmPortfolios')
->find($portfolio_id);
$portfolio_group = new PmPatentgroups();
$portfolio_group->setName($name);
$portfolio_group->setDescription($description);
$portfolio_group->setPortfolio($portfolio);
$portfolio_group->setOrder(1000000);
$portfolio_group->setIs_deleted(0);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($portfolio_group);
$em->flush();
$msg = 'true';
}
echo $msg;
return new Response();
}
The 2nd ajax call is going to get the updated data that is inserted by the first ajax call, The action for this call is
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
echo json_encode($portfolio_groups);
return new Response();
}
}
My JQuery is as follows
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
if(data == "true") {
$("#new-group").fadeOut("fast", function(){
$(this).before("<strong>Success! Your Portfolio Group is created Successfully.</strong>");
setTimeout("$.fancybox.close()", 3000);
});
$.ajax({
type: 'POST',
url: getgroups,
data: data,
success: function(data)
{
var myArray = JSON.parse(data);
var options = $("#portfolio-groups");
for(var i = 0; i < myArray.length; i++)
{
options.append($("<option />").val(myArray[i].id).text(myArray[i].name));
}
}
});
}
}
});
I am calling the 2nd ajax inside the success of the 1st one to ensure that the first ajax is successfully completed, but the 2nd ajax call is not getting the updated data.
How can I ensure that the 2nd ajax will be called after the completion of the first one and I get the recently inserted data as well
Thanks
MY SOLUTION
Just using one ajax call
in the create action where an insertion is made , just after the insertion take all the groups for the portfolio, and return json_encode($portfolio_groups);
Inside the JQuery
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
$("#new-group").fadeOut("fast", function(){
$(this).before("<strong>Success! Your Portfolio Group is created Successfully.</strong>");
setTimeout("$.fancybox.close()", 3000);
});
var myArray = JSON.parse(data);
var options = $("#portfolio-groups");
for(var i = 0; i < myArray.length; i++)
{
options.append($("<option />").val(myArray[i].id).text(myArray[i].name));
}
}
});

I think the problem may be that you've got lots of variables names ´data´. In the second ajax call, the data sent will always be "true", but I suspect you would like to send something else. I would give them unique names to make things clearer and see what happens.

Just using one ajax call
in the create action where an insertion is made , just after the insertion take all the groups for the portfolio, and return json_encode($portfolio_groups);
Inside the JQuery
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
$("#new-group").fadeOut("fast", function(){
$(this).before("<strong>Success! Your Portfolio Group is created Successfully.</strong>");
setTimeout("$.fancybox.close()", 3000);
});
var myArray = JSON.parse(data);
var options = $("#portfolio-groups");
for(var i = 0; i < myArray.length; i++)
{
options.append($("<option />").val(myArray[i].id).text(myArray[i].name));
}
}
});

Ajax in side the success method of the first Ajax, as you did, should ensure you the second Ajax is called after the first one. The success method is triggered ONLY after results have returned.
For a test add console.log() inside the first Ajax req just before you call the second one. and another console.log() inside the second Ajax success method.
try to put a console.log on the first success->data variable and see what you get. If you have an error I will cause the second request to fail.

Related

Recursive AJAX calls get cancelled

I have a page showing log files which I want to give the user the ability to select and delete. The deletion is done through an AJAX request where the ID of each log-for-deletion is sent via the parameters.
The problem is that there are instances where there are hundreds of logs and in these cases the AJAX request seems to fail. I assume because there is just too much data sent via the parameters. I have tried breaking the AJAX request into parts, but only the first request is sent, afterwards all other requests are shown in Chorme as "cancelled". Following is my code:
var logFiles = [];
function deleteLogBatch() {
if (logFiles.length == 0)
return false;
if (logFiles.length > 10)
var elements = 10;
else
var elements = logFiles.length;
var params = 'action=deletelog';
for (var i = 0; i < elements; i++) {
params += '&lf' + i + '=' + escape(logFiles.shift());
}
$.ajax({
type: "POST",
url: './ajax/logs.php',
data: params,
success: function(response) {
checkResponse(response);
deleteLogBatch();
}
});
}
$('body').on('click', '#confirm-log-delete', function(event) {
event.preventDefault();
$('.select-log').each(function() {
if ($(this).is(":checked")) {
logFiles.push($(this).attr('id'));
}
});
deleteLogBatch();
}
Any help as to why this is happening and what is the proper way of doing this would be appreciated.
You should use async ajax calls
$.ajax({
type: "POST",
url: './ajax/logs.php',
async: true,
data: params,
success: function(response) {
checkResponse(response);
deleteLogBatch();
}
});
It will not wait to previous ajax call

Send data from Javascript to PHP and use PHP's response as variable in JS

I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3

Recurring jquery ajax calls

I have multiple check boxes for users to select and based on selected checkboxes i need to make a jquery ajax call. For that i used FOR loop to iterate through selected elements array and sent ajax request for each checkbox. Each request takes more than 5-10 minutes. In current scenario it calls all ajax request simultaneously.
I want to call next ajax calls only after finishing earlier ajax request.
Is there any solution for this?
You can make recursive calls.
function sendAjax(id) {
var checkbox = $('input[type=checkbox]:eq('+id+')','#formid');
if(checkbox == undefined)
return;
$.ajax({
type: 'POST',
dataType: "json",
url: 'url',
data: { },
success: function (data) {
sendAjax(id+1);
},
error: function (data) {
alert(data.responseText);
}
});
}
sendAjax(0);
Iterate in your readyStateChange method instead of in the for loop.
...
array_index++;
var data = selected_elements[array_index];
if (data) {
send_ajax_request(data);
}
}
That is kind of against the whole point of ajax. The first "a" is usually considered to mean "asynchronous", but you want to make the request synchronous (async = false I believe in jQuery)
Using recursive call, until previous ajax request not finished, next request cant be processed. So recursive call can solve the problem of these ajax request.
var queue_element = ["a","b","c","d","e","f","g"];
var execute_queue = function(i){
$.ajax( {
url: queue_element[i],
success: function({
i++; // going to next queue entry
// check if it exists
if (queue_element[i] != undefined){
execute_queue(i);
}
}
}); // end of $.ajax( {...
}; // end of execute_queue() {...
var index = 0;
execute_queue(index); // go!

Wordpress - fetch user info using jQuery ajax POST request

I am working in Wordpress trying to use an ajax request to fetch user data by passing the user id.
I can see that the user id sends correctly via AJAX POST but I am getting an internal error message and I don't know why.
At first I thought it was because I was trying to fetch some custom fields that I had added to the user profile but even when I simplified my script I am still getting the error message.
Any help is much appreciated!
Front End
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: 'wp-content/themes/twentyeleven/author_info.php',
data: {id: id},
dataType: 'html',
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
author_info.php
$user_id = $_POST['id'];
$forename = get_the_author_meta('user_firstname', $user_id);
$output = $user_id;
echo $output;
Error Message
500 (Internal Server Error) jquery.min.js:4
Mathieu added a hackable approach to intercepting a request and redirecting it, which is fine. I prefer to build out AJAX responses that return json_encoded arrays.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
url: 'http://absolute.path/wp-admin/admin-ajax.php',
data: {'action' : 'ajax_request', 'fn': 'getAuthorMeta', 'id': id},
dataType: 'json',
success: function(data) {
//We expect a JSON encoded array here, not an HTML template.
}
});
return false;
});
Now we build out the function to handle our ajax requests.
First, we need to define our ajax add_action method ->
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');
We need to use both add_action lines here. I won't get into why. You'll notice the _ajax_request here. This is the 'action' that we sent over in our AJAX function data: {'action' : 'ajax_request'}. We use this hook to validate our AJAX request, it can be anything you'd like.
Next, we'll need to build out or function ajax_handle_request.
function ajax_handle_request(){
switch($_REQUEST['fn']){
case 'getAuthorMeta':
$output = ajax_get_author_meta($_REQUEST['id']);
break;
default:
$output = 'That is not a valid FN parameter. Please check your string and try again';
break;
}
$output = json_encode($output);
if(is_array($output)){
return $output;
}else{
echo $output;
}
}
Now let's build our function to actually get the author meta.
function ajax_get_author_meta($id){
$theMeta = get_the_author_meta([meta_option], $id);
return $theMeta;
}
Where [meta_option] is a field provided by WP's native get_the_author_meta function.
At this point, we'll now go back to our success:function(data) and (data) is a reference to the json_encoded array we've returned. We can now iterate over the object to get our fields and output them into the page as you'd like.
You are not in a POST at that moment because you are calling a specific page of your template that probably doesn't correspond to any article in your blog.
Instead, create a pluggin that will do this:
add_action('template_redirect', 'my_author_meta_intercept');
function my_author_meta_intercept(){
if(isset($_POST['getAuthorMeta'])){
echo get_the_author_meta('user_firstname', $_POST['getAuthorMeta']);
exit();
}
}
This will short circuit the request to the same page as before when you call it using:
http://mysite/mycurrenturl?getAuthorMeta=testMetaKey
So calling that post normally will return the article as usual, but if you pass in ?getAuthorMeta, it will stop the template from being selected and simply return the exact content you want it to return.
In your page, you just have to change your javascript to:
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: window.location.href,
data: {getAuthorMeta: id},
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
Just make sure you adapt the concept to what you need!
I would rather recommend you to use WP AJAX action method.
As in your case, add the following to your functions.php file.
add_action('wp_ajax_get_user_info', 'ajax_get_user_info');
add_action('wp_ajax_nopriv_get_user_info', 'ajax_get_user_info');
function ajax_get_user_info() {
//Handle request then generate response using WP_Ajax_Response or your html.
}
then in javascript tag.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
jQuery.post(
ajaxurl, /* if you get error of undefined ajaxurl. set it to "http://example.com/wordpress/wp-admin/admin-ajax.php"*/
{
'action':'get_user_info',
'user_id':id
},
function(response){
alert('The server responded: ' + response);
}
);
});
I would recommend you to read the 5 tips for using AJAX in WordPress.
p.s; Code above is not tested, it may have errors. but you get the idea.

jQuery.ajax() success callback store data to return

I'm trying to get some data from a PHP script in a project right now. All examples I found searching for AJAX callback functions "use" the data already in the callback itself, but I want to fetch data and store it in a way ready to be returned.
function getEle (id) {
var element = [];
$.ajax({
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id;
element[1] = content;
// if I alert(element[1]); here it will work!
}
});
alert(element[1]); // here it just won't :/ ("undefined")
return element;
}
Somewhere in my script some function needs to getEle(ments) but all I get is undefined.
is there a way to do what I want? Or is there maybe a better way to do this?
A solution would be to pass a callback function to getEle():
getEle(id, callback){
$.ajax({
/* some options, */
success: function(){
var content = data;
element[0] = id;
element[1] = content;
callback(element);
}
})
}
And then pass a function containing the code of what to do when you have the element content:
getEle('myId', function(element){
alert(element[1]);
});
Two things are failing here:
Variable scope - You define the variable content inside the AJAX callback. This makes it inaccessible from the surrounding code. You could omit the var and just write content = data which makes it accessible globally.
Asynchronicity - Becaus AJAX is asynchronous the script following the callback will be executed before the callback was executed. The only way to solve that problem is to use the callback as it's intended to.
Take a look at this.
function getEle (id, callback) {
var element = [];
$.ajax({
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id;
element[1] = content;
callback(element);
}
});
}
}
getEle ("someID", function(someElement) {
alert(someElement);
});
Here's what's happening in your code:
the array "element" is initialized.
the AJAX call is made with a success callback function
while it's waiting for that AJAX to run, it goes ahead with the rest of your code and alerts element[1], which doesn't exist yet
the success callback runs and populates the array "element".
You might consider a global variable to solve this:
var element = [];
function getEle (id) {
$.ajax({
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id; // the global "element" is set
element[1] = content;
}
});
}
// element[0] will exist now, but only after the AJAX call is complete
Alternatively, you could turn your AJAX into a synchronous call:
function getEle (id) {
var element = [];
$.ajax({
async: false, // forces synchronous call
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id;
element[1] = content;
}
});
alert(element[1]); // now it is set
return element;
}
The only other option I can see is to keep everything tied up inside the "success" callback, which you already discovered works fine.
Your callback executes some time after the rest of your code finishes.
You need to pass the value back using a callback, the way $.ajax does.
Your alert ends up being undefined because the AJAX call is asynchronous. So while that AJAX call is waiting for the server's response, the script continues on to the alert, at which point element[1] is not yet defined.
You should place your return element line inside of the success callback function.

Categories