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.
Related
I want to create a session var. I have a web page with some tabs that don't recharge when I active one another. So, I don't know how to set my session var.
Indeed, my first tab will generate the session var when the user submit the form into this tab. I'm trying to do it with ajax. So in my ajax file, I have this to set my var :
if(pg_num_rows($res) == 1)
{
$flag=false;
$message = "L'identifiant de l'essai existe déjà dans la base";
array_push($tab_erreur,$cpt,$message);
}else {
$sessionIDEssai=$ligne[1]; //Here is my session var
}
After, I want to return that value with an other like this :
echo json_encode($tab_erreur),$sessionIDEssai;
First of all I don't know if it's correct, because I can't get it in my callback function.
function insert_essai_callback(responseObject,ioArgs) .
{
var jsonobject = eval(responseObject);
console.log(jsonobject);
}
I can get the first var $tab_erreur.
And after I don't know how to set my session var for all my tabs. I think that at the return of the ajax, I will get the value and I could set it and use it, but I'm not sure.
EDIT
I send an array in my ajax request like that :
$(document).ready(function(){
$('#submit_button_essai').click(function(){
$.post("ajax_insert_essai.php",{arr:data_essai}, insert_essai_callback,'json');
});
});
Ajax
$.ajax({
type : 'POST',
url : './session.php',
dataType: "json",
data: data,
success : function(data){},
error : function(){}
});
PHP
<?php
session_start();
$_SESSION['data']=$_POST['data'];
echo $_SESSION['data'];
?>
});
Data is what you send through a POST, now echo can return that data or a different amount of data to your Ajax request as a response.
Using, $.post():
$.post({
url: url,
data: data,
success: success,
dataType: dataType
});
However, $.ajax(), is much much better, since you have more control over the flow, and if success do this etc.
I added the following to my functions.php file:
add_action('wp_ajax_send_email', 'send_email_callback');
add_action('wp_ajax_nopriv_send_email', 'send_email_callback');
So i added the following callback function:
send_email_callback()
{
//do some processing
echo json_encode(array('response'=>'Ya man it worked.'));
//return control back to *-ajax.php
}
This is what is returned to my javascript :
{"response":"Ya man it worked."}0
So ofcourse when it reaches the $.parseJSON( msg ) line I get Uncaught SyntaxError: Unexpected number.
var request = $.ajax({
url: "/wp-admin/admin-ajax.php",
method: "POST",
data: { action : 'send_email', P : container },
dataType: "html"
});
request.done(function( msg ) {
var obj = $.parseJSON( msg );
console.log(obj.response);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
So where does this 0 come from? admin-ajax.php
it says on line 97:
// Default status
die( '0' );
Why is this here, why am I reaching the die('0') line? Shouldnt it be just die() so it doesnt mess up my response?
Seems the only way to fix this is either modify admin-ajax.php or simply die() at the end of my send_email_callback() function.
In WordPress AJAX actions, you aren't supposed to return the response, but echo the response and call die yourself. WordPress will continue to call all of the AJAX registered callbacks until one of the callbacks kills the execution, with the final one dieing with the response of 0.
Example from WordPress Codec AJAX in Plugins
<?php
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die(); // this is required to terminate immediately and return a proper response
}
I have an AJAX function which POST data to a PHP handler. I echo back either "success" or "failure" from PHP to determine if it was completed as intended. Unfortunately I am not used to JS/AJAX and have trouble finding documentation that answers my questions.
Do I need to JSON encode the response? I only check for .done() in my AJAX function, should I also check success and failed? My code inside of .done() which is just an alert box isn't working, despite the functionality in the PHP handler running without issue.
JS/AJAX:
<script type="text/javascript">
function powerSignal(device, signal)
{
var cfm = confirm("Do you wish to ___ the server?");
if (cfm==true)
{
$.ajax({ type: "POST", url: "https://domain.net/modules/power_functions.php", data: { device: device, 'power_signal': signal }}).done(function(result)
{
alert("success!");
});
}
}
</script>
PHP:
if ( isset($_POST["device"]) && isset($_POST["power_signal"]) )
{
$deviceid = $_POST["device"];
$signal = $_POST["power_signal"];
//API: Get Device Inventory
$url = 'http://domain.net/dp/api/set_device_power_status';
$fields = array('deviceid' => urlencode($deviceid), 'power_signal' => urlencode($signal));
$result = curl_get($url, $fields);
$json = json_decode($result);
$status = $json->{'status'};
if ($status == "success")
{
echo "success";
}
echo "failed";
}
the content of the result variable will be what the server sends back, you'll have to test it :
$.ajax({ type: "POST", url: "https://domain.net/modules/power_functions.php", data: { device: device, 'power_signal': signal }}).done(function(result)
{
if(result=='success'){
alert("success!");
}else{
alert("failure!");
});
To answer the comment below, here is how I do in my current project with a simple get request :
$.get( "/getResult/"+data, function( results ) {
$('.popin_content').html('<p>Vos documents ont bien été créés :</p><br/><ul><li>Plan PDF</li><li>Devis PDF</li></ul>');
});
I'm new here and jQuery development, I have a question, Why can not I use the dataType:'json' nor $.parseJSON to handle a return of a query from PHP to AJAX (jQuery).
reader.js
$(function(){
//Modal form which encapsulates the loading of information occurs
var modal = $('.modal');
//Encapsulates the existing list or the list elements, each element has an "edit" button
var lista = $('.lista');
lista.on('click','.actionedit',function(){
var id = $(this).attr('href');
var li = lista.find('li[class*="j_'+id+'"]');
$.ajax({
url: 'php/controller.php',
data: 'acao=consulta&editid='+id,
type: 'POST',
//contentType: 'application/json; charset=utf-8;',
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert('Erro: "'+ xhr.status + '"\nMensagem: " ' + thrownError +'"');
},
beforeSend: function(){
li.css("background","#0F6") },
success: function( carga ){
//alert( carga );
alert( carga.nome );
//modal.fadeIn("slow");
//modal.find('form span[class="filebar"]').text(carga.file);
//modal.find('form input[name="titulo"]').val(carga.title);
//modal.find('form textarea').append(carga.description;
},
complete: function(){ loader.fadeOut("slow"); },
});
return false;
});
});
controller.php
<?php
require_once("conexao.php");
switch($_POST['acao']){
case 'consulta':
//Validates query, that returns a json string...
$editid = $_POST['editid'];
$qr = "SELECT * FROM mod6_uploads WHERE id = '$editid'";
$ex = mysql_query($qr);
$st = mysql_fetch_array($ex);
//Return array in json format string for testing...
$u['file'] = 'File';
$u['title'] = 'File title';
$u['description'] = 'File Description';
echo json_encode($u);
break;
default:
echo 'Error querying';
}
Thus, the alert returns me the following message:
Error: "200"
Message: "SyntaxError: JSON.parse: unexpected character"
If I comment the dataType: "json", it returns me the following warning: undefined
And if I change the alert to "alert (carga.nome)" to "alert (load)", it returns me the following:
{"name": "File", "title": "File Title", "description": "File Description"}
Also, as I said earlier, if I use the $.ParseJSON or JSON.parse not have any return, or the error or the success.
Anyone out there have come across something like this?
If anyone could help me I would be very grateful!
I'd change this line:
data: 'acao=consulta&editid='+id,
By this:
data: {acao: 'consulta', editid: id},
As your id comes from an href, it would be better if it's automatically escaped.
Also, instead of this:
echo 'Error querying';
something like:
echo json_encode(array('Error querying'));
so it doesn't give JSON parse errors (return as javascript array of errors).
Also, ensure your mod6_uploads table has a nome field.
I see the rest is fine.
Cheers
PS: I suggest you to use a dev tool for debugging. One very easy is chrome's, just press F12, click the network tab and then run your ajax request.
If you use dataType:'json', success callback will only trigger if the server response is a valid JSON.
So if error callback is triggering, your response is 'populated' with extra data that makes JSON invalid.
In this case try to comment dataType:'json' and write in your success callback:
alert(carga)
or
console.log(carga)
This will output the server response and you will be able to see what's wrong with it.
Also if you deside to use JSON, try to use JSON everywhere in that file and avoid such code:
echo 'Error querying';
Otherwise you may get unexpected result
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