I cannot get $_POST in php from js ajax in wordpress - javascript

This is my php file:
add_action( 'wp_ajax_mon_action', 'mon_action' );
add_action( 'wp_ajax_nopriv_mon_action', 'mon_action' );
function mon_action() {
if (isset($_POST["form_data"])) {
$field1=$_POST["form_data"];
}else{
$field1='heye';
}
var_dump($_POST);
die();
}
And this is js file:
function sayHelloWorld() {
window.alert('hey');
var div = document.getElementById('alt_textarea');
var div_tmp = document.createElement('div');
div_tmp.innerHTML = div.innerHTML;
var images = Array.prototype.slice.call(div_tmp.getElementsByTagName('img'));
var form_data = new FormData();
for (var i = 0; i < images.length; i++) {
var altImage = document.createTextNode("articleImage_" + i);
images[i].parentNode.insertBefore(altImage,images[i]);
images[i].parentNode.removeChild(images[i]);
form_data.append('eyecatch[]',images[i].src);
};
form_data.append('body',div_tmp.innerHTML);
jQuery.ajax({
url: 'admin-ajax.php',//I wrote absolute path here.
type:'POST',
data: {
'action': "mon_action",
'form_data': form_data
},
timeout:10000
}).done(function(data) {
window.alert(data);
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
window.alert("error");
});
}
But var_dump($_POST) did not work.
My window.alert stops only with 'hey'.
When I change to "formdata: 'some strings'" in data in js file, I can use var_dump($_POST).
So my question is why I cannot use $_POST when I use these files.
Please tell me.

Related

The function requires a field to be completed live to run

I'm using WooCommerce. The checkout form has two fields hidden (latitude and longitude). To show the shipping price, I'm using an API. I created a function of class new Address( $dato1, $dato2 ); in test.php. This needs the information from AJAX (latitude and longitude) when the customer completes this in the same page. How I can modify this to work?
function shipping($rates){
...
$dato2 = $_POST['dato1lat'];
$dato3 = $_POST['dato2long'];
$origen = new Address( $dato1, $dato2 );
$destino = new Address( -85.582, -58.585 );
$order = new Order();
$order->setAddresses( [$origen, $destino] );
$orderEstimado = $api->estimateOrderPrice( $order );
$shipping_cost = $orderEstimate['total']['amount'];
WC()->session->set( 'shipping_city_cost', $shipping_cost );
foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ) {
WC()->session->set( 'shipping_for_package_' . $package_key, false );
}
//Price
add_filter( 'woocommerce_package_rates', 'adjust_shipping_rate', 50 );
function adjust_shipping_rate( $rates ){
foreach ($rates as $rate) {
$cost = $rate->cost;
$rate->cost = WC()->session->get( 'shipping_city_cost' );
}
return $rates;
}
My Javascript code:
var dato1lat = $('#billing_billing_lat').val();
var dato2long = $('#billing_billing_lon').val();
$.ajax({
data:{ dato1lat: lat,dato2long: lng},
url:"/wp-content/plugins/test.php",
contentType: "application/json",
success: function(output) {
alert(output);
}
});
jQuery('body').trigger('update_checkout');
Thanks!
I see a wrong variable in ajax call data.
Could you try this;
Change:
data:{ dato1lat: lat,dato2long: lng},
with:
data:{dato1lat: dato1lat,dato2long: dato2long},
Because of:
var dato1lat = $('#billing_billing_lat').val();
var dato2long = $('#billing_billing_lon').val();
EDIT:
I found another problem, change your variables in your php file;
$dato1 = $_POST['dato1lat'];
$dato2 = $_POST['dato2long'];
$origen = new Address( $dato1, $dato2 );
In comments, you asked an ajax sensitive to change if I understood correctly.
Here is codes which I use in these situation
$('.yourClasswhichInputs').on('change keyup paste', function () {
var dato1lat = $('#billing_billing_lat').val();
var dato2long = $('#billing_billing_lon').val();
$.ajax({
url: "test.php",
type: "POST",
data: {dato1lat:dato1lat, dato2long:dato2long},
success: function(output){
alert(output);
}
});
});

Fetching PHP Data with Javascript and assign it to an array

I've got a php script with collects data from a server and displays it in an array and after that as a json with the function.
echo json_encode($result);
Now I want to access that array with my javascript and display it. It should be saved in a var as an array so it should look like:
data = [ "xxxx" , "ssss",];
But I guess I can simply put in my function which gets the array data instead so it'd be:
data = myfunction ;
What I've tried so far:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
};
oReq.open("get", "http://myserver.com/myscript.php", true);
oReq.send();
and
function getdata(url) {
jQuery.ajax(
{
type: "GET",
url: "http://myserver.com/myscript.php/",
dataType: "text",
success: function (response) {
var JSONArray = jQuery.parseJSON(response);
connsole.log(JSONArray);
}
});
}
But none seems to work and I get displayed 'undefined' instead of my arrays.
Would be really great if somebody has some ideas on that and can help me out.
Edit:
Since we are getting nowhere here's my php code:
<?php
error_reporting(0);
$html = file_get_contents("url here");
$dom = new DOMDocument();
$dom->loadHTML($html);
$tbodyRows = $dom->getElementsByTagName( 'tbody' )
->item( 0 ) // grab first tbody
->getElementsByTagName( 'tr' );
$result = array();
foreach( $tbodyRows as $tbodyRow )
{
$result[] = $tbodyRow->getElementsByTagName( 'td' )
->item( 2 ) // grab 3rd column
->nodeValue;
}
echo json_encode($result);
?>
Try this code:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "text",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
Open the browser's console, and let me know about its contents. If you don't see Error or Success, your code isn't actually executing
I have done a similar thing earlier. I will describe it and I wish it will help you.
In the following code (get_categories.php), I am retrieving data from the database and add them to an array. Then return it by encoding as a JSON.
$sql = "SELECT category_name FROM category;";
$dataArray = [];
$result = $connection->query($sql);
if ($result) {
while ($row = $result->fetch_assoc()) {
$dataArray[] = $row;
}
echo json_encode($dataArray);
}
Then in my Javascript code, I can get the data as follows.
$.ajax({
url: "/get_categories.php",
type: "GET",
dataType: "json",
success: function (categories) {
for (var i = 0; i < categories.length; i++) {
console.log(categories[i]);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// Error handling code
}
});

Ajax jQuery firing multiple time display event for the same result

What I'm trying to do, is to simply display 5 posts returned from WordPress.
What jQuery does is that it displays me this 5 posts, 7 times.
Inside my_response.posts looks like:
Maybe my function is wrong, or I should remember about something, when doing ajax request to WordPress.
Any idea why this happens?
jQuery('span.main-nav-text').click(function(ev) {
ev.preventDefault();
//var slug = '';
//var trimmed = jQuery.trim(jQuery(this).parent().children()[0].innerHTML);
//slug = trimmed.replace(/[^a-z0-9-]/gi, '-').
// replace(/-+/g, '-').
// replace(/^-|-$/g, '');
// Information of our Request
var data = {
type:"POST",
'action': 'fyc_qet_menu_option',
'post_type': 'blog',
'qty': -1
};
jQuery.post( callajax.ajaxurl,data).done(
function (response){
var cipka=[];
jQuery('div.blog-entry').empty();
console.log(response);
var my_response =jQuery.parseJSON(response);
console.log(my_response.posts);
for(var i=0;i<my_response.posts.length;i++)
{
jQuery('div.blog-entry').html(my_response.posts[i]["post_date"]);
jQuery('div.blog-entry').html(my_response.posts[i]["post_title"]);
jQuery('div.blog-entry').html(my_response.posts[i]["post_content"]);
}
// jQuery.each(my_response.posts,function(index,element){
//// console.log(element["post_title"]);
// cipka.push("<a href="+element["guid"]+">");
// cipka.push(element["post_title"]+"<br />");
// cipka.push(element["post_content"].substring(0,220)+"...<br />");
// cipka.push("</a>");
// });
}
);
});
Here ho i have change the index.php template
<?php get_template_part('inc/content'); ?>
<?php endwhile; else : ?>
<div class="margint30"><h4><?php echo __('Not Post Found!','2035Themes-fm') ?></h4></div>
<?php endif; ?>
<?php Theme2035_pagination(); ?>
</div>
and here how i have changed jQuery function:
jQuery('span.main-nav-text').click(function(ev) {
ev.preventDefault();
//var slug = '';
//var trimmed = jQuery.trim(jQuery(this).parent().children()[0].innerHTML);
//slug = trimmed.replace(/[^a-z0-9-]/gi, '-').
// replace(/-+/g, '-').
// replace(/^-|-$/g, '');
// Information of our Request
var data = {
type:"POST",
'action': 'fyc_qet_menu_option',
'post_type': 'blog',
'qty': -1
};
jQuery.post( callajax.ajaxurl,data).done(
function (response){
var cipka=[];
jQuery('div.dynamic-blog-posts').empty();
console.log(response);
var my_response =jQuery.parseJSON(response);
console.log(my_response.posts);
for(var i=0;i<my_response.posts.length;i++)
{
jQuery('div.dynamic-blog-posts').html(my_response.posts[i]["post_date"]);
jQuery('div.dynamic-blog-posts').html(my_response.posts[i]["post_title"]);
jQuery('div.dynamic-blog-posts').html(my_response.posts[i]["post_content"]);
}
// jQuery.each(my_response.posts,function(index,element){
//// console.log(element["post_title"]);
// cipka.push("<a href="+element["guid"]+">");
// cipka.push(element["post_title"]+"<br />");
// cipka.push(element["post_content"].substring(0,220)+"...<br />");
// cipka.push("</a>");
// });
}
);
});

Sending data and file with ajax and jquery

I know that there is a topic speaking about this
I followed it but i still have problem with my code
Here is my code
var id_dossier = $('#jform_id').val();
var date_facture = $('#jform_date_facture').val();
var date_paiement_facture = $('#jform_date_paiement_facture').val();
var mode_paiement_facture = $("select#jform_mode_paiement_facture option").filter(":selected").val();
var idBanque = $("select#jform_id_banque option").filter(":selected").val();
var idCompte = $("select#jform_id_compte option").filter(":selected").val();
var cheque_facture = $('#jform_cheque_facture').val();
var montant_cheque = $('#jform_montant_cheque').val();
var numero_facture = $('#jform_numero_facture').val();
var numero_retenu_source = $('#jform_numero_retenu_source').val();
var echeance = $('#jform_valeur_echeance').val();
var document_facture = document.getElementById('facture_document');
the document_facture is the file input
Then I put the data in a other var I called donnee
var donnee ={
'id_dossier' : id_dossier,
'date_facture' : date_facture,
'date_paiement_facture' : date_paiement_facture,
'mode_paiement_facture' : mode_paiement_facture,
'id_banque' : idBanque,
'id_compte' : idCompte,
'cheque_facture' : cheque_facture,
'montant_cheque' : montant_cheque,
'numero_facture' : numero_facture,
'numero_retenu_source' : numero_retenu_source,
'echeance' : echeance,
'document_retenu_source' : document_retenu_source
};
Well in the other question there is this line of code and I dont know what is and how could I replace it in my code
var formData = new FormData($(this)[0]);
so I replace it with this
var formData = new FormData();
formData.append('documents', document_facture.files[0]);
And I add it in the data of the Ajax Request
$.ajax({
type: 'post',
cache: false ,
url: 'index.php?option=com_tktransit&task=dossier.genererFacture',
data: {donnee:donnee,formData:formData },
success: function(resp)
{
if(resp == "1")
{
ajax_result_message("<?php echo JText::_( 'COM_TKTRANSIT_DOSSIER_FACTURE_GENERER' ); ?>",0,'facture');
afficher_button(2);
$('#td_facturation').html("<?php echo JText::_( 'COM_TKTRANSIT_FACTURE_DEJA_FACTURER' ); ?>");
$('#td_check_facturation').hide();
generate_pdf(id_dossier);
}
else if(resp == "2")
{
ajax_result_message("<?php echo JText::_( 'COM_TKTRANSIT_DOSSIER_FACTURE_NUMERO_FACTURE_EXISTE_DEJA' ); ?>",1,'facture');
}
else
ajax_result_message("<?php echo JText::_( 'COM_TKTRANSIT_DOSSIER_FACTURE_ERREUR_GENERER_FACTURE' ); ?>",1,'facture');
$("#ajax-facture-image_loader").hide();
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
ajax_result_message("<?php echo JText::_( 'COM_TKTRANSIT_DOSSIER_FACTURE_ERREUR_GENERER_FACTURE' ); ?>",1,'facture');
$("#ajax-facture-image_loader").hide();
}
});
well When I click on the button to call the ajax function I got this error
TypeError: 'append' called on an object that does not implement interface FormData.
Any help please
You should placed all your variables on the form in the html page, so, the line
var formData = new FormData($(this)[0]);
will become
var formData = new FormData($('#yourFormUniqueId')[0]);
I think you can find more details by this answer

ajax function not returning right data

I'm trying to get the proper information out of this ajax function (thumbnail image, the owner of the image). I dont think it knows what data.images[i].imgurl and data.images[i].username is.
ajax.php
require_once 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('123456');
// Receive AJAX request and create call object
$tag = $_GET['tag'];
$maxID = $_GET['max_id'];
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";
// Receive new data
$media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));
// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
$images[] = array(
"imgurl"=>$data->images->thumbnail->url,
"username"=>$data->user->username;
);
}
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $images,
));
search.php
<script>
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('#photos').append('<div id=box><div class=mainimg><img src="'+ data.images[i].imgurl +'"></div><div class=\"pfooter\">'+ data.images[i].username +'</div></div>');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
..
In your search.php file you have to close the variable statement with a semicolon.
Change this line:
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
to this:
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'); // <-- added semicolon

Categories