function votar(eid){
alert('inside function');
$.post(baseUrl+"/index/voto",{id:eid},function(e){
alert('after post');
I have this function here. On developer server, I get all working. No problems.
Once I upload to the production server I got only the first alert to show.
$.post(baseUrl+"/index/voto",{id:eid},function(e){
The baseUrl is correct.
The /index/voto is the correct path (the same as dev. server) to the voto method into index controller, id:edid is a json format yes, so, nothing wrong, and at the end, I just have that callback.
What possibilities do we have for the fact that the second alert is not showing on the production environment ?
Later on this same file, I have this function, the the same line of code, and it works perfectly:
function showDetails(eid, elemento){
$.post(baseUrl+"/index/details.campaign",{id:eid},function(e){
The only difference being the server side function it calls, "details.campaign" on one side, "voto" on the other.
Could we state that the issue must rely there, and only there ?
Update:
Here is, ipsis verbis, the full votar function:
function votar(eid) {
$.post(baseUrl+"/index/voto",{id:eid},function(e){
var divMsg = $("#msg");
var colunasFinalistas = $("#colunasFinalistas");
var rodape = $("#rodape");
var botaoVota = $("#votaEmGrande");
var html = "";
//no caso de votar pela primeira vez
if(e.msg == 1){
html = '<img src="'+baseUrl+'/lib/img/obrigadoParticipacao.png" alt="pdf" />';
rodape.removeClass("margemSeparadorRodape");
colunasFinalistas.hide();
}else if(e.msg == 3){
//no caso ja ter votado - se não existir nenhum elemento já:
if ($('#votoJaContabilizado').length == 0) {
botaoVota.after('<p id="votoJaContabilizado">O teu voto já foi contabilizado.</p>');
}
} else if(e.msg == 2){
//no caso da equipa nao existir
html = '<img src="'+baseUrl+'/lib/img/equipaNaoExiste.png" alt="pdf" />';
colunasFinalistas.hide();
} else{
//no caso de outro erro
html = '<img src="'+baseUrl+'/lib/img/erroEstranho.png" alt="pdf" />';
}
if (html != ''){
divMsg.html(html);
divMsg.show();
}
}, 'json');
}
At the risk of stating the obvious, if the callback method is not being called, it means the call was not successful.
$.post is a shorthand for the full $.ajax. Try using $.ajax and implement a function for error; this will show you if any errors are being thrown which your code is missing.
More information on $.ajax here: $.ajax
$.ajax({
type: 'POST',
url: baseUrl+"/index/voto",
data: //any required params go here,
success: function(data, textStatus, jqXHR) {
debugger;//hooray it worked!
},
error: function(jqXHR, textStatus, errorThrown) {
debugger;//there was an error
},
dataType: //type of data you are expecting back from the server
});
Try this, and tell us what you get:
var vote = $.post(baseUrl+"/index/voto",{id:eid},function(e){
alert('after post');
});
vote.error(function(e){
alert(e.statusText);
});
The third parameter in the $.post function is the success callback. So if it is working fine on developer server and not your production server, you got an issue with the response you are getting from the server. Have you had a look at what the response if from the server, because your ajax request isn't getting a success.
Inspect the response you are getting from your server (if any) and/or check if anything is done on the server when the $.post is submitted.
It seems like the request is failing in your development server. First, I would suggest showing the baseUrl in the first alert so you are sure the address is ok. If the address seems ok, set a function to handle the error with $.ajaxSetup or $.ajaxError before doing your $.post call
$.ajaxError(error: function (event, jqXHR, ajaxSettings, thrownError){
//try to find out the error
});
More into on $.ajaxError here.
Also, you can try using fiddler to examine the request from your server
Related
I am trying to send a package to admin-ajax.php to save the info into a $_POST variable to handle it in cart page... But the .ajax only fail...
var sendJsonA = {'value':'Llegando desde JSON'}
var ajaxurl = $('#ele_admin-ajaxURL').attr('data-value') //this is is "https://blablabla.com.ve/wp-admin/admin-ajax.php" -->>> err 400 bad request
// var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>'; doasnt work neither error 404 not found
jQuery.ajax({
data: sendJsonA,
url:ajaxurl,
type:'POST',
dataType:'json',
beforeSend: function(){
console.log('Se envia : '+JSON.stringify(sendJsonA))
},
success: function(response){
console.log('Se recibe : '+JSON.stringify(response))
}
})
.done(function( data, textStatus, jqXHR ) {
if ( console && console.log ) {
console.log( "La solicitud se ha completado correctamente."+ JSON.stringify(jqXHR) );
}
})
.fail(function( jqXHR, textStatus, errorThrown ) {
if ( console && console.log ) {
console.log( "La solicitud a fallado 2: " + JSON.stringify(jqXHR)+"----------------");//this is the only message i see in the console
}
});
function ele_inSelectionGrid()
{
echo "Mostrando texto antes de POST : ".$_POST['value'];
if ( isset( $_POST['value'] ) ) {
$numbers=$_POST['value'];
session_start();
$_SESSION['value']=$numbers:
die();
}
};
add_action('wp_ajax_ele_inSelectionGrid', 'ele_inSelectionGrid');
//this never happends
I dont know what to try...
Also I have to say that the security certificate of the host is expired for more than 100 days, every time I try to open the hosting it sends an error warning of unsafe site because it does not have a valid security certificate and it has not yet been renewed. This can intervene? Since ajax uses https. It happens that other woocommerce ajax applications work well because the console displays messages from finished XHR Loading from other applications
i dont know what else to try, to continue with this proyect.
You have to set the action property of the data you are sending via ajax, so that wordpress knows which wp_ajax_xxxx function to run.
For example in your case you want to call wp_ajax_ele_inSelectionGrid, so you must add a property "action": "ele_inSelectionGrid" to your data object, ie:
var sendJsonA = {'value':'Llegando desde JSON', 'action': 'ele_inSelectionGrid'};
There are some more examples in this question.
I'm using a simple if else statement to check for response from a POST form.
This is weird: I can check for response in form of error. Using elseif: or else: just does absolut nothing. Even though the response is valid.
Current code:
post_data = {
'someData': someData
}
// Ajax post data to server
$.post('register.php', post_data, function(response) {
if (response.type == 'error') {
if (response.errorType == 'something') {
$("#someThing").addClass('has-error');
}
} else {
window.location.reload(true);
}
}, 'json');
This is so weird. I've tried to insert alerts to really check if the else statement ran in background or something.
When the response is: "error" the error statement is executed.
However when the response is: success/done/cleared/failed etc. (whatever i try) nothing happens.
I receive the respond in console - but JQuery doesnt run the } else { ... statement.
Actually its not what you think.
The function is only called on Success. For error handling you have to chain another function
For example try this:
post_data = {
'someData':someData
}
// Ajax post data to server
$.post('register.php', post_data).done(function (response) {
// This is your success function
window.location.reload(true);
})
.fail(function (xhr, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
$("#someThing").addClass('has-error');
});
I hope this help you to understand that weird behavior :P
jQuery documentation have different handling functions for different jQuery version. so better to use $.ajax
I've been searching for a while for a solution to this problem. I've found many people with the same problem, but not the same solution.
The issue I'm having is that PHP is not returning any data to the AJAX function. The alert spits out data = undefined. As you can see, using return instead of echo is not the problem. I know that the PHP script I call completes correctly because the values are properly inserted into the database. No matter where I place the echo statement, I can't get it to return the value. Am I using the data variable incorrectly? Is returnValue not the proper variable to use? Has any of the functionality I've been trying to use been deprecated? I'm really at a complete loss. I can't see why this is failing.
//AJAX function
$("document").ready(function(){
$("#add_interest_form").submit(function(event) {
event.preventDefault();
$("#output").html("");
var values = $(this).serialize();
$.ajax
({
url: "./php/add_interest.php",
type: "POST",
data: values,
success: function(data) {
alert('data = ' + data.returnValue);
$("#output").html(data.returnValue);
},
error: function() {
alert('failed adding to database. Please try again or contact the Webmaster.');
}
});
});
});
//PHP snippet
echo 'Success!';
Just do alert('data = ' + data); instead of alert('data = ' + data.returnValue);.
I am using Code Igniter and I have the following Javascript function in my View. I have tried to echo values such as "error" from my handler function in the controller, but the "success" code is always ran in this function below instead.
Do I use echo or return to respond to the AJAX post? What value do I return for success and failure?
<script>
function removeDatacenter(id)
{
var cfm = confirm("Do you wish to delete this datacenter?");
if (cfm==true)
{
$.ajax({
type: "POST",
url: "<?=base_url()?>datacenters/remove_handler.php",
data: { id: id },
success: function(result)
{
document.location.href = document.URL + "?result=success";
},
error: function(result)
{
document.location.href = document.URL + "?result=failed";
}}
);
}
};
</script>
The success-method runs if the ajax-request was successfully sent to your script. It does not say anything about what the request returned.
If you simply do echo "error"; in your PHP-script, you can check the value in the success-method like this:
success: function(response) {
if (response == "error") {
document.location.href = document.URL + "?result=failed";
}
else {
document.location.href = document.URL + "?result=success";
}
}
Edit: People tend to use json_encode in the PHP-code and decode the json-string to an object in the javascript-code. That way you can send more structured data from your script.
Any text you echo will be seen, by AJAX, as a success. Even if it's the word "error". In order for you to trigger the Javascript error handler, you need to trigger some sort of actual HTTP error. If you're just trying to trigger an error for testing purposes, you could throw an exception in your controller. Or point the AJAX request to a URL that doesn't exist on your server (then you'd get a 404 error).
By the way, the error callback you have in your Javascript is slightly off on the API. It might not matter depending on what you do in the error handler, but here's the full call:
error: function(xmlHttpRequest, textStatus, errorThrown) {
//handle error here
}
$(document).ready(function(){
var temp='getUser';
$.ajax ({
type:'GET';
url: 'listdetails.php?ud=temp';
success:function(data)
{
alert(data);
}
});
});
By using this jquery , i am calling the same page "listdetails.php"(ie:this jquery is in listdetails.php).This is the code i entered at the begining of the page
if($_GET['ud'] =="getUser")
{
echo "ok";
}
When i am loading the page it is showing the error " Notice: Undefined index: ud in C:\wamp\www\listdetails.php on line 8"
ie: variable ud is undefined.How can i avoid this error.I think , if condition need to check only when the page request is ajax,Is it possible to check page request is ajax?
Use isset
if(isset($_GET['ud']) && $_GET['ud'] =="getUser")
{
echo "ok";
}
To check specifically for AJAX requests, try
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
But HTTP headers can easily be spoofed.
You will definetly not get in the if loop for $_GET bcoz the url of ajax is not properly made. I have written the code below, check it
var temp='getUser';
$.ajax ({
type:'GET',
url: 'listdetails.php?ud='+temp, // your code --- url: 'listdetails.php?ud=temp';
success:function(data)
{
alert(data);
}
});