My Ajax function is skipping my success function, but yet I can still get my php script to run.
Below is my JavaScript function containing my AJAX call. Here's an explanation of what I'm experiencing:
If I put a alert("msg"); in my success function, it NEVER gets hit.
It goes to the error function every time.
However, if I put an alert("error"); in my error function, then my php file still runs and my data is entered into the database correctly.
If I removed alert("error"); from the error function, my php file does not run and nothing is added.
... It's almost as if I need that alert message in my error function to halt the code (or something), in order for my my php file to run.
Does this make sense to anyone?
<script>
function AddItem(){
var name = document.forms["additemform"]["nc_name"].value;
var tag = document.forms["additemform"]["nc_tag"].value;
var table = "<?php echo $_SESSION['UserItemTable']; ?>";
var isValid = false;
$.ajax({
type: "POST",
url: "/AddItem.php",
data: {
"Item_Name": name,
"Tag_Num": tag,
"Table_Name": table
},
dataType: "json",
success: function(resp){
console.log(resp);
alert('msg");
if(resp.reply == "Success")
{
}
else
{
}
},
error: function(data, status){
console.log(data, status);
alert("error");
}
}); //end Ajax
The message that is dumped out in my console is this:
{
readyState: 0,
getResponseHeader: function,
getAllResponseHeaders: function,
setRequestHeader: function,
overrideMimeType: function,
…}
Not sure why my code is not executed...
I don't know if you have this typo in your code as well as in this example, but you have written:
alert('msg");
... both a single and a double-quote. That screws up the execution.
Related
I have the below function in my WordPress functions file, and if I run it as below without the two parameters it works fine, but when I pass the parameters the error handler in the jQuery returns status 500.
If I don't pass the parameters to the PHP function I get status 200 from jQuery, but it's coming from the error handler, and not from the success handler. Why so?
function subscribe_funk(){//$payment_method, $customer_handle){
return "This is a test";
die();
}
It gets called from this ajax:
function subscribe(data) {
jQuery.ajax({
url: PT_Ajax.ajaxurl,
type: "POST",
data: {'action': 'subscribe_funk', 'payment_method': data.payment_method, 'customer_handle': data.customer},
cache: false,
dataType: 'json',
beforeSend: function(){
console.log('Before send subscribe');
},
complete: function(){
},
success: function (response) {
console.log('Message from success handler: ');
console.log(response);
},
error: function(xhr, status, error){
console.log("Message from error handler:")
var errorMessage = xhr.status + ': ' + xhr.statusText
console.log(errorMessage);
}
});
}
Your function expects 2 parameters, however WP/ajax is not passing them directly.
You need to fetch them from $_POST array yourself:
function subscribe_funk(){
$payment_method = $_POST['payment_method'];
$customer_handle = $_POST['customer_handle'];
return "This is a test";
die();
}
Also, you may want to sanitize the post data with sanitize_text_field() or similar function.
Here is a relevant thread in WP StackExchange: how to pass parameters from jQuery ajax to a PHP function
When I click and run my ajax script, I see this error in Chrome:
Status: cancelled
The json data returns to the page in the url bar. My sql table is updating but the error message I indicate above is displaying and the modal doesn't remain open. I suspect there could be a few problems here but I wonder if anybody notice something.
This ajax script is inside a PHP variable that is why you may see some escaped characters. Here the $row is a PHP array. Please don't get confused.
$("document").ready(function() {
$(".form-inline'.$row["userid"].'").submit(function(event) {
event.preventDefault;
var formData = new FormData($(".form-inline'.$row["userid"].'")[0]);
console.log();
$.ajax({
type: "POST",
dataType: "json",
url: "sponsorship.php",
data: formData,
success: function(response) {
if (response.success) {
$("#myModal'.$row["userid"].'").modal(\'show\');
$(".form-inline'.$row["userid"].'").hide();
$("#paypalform'.$row["userid"].'").show();
$("#alertmessage'.$row["userid"].'").show();
$("#closebutton'.$row["userid"].'").hide();
}
else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
contentType: false,
processData: false,
error: function() {
alert("this error is getting displayed");
}
});
});
});
event.preventDefault is a function. You're referencing it, but not calling it.
The default action of the submit event will therefore happen, causing you to leave the page and terminate the JS.
Don't forget to put () when you are trying to call a function.
The problem is with String conctatination on your JS :
$("#myModal'.$row["userid"].'").modal(\'show\');
$(".form-inline'.$row["userid"].'").hide();
$("#paypalform'.$row["userid"].'").show();
$("#alertmessage'.$row["userid"].'").show();
$("#closebutton'.$row["userid"].'").hide();
You have to either fix the concatination :
$("#myModal'.$row['userid'].'")
Or I'm assuming you are missing the php tags on $row
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
So I have this javascript function, it sends an ajax requests to fetch a value from a php variable.
The function looks like so:
function get_cart_limit() {
$.ajax({
url: '/w2w/ajax/',
data: {
_action: 'get_cart_limit'
},
type: 'post',
timeout: 10000,
success: function(output) {
var cartlimit = output;
alert(cartlimit); // this gives me the correct value.
return cartlimit;
},
error: function(output){
}
});
}
When I call this function from another function like this:
var cartlimit = get_cart_limit();
my variable "cartlimit" is undefined.
So the ajax call is working, but why can't I return the value to another function?
To early for me, my brain isn't working properly! :)
Cheers!
If you change the scope of the cartlimit variable and disable Asynchronous request, get_cart_limit() should return the correct value
function get_cart_limit() {
var cartlimit;
$.ajax({
url: '/w2w/ajax/',
data: {
_action: 'get_cart_limit'
},
type: 'post',
timeout: 10000,
async: false,
success: function(output) {
cartlimit = output;
},
error: function(output){
}
});
return cartlimit;
}
The variable cart_limit is only set once the AJAX request successfully terminates.
Why?
The AJAX call is asynchronous, i.e. get_cart_limit() ends before the actual answer comes back from the server
The anonymous function that you specified as success: function(output) { /*...*/ } is called when the answer comes back from the server.
If you call another function that tries to access cart_limit before the success function has been executed, you will get an undefined value.
Even if you execute a return statement in the success function, it is a different function from get_cart_limit() and it gets executed at a different time, so you will not obtain the desired effect of assigning the return value to whatever variable.
One to solve this problem is to have the function that needs cart_limit be called by the anonymous success function.
function get_cart_limit() {
$.ajax({
url: '/w2w/ajax/',
data: {
_action: 'get_cart_limit'
},
type: 'post',
timeout: 10000,
success: function(output) {
var cartlimit = output;
alert(cartlimit); // this gives me the correct value.
function_that_needs_cart_limit();
},
error: function(output){
}
});
}
Declare this cartlimit with a global scope. Decalre this before the function starts
var cartlimit;
function get_cart_limit() {
$.ajax({
...................
Here your cartlimit will be declared only after the ajax function get success .
But execution of another scripts may take before this success. So it will get undefined
Your can pass your output data to the specified function like this
var cartlimit = get_cart_limit(output);
Having some trouble with AJAX/JQuery. Here is the context of my problem followed by a code sample:
What I am attempting to do is call a PHP script called getInfo.php and check whether or not some data is contained within a database. I can write queries easily enough but in terms of the code sample below how can I "tell" the success function to fail if it cannot find data in the database and run the error function instead?
$(document).ready(function(){
getInfo();
function getInfo(){
$.ajax({
type: "GET",
url: "getInfo.php",
data: "do=getInfo",
cache: false,
async: false,
success: function(result) {
$("#myInfo").remove();
alert("Data found");
},
error: function(result) {
alert("Data not found");
}
});
}
});
Any advice would be greatly appreciated. =)
The error handler is used to handle errors in your AJAX call.
You could echo 1 in your PHP script if the data was found and 0 if it was not found. Then you could use an if statement to determine what to do. For example:
success: function(result)
{
if(result == 1)
{
$("#myInfo").remove();
alert("Data found");
}
else
{
alert("Data not found");
}
},
"success" gets called when the returned code is a "200" (successfull request).
"error" gets called whenever another code is returned (e.g. 404, 500).
So I think you can do 2 things:
Let PHP return a 404 so the error function gets called
Let your getinfo.php return a boolean value (usually my approach)
{"success":true, ...}
The 'error' function you're using is for identifying and handling an AJAX error, not a script error. If the script you're calling is found, and it executes without terminating unexpectedly (ie, it has errors!), then its considered a success.
The best thing to do is have your getInfo.php script return something you can use within the success function; such as the number of rows in your result set or something - then you can check in success() whether you have data and code accordingly.
I think your getInfo.php page should just print SUCCESS or FAIL and in your success method do
success: function(result) {
if (result == 'SUCCESS')
{
$("#myInfo").remove();
alert("Data found");
}
else
{
alert("Data not found");
}
}