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);
}
});
});
Related
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.
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
}
});
I am storing my checkbox selections in an array then splitting each array and posting them using AJAX so my PHP function can use the posted id/ids to query my MySQL database.
First part of my JavaScript
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
alert(tbl);
This first part works as intended, where every time I click a checkbox the value is alerted.
AJAX post
$.ajax({
type: "POST",
url: "index.php",
data: "tbl=" + tbl
});
});
Finally my PHP
function describeTables() {
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}}
I don't get any vlaues of tbl even if I choose just one option. Why is this????
EDIT
My Checkbox
function showTables() {
if (isset ( $_GET ['db'] )) {
$db = $_GET ['db'];
$link = mysqli_connect ( 'localhost', 'root', '', $db );
$qry = "SHOW tables";
$tbl_list = mysqli_query ( $link, $qry );
echo '<ul>';
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
echo '<input type="checkbox" name="tbl[]" class="tbl_list" value="' . $row [0] . '" class="tablebox" />';
echo $row [0];
echo '<br>';
}
}
}
showTables ();
SECOND EDIT
After suggestions I have amended my code but now have a new problem where the page doesn't load #dbdisplay Below is my full JS code
if (!location.search.match(/db=[^&#]+/i)) {
$("#dbdisplay").show();
} else {
$("#qryDisplay").show();
}
$(document).on("change", ".checkbox", function () {
var db = $(this).val();
window.sessionStorage.setItem("db", db);
window.location.assign("index.php?db=" + db);
$("#dbdisplay").hide();
});
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
//alert(tbl);
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl': tbl }
});
});
The old function
/*
$(document).on("change", ".tablebox", function () {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
var yourDB = window.sessionStorage.getItem("db");
window.location.assign("index.php?db=" + yourDB + '&tbl=' + tbl);
});
*/
How do I fix this??
In ajax call, data has to be object data: {'tbl': tbl}
This should to the job
$.ajax({
type: "POST",
url: "someurl",
data: {"tbl=" + tbl}
});
http://api.jquery.com/jquery.getjson/
See here for documentation
First thing in your ajax call, data has to be object
data: {'tbl': tbl}
Secondly Ajax can't call php function directly
so your index.php file should be something like this without function
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}
You should use "{ }" with data
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl' : tbl}
});
or
$.ajax({
type: "POST",
url: "index.php&tbl="+tbl
});
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
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