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
Related
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);
}
});
});
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 knew so much duplicate question. But I don't know, how to upload it with complicated form with arrays in form. This is my html:
And this jquery:
function saveDraft(){
var scope = $('#scope').val();
var secrecy = $('#secrecy').val();
var priority = $('#prio').val();
var cc = $('#cc').val();
var subject = $('#form-field-subject').val();
var msg = $('.wysiwyg-editor')[0].innerHTML;
var attachment = document.getElementById('attachment');
var refnd = $('#refnd').val();
var refarsip = $('#refarsip').val();
var from = $('#from').val();
var approval = [];
$('.approval :selected').each(function(i, selected){
approval[i] = $(selected).val();
});
var receiver = [];
$('.for :selected').each(function(i, selected){
receiver[i] = $(selected).val();
});
$.ajax({
type: 'post',
url: '<?php echo $this->baseurl; ?>/memo/saveDraft',
data: {
scope : scope,
secrecy : secrecy,
priority : priority,
from : from,
approval : approval,
receiver : receiver,
cc : cc,
subject : subject,
msg : msg,
attachment : formData,
refnd : refnd,
refarsip : refarsip
}
Try this:
HTML:
<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>
JS:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php:
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
This will upload a single file to server. Make some changes so that you can upload multiple file as well.
I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});
I am trying to use json_encode so that my jquery ajax function can retrieve data from my php script however the array I am attempting to encode and retrieve is an array of objects
$la_uselessinfo = array();
$lv_cnt = 0;
$uselessinfo = pg_execute($gv_dbconn, "uselessinfo_cur", array());
while($la_row = pg_fetch_row($uselessinfo)) {
$la_uselessinfo[$lv_cnt]["uinf_idno"] = $la_row[0];
$la_uselessinfo[$lv_cnt]["uinf_desc"] = $la_row[1];
$lv_cnt = $lv_cnt + 1;
}
echo json_encode($la_uselessinfo);
I am trying to retrieve this using the jquery ajax function
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
success : function(data) {
//console.log(data);
console.log(data["uinf_desc"][0]);
},
error : function(log) {
console.log(log.message);
}
});
I am getting the following error
Uncaught TypeError: Cannot read property '0' of undefined
I can't tell if it's going wrong in the php code or the jquery code, what is the correct way to retrieve an array of objects?
Change your PHP to:
$la_uselessinfo = array();
$lv_cnt = 0;
$uselessinfo = pg_execute($gv_dbconn, "uselessinfo_cur", array());
while($la_row = pg_fetch_row($uselessinfo)) {
$la_uselessinfo[$lv_cnt]["uinf_idno"] = $la_row[0];
$la_uselessinfo[$lv_cnt]["uinf_desc"] = $la_row[1];
$lv_cnt = $lv_cnt + 1;
}
echo json_encode($la_uselessinfo); //$la_uselessinfo is already an array, no need to wrap it again, and doing so causes you to misjudge the depth of your array
Then change your jQuery to :
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
success : function(data) {
//console.log(data);
console.log(data[0]["uinf_desc"]); // this line changed
},
error : function(log) {
console.log(log.message);
}
});
To loop over your results do this:
// sample data
var data = [{
"uinf_idno": "1",
"uinf_desc": "website db "
}, {
"uinf_idno": "2",
"uinf_desc": "local apache "
}]
$.each(data,function(i,e){
var uinf_idno = e.uinf_idno;
var uinf_desc = e.uinf_desc;
$('#result').append('uinf_idno= '+uinf_idno+' and uinf_desc= '+uinf_desc+' <br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
dataType: "json",
success : function(data) {
console.log(data[0]["uinf_desc"]);
console.log(data[0]["uinf_desc"]);
},
It should be data[0]["uinf_desc"] as written in your PHP