This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 years ago.
Trying to run a script, (test.al();) and inside test.al, its called getcrypt.php();, the php script is on a webserver, and it is working. Currently, these are my scripts
JS
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
return v;
}
});
}
}
var test = {
al: function () {
a = getcrypt.php();
alert(a);
}
}
PHP
<?php
$id = $_POST['id'];
if ('getit' == $id){
$value = 'VALUE';
echo $value;
}else{
echo 0;
}
?>
In this way, it will show an alert with 'unidefined', and if i add a alert(v); right before return v, it will show me 'VALUE', but not able to use it outside the variable...
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
return v;
}
});
}
}
This will give me an alert with the correct value (AFTER THE 'undefined')
This is because of the asynchronous call you're making. The return is only for the success function and not for the php function.
To get the value out you would need to write:
var value;
var getcrypt = {
php: function (callback) {
$.ajax({
url: "",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
callback(v);
}
});
}
}
getcrypt.php(function(v) {
alert(v);
// This happens later than the below
value = v;
});
// The below will still not work since execution has already passed this place
// alert will still return undefined
alert(value);
The problem is jQuery ajax works with callbacks and does not work with return value's so you need to add an callback to your getcrypt function so say
var getcrypt = {
php: function (callback) {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
callback(v);
}
});
}
}
so now if you call
getcrypt.php(function(returnVar){
alert(returnVar)
});
you will get an alert with VALUE
$.ajax returns immidiately (well, almost :)) upon calling, before the response is received. You should rewrite your code to accomodate to this fact, something like this;
var getcrypt = {
php: function(){
$.ajax({
//..other params ..//
success: function(msg){
var v = msg.match(/^.*$/m)[0];
alertResponse(v);
}
});
},
alertResponse: function(processedResponse) {
alert(v);
}
}
var test = {
al: function(){
getcrypt.php();
}
}
If you need your response in test object, you move alertResponse to that object and call it from success method. I think this tutorial might be useful for you to learn javascript event-driven programming model.
$.ajax calls are async. So what you get is the return value of $.ajax (when the request is sent, before a response is received). It is only when the browser receives a response to the ajax call that the success callback is run, as a seerate process from the $.ajax call. In other words the return value of $.ajax will always be null. I'm not sure it's possible to do anythging with the return value of the success callback, you need to put your logic (or a call to another function with the logic) in the success callback itself, in the same way you did with the alert in your final example
Related
I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.
How would I merge these two bits of code and can someone explain what the key and value would be.
I'm building a notifications system and I'm wanting to store the last new notification_id but not have it inserted into the div over and over again if its the same one, so then the ajax searches for anything else within my server that maybe new.
Ajax
<script type="text/javascript">
function loadIt() {
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(dataHandler){
}
});
}
setInterval(loadIt, 10000);
</script>
Localstrorage
window.localStorage.setItem('key', 'value');
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
You've confused oldschool Ajax by hand with jQuery. The parameter to the success function in jQuery is not a function name or handler. Its a variable name that will contain the response from the server. The success function itself is equivalent to the handler functions you would have created doing it the old way.
So not:
success: function(dataHandler){ }
...
...
var dataHandler = function (response){
But rather:
success: function(response) { doCallsToSaveToLocalStorage(response); }
I try to take a response but I could not. I can't describe it why it does not work or what it is wrong.
var virmanYap = function(){
$("#loading").show();
$("#tblVirman").hide();
alert('Virman');
var data = $("#virman_filtre").serialize();
$.post("php/virman_yap.php", data).success(function(r){
alert(r);
});
}
my php code:
foreach ($_POST['virman'] as $evrakNo => $detay) {
print_r($_detay);
}
echo "asd";
Try $.ajax instead of $.post:
var virmanYap = function () {
$("#loading").show();
$("#tblVirman").hide();
alert('Virman');
var data = $("#virman_filtre").serialize();
$.ajax({
url: 'php/virman_yap.php',
type: 'POST',
data: data,
success: function (r) {
alert(r);
}
});
}
Check $.post documentation here: https://api.jquery.com/jQuery.post/
As you can see, success callback is one of the parameters, you don't need to chain it.
$.post("php/virman_yap.php", data, function(r){
alert(r);
});
Do something like this. Just remove the chained success function and you should be good.
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
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Kill Ajax requests using JavaScript using jQuery
Here is the simple code I am working with:
$("#friend_search").keyup(function() {
if($(this).val().length > 0) {
obtainFriendlist($(this).val());
} else {
obtainFriendlist("");
}
});
function obtainFriendlist(strseg) {
$.ajax({
type: "GET",
url: "getFriendlist.php",
data: "search="+strseg,
success: function(msg){
UIDisplayFriends(msg);
}
});
}
Essentially, if a keyup event is fired before the function obtainFriendlist returns a result (and triggers UIDisplayFriends(msg), I need to cancel the in-flight request. The issue I have been having is that they build up, and then suddenly the function UIDisplayFriends is fired repeatedly.
Thank you very much, and advice is helpful too
The return value of $.ajax is an XHR object that you can call actions on. To abort the function you would do something like:
var xhr = $.ajax(...)
...
xhr.abort()
It may be smart to add some debouncing as well to ease the load on the server. The following will only send an XHR call only after the user has stopped typing for 100ms.
var delay = 100,
handle = null;
$("#friend_search").keyup(function() {
var that = this;
clearTimeout(handle);
handle = setTimeout(function() {
if($(that).val().length > 0) {
obtainFriendlist($(that).val());
} else {
obtainFriendlist("");
}
}, delay);
});
A third thing that you should really be doing is filtering the XHR responses based on whether or not the request is still valid:
var lastXHR, lastStrseg;
function obtainFriendlist(strseg) {
// Kill the last XHR request if it still exists.
lastXHR && lastXHR.abort && lastXHR.abort();
lastStrseg = strseg;
lastXHR = $.ajax({
type: "GET",
url: "getFriendlist.php",
data: "search="+strseg,
success: function(msg){
// Only display friends if the search is the last search.
if(lastStrseg == strseg)
UIDisplayFriends(msg);
}
});
}
How about using a variable, say isLoading, that you set to true through using the beforeSend(jqXHR, settings) option for .ajax, and then using the complete setting to set the variable back to false. Then you just validate against that variable before you trigger another ajax call?
var isLoading = false;
$("#friend_search").keyup(function() {
if (!isLoading) {
if($(this).val().length > 0) {
obtainFriendlist($(this).val());
} else {
obtainFriendlist("");
}
}
});
function obtainFriendlist(strseg) {
$.ajax({
type: "GET",
url: "getFriendlist.php",
beforeSend: function () { isLoading = true; },
data: "search="+strseg,
success: function(msg){
UIDisplayFriends(msg);
},
complete: function() { isLoading = false; }
});
}