Ajax not sending data to PHP script - javascript

I have a web app that is basically a huge form that will eventually be transformed into a pdf. When the form is submitted, all the input gets sent to a php file that stores them as variables to be added to the pdf. Some of the data I need on the pdf is calculated in JavaScript, so I am using ajax to send those calculated variables to the same php file that the form sends its data to. The ajax call is not sending the data to the php script. I tried to echo some of the variables, but nothing shows up. Here is my ajax call:
$.ajax({
url: 'FMpdf_values.php',
method: 'POST',
data: {elevChartImg : elevChartImg, azChartImg : azChartImg, power_rating : power_rating, antWeight : antWeight, antennaWithRadomeWeight : antWithRadomeWeight,
epa : epa, radome : radome, deicer : deicer, thetaCol : thetaCol, afAmpCol : afAmpCol, dbCol : dbCol, product : product, channelFM : channelFM,
antLongDescription : antLongDescription, antShortDescription : antShortDescription},
success:function(data){
console.log(data);
}
});
The PHP file is just setting the variables to $_POST['some_data'], then that file is included in the PHP file that creates the pdf. I am relatively new to both PHP and ajax, so I apologize if this is an easy fix. I am wondering if it is even possible to get values from the HTML form and ajax in the same file?
FMpdf_values.php:
<?php
//PHP file for getting the values needed for the PDF
//All html element variables are added here, while calculated values are passed through AJAX
header("Content-Type: application/json", true); //For accepting JSON data
//HTML Element Variables
$projectName = $_POST['projectTitle'];
$customer = $_POST['customer'];
$location = $_POST['location'];
$antModel = $_POST['tlantennaModel'];
$specCode = $_POST['specNumber'];
$createdBy = $_POST['completedBy'];
$notes = $_POST['notes'];
$date = date("F j, Y");
$revDate = $_POST['revisionDate'];
$freq = $_POST['channelNum'];
$wavelength = "11807.22891";
$gainVal = $_POST['tlhorPeakPower'];
$erpVal = $_POST['tlhorERP'];
$beamtilt = $_POST['beamTiltVal'];
$firstNull = $_POST['firstNull'];
$secondNull = $_POST['secondNull'];
$rfInput = $_POST['rfInputs'];
$antennaHeightFt = $_POST['antennaHeightFt'];
$antennaHeightMt = $_POST['antennaHeightMt'];
$CORHeightFt = $_POST['CORHeightFt'];
$CORHeightMt = $_POST['CORHeightMt'];
$ovrHeightFt = $_POST['overallHeightFt'];
$ovrHeightMt = $_POST['overallHeightMt'];
$vertLineType = $_POST['tlTypeVertSelect'];
$vertLineLengthFt = $_POST['tlvertft'];
$vertLineLengthMt = $_POST['vertLengthMeters'];
$vertAttenFt = $_POST['tlvertatten'];
$vertAttenMt = $_POST['tlVertAttenMt'];
$horLineType = $_POST['tlTypeHorSelect'];
$horLineLengthFt = $_POST['tlhorft'];
$horLineLengthMt = $_POST['horLengthMeters'];
$horAttenFt = $_POST['tlhoratten'];
$horAttenMt = $_POST['tlhorattenmt'];
$transLineLosskW = $_POST['tranlinelossKW'];
$transLineLossdB = $_POST['tranlinelossdb'];
$transLineEff = $_POST['tlefficiency'];
$antInputPowerkW = $_POST['antennaInputPowerkw'];
$antInputPowerdB = $_POST['antennaInputPowerdBk'];
$isoTranLosskW = $_POST['isoLosskw'];
$isoTranLossdB = $_POST['isoLossdB'];
$filterLosskW = $_POST['filterLosskw'];
$filterLossdB = $_POST['filterLossdB'];
$systemLosskW = $_POST['systemLosskw'];
$systemLossdB = $_POST['systemLossdB'];
$totalLosskW = $_POST['totallosskw'];
$totalLossdB = $_POST['totallossdB'];
$TPOkW = $_POST['poweroutputkw'];
$TPOdB = $_POST['poweroutputdB'];
$systemEff = $_POST['otherSystemEfficiency'];
//Variables from AJAX
$elevChartImg = $_POST['elevChartImg'];
$azChartImg = $_POST['azChartImg'];
$power_rating = $_POST['power_rating'];
$antWeight = $_POST['antWeight'];
$antWithRadomeWeight = $_POST['antWithRadomeWeight'];
$epa = $_POST['epa'];
$radome = $_POST['radome'];
$deicer = $_POST['deicer'];
$thetaCol = $_POST['thetaCol'];
$afAmpCol = $_POST['afAmpCol'];
$dbCol = $_POST['dbCol'];
$product = $_POST['product'];
$channelFM = $_POST['channelFM'];
$antLongDescription = $_POST['antLongDescription'];
$antShortDescription = $_POST['antShortDescription'];
//ThetaCol, afAmpCol, & dbCol are currently JSON encoded objects
$thetaCol = json_decode($thetaCol);
$afAmpCol = json_decode($afAmpCol);
$dbCol = json_decode($dbCol);
die(print_r($_POST));

You are basically calling your PHP script 2 times.
At the first time you are firing up an ajax call (Your php script executes at the server side and PDF generator code runs and generates invalid PDF, as you don't have the form data yet)
Second time the actual form is submitted, your PHP script executes again, this time you don't have the AJAX data, so again the target PDF will be invalid)
Instead of sending data in 2 parts (one part using form POST and another part using AJAX POST), have some hidden fields in your form, fire the javascript calculation function on click of your submit button, fill up the hidden fields and then submit the form. This way you get all the data at one go.
Let me know if that make sense and if you are able to proceed ahead or do you need some sort of code samples..

Related

How can I send the .xlsx file created on the client to mail?

Here I`m creating a file using JQuery plugin table2excel:
$('.btn-primary-1').on('click', function(){
$("#table1").table2excel({
name:"Worksheet Name",
filename:"fileName",//do not include extension
fileext:".xlsx", // file extension
preserveColors:true
});
});
This is how I fill the table:
$('.one_busket').on('click', function(){
let $tovar1 = $('.title_one').html();
let $value1 = $('.one_number').val();
let $itog1 = $('.end1').text();
$('.tbody1').append('<tr><td class="td_tovar">'+$tovar1+'</td>'+'<td>'+$value1+'</td><td class="td_itog" id="td">'+$itog1+'</td></tr>');
});
I can't just send the dynamically created table, so I decided to send an .xlsx file by mail. Now I need not just download the file, but send this file by mail via PHP. How can i do this?
P.S
This is what a crutch looks like now, which can only send 6 goods.
PHP:
$input_tovar1 = $_POST['input_tovar1'];
$input_value1 = $_POST['input_value1'];
$input_itog1 = $_POST['input_itog1'];
$input_tovar2 = $_POST['input_tovar2'];
$input_value2 = $_POST['input_value2'];
$input_itog2 = $_POST['input_itog2'];
$input_tovar3 = $_POST['input_tovar3'];
$input_value3 = $_POST['input_value3'];
$input_itog3 = $_POST['input_itog3'];
$input_tovar4 = $_POST['input_tovar4'];
$input_value4 = $_POST['input_value4'];
$input_itog4 = $_POST['input_itog4'];
$input_tovar5 = $_POST['input_tovar5'];
$input_value5 = $_POST['input_value5'];
$input_itog5 = $_POST['input_itog5'];
$input_tovar6 = $_POST['input_tovar6'];
$input_value6 = $_POST['input_value6'];
$input_itog6 = $_POST['input_itog6'];

SuiteScript Create File In Client Side Script

I'm trying to create a file in the File Cabinet and write to it in a Client Script. Checking the API reference, I see that all the File objects are Server-side only.
Does that mean you can't create and write to a file in a Client script? I tried to use the code in my Client script anyway, but got the error:
Fail to evaluate script: {"type":"error.SuiteScriptModuleLoaderError","name":"{stack=[Ljava.lang.Object;#59c89ae9, toJSON=org.mozilla.javascript.InterpretedFunction#5a4dd71f, name=MODULE_DOES_NOT_EXIST, toString=org.mozilla.javascript.InterpretedFunction#1818dc3c, id=, message=Module does not exist: N/file.js, TYPE=error.SuiteScriptModuleLoaderError}","message":"","stack":[]}
When I tried to save it in NetSuite as the script file. Does the above mean that the N/File object can't be loaded in a Client script?
Can I write to a file in a Client script?
Create a Client Script - this Script will contain the function to call the Suitelet and pass along information from the current record/session if needed.
function pageInit{
//required but can be empty
}
function CallforSuitelet(){
var record = currentRecord.get();
var recId = record.id;
var recType = record.type
var suiteletURL = url.resolveScript({
scriptId:'customscriptcase3783737_suitelet',// script ID of your Suitelet
deploymentId: 'customdeploycase3783737_suitelet_dep',//deployment ID of your Suitelet
params: {
'recId':recId,
'recType':recType
}
});
document.location=suiteletURL;
}
return {
CallforSuitelet : CallforSuitelet,
pageInit : pageInit
}
Create a Suitelet - this script will create the file
function onRequest(context) {
var requestparam = context.request.parameters;
var recId = requestparam.recId; //the same name of the fields specified in url.resolveScript parameters from Client Script
var recType = requestparam.recType;
var objRecord = record.load({
type: record.Type.___,//insert record type
id: recId
});
var content = 'Insert Content Here';
var xml = "<?xml version=\"1.0\"?>\n<!DOCTYPE pdf PUBLIC \"-//big.faceless.org//report\" \"report-1.1.dtd\">\n";
xml += "<pdf>\n<body font-size=\"12\">\n<h3>Sample PDF</h3>\n";
xml += "<p></p>";
xml += content;
xml += "</body>\n</pdf>";
context.response.renderPdf({xmlString: xml});
}
return {
onRequest: onRequest
}
As you've already discovered, server-only modules can't be called from client-side scripts directly, but this can be done via a Suitelet. You will need to decide how the Suitelet does it's work. An example of the principal at work can be found here and here

Sending Object Data from AJAX to PHP

I'm trying to send data to a php file to save in database, but I don't have any response. If a checkbox is check, the [obj][idCheckbox] = 1, else [obj][idCheckbox] = 0.
File that sends
var i=0;
var objetoTodasPermissoes = function(){};
var objTodasPermissoes = new objetoTodasPermissoes();
$.each($(".classePermissoes"), function(){
objTodasPermissoes[$(this)[0].id] = 0
i++;
});
$.each($(".classePermissoes:checked"), function(){
alert('ok');
objTodasPermissoes[$(this)[0].id] = 1;
});
console.log(objTodasPermissoes);
$.each($("#userList tr"),function(){
alert(this.id);
var iduser = this.id;
$.ajax({
url:'../json/usuarioperm/savePermissions.php',
data:({
idusuario:iduser,
objTodasPermissoes:objTodasPermissoes,
}),
success:function(a){
Alert("Saved!");
}
});
});
}
the savePermissions.php file.
$iduser = $_POST["iduser"];
$perm_usuarios = $_POST["objTodasPermissoes"]["perm_usuarios"];
$perm_importar = $_POST["objTodasPermissoes"]["perm_importar"];
$perm_log = $_POST["objTodasPermissoes"]["perm_log"];
$perm_proto = $_POST["objTodasPermissoes"]["perm_proto"];
$perm_limpeza = $_POST["objTodasPermissoes"]["perm_limpeza"];
$perm_lixeira = $_POST["objTodasPermissoes"]["perm_lixeira"];
$perm_relatusuarios = $_POST["objTodasPermissoes"]["perm_relatusuarios"];
$perm_deptos = $_POST["objTodasPermissoes"]["perm_deptos"];
$perm_deptospastas = $_POST["objTodasPermissoes"]["perm_deptospastas"];
$perm_empresas = $_POST["objTodasPermissoes"]["perm_empresas"];
mysql_query("UPDATE hospital.users set
perm_usuarios=".$perm_usuarios.",
perm_importar=".$perm_importar.",
perm_log=".$perm_log.",
perm_proto=".$perm_proto.",
perm_limpeza=".$perm_limpeza.",
perm_lixeira=".$perm_lixeira.",
perm_relatusuarios=".$perm_relatusuarios.",
perm_deptos=".$perm_deptos.",
perm_deptospastas=".$perm_deptospastas.",
perm_empresas=".$perm_empresas." where id=".$iduser) or die (mysql_error());
Thank you.
PHP is kind of interesting in that it doesn't pull from $_POST like other forms when Ajax is involved. You actually will need to read the input from php://input
Here is a tiny example
$data = file_get_contents("php://input");
$response = json_decode($data, true ); // True converts to array; blank converts to object
$emailAddr = $response["email"];
Hopefully you can apply that successfully.
Edit: You can add the filter_var command to strip bad characters and sanitize the input.
$emailAddr = filter_var($response["email"], FILTER_SANITIZE_EMAIL);
$firstName = filter_var($response["firstName"], FILTER_SANITIZE_STRING);
While debugging this I would highly recommend using Chrome's Developer mode with the 'network' tab. Find your ajax call near the bottom and you can view exact header info.

How do I run a .php function file from a .js file

How do I send data from a JavaScript file to a PHP file so that it does what it needs to do in the PHP server side. I want to send a SMS and my JavaScript is reading all the data that is coming though so all that is left is that my PHP activates and sends the data in a SMS which is already done with my PHP file. I just need to make them connect to be able to send.
Can PHP handle functions? That is what I am trying to do here by sending the data to a function in PHP from my .js file. If not, how do I send them via post?
.js file:
render : function(template,params){
var arr = [];
switch(template){
case 'smsLine':
arr = [
'<div class=" sms-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
'" width="23" height="23" onload="this.style.visibility=\'visible\'" />',
'</span><span class="author">',params.author,
':</span><span class="text">',params.text,
':</span><span class="text">',params.to,
'</span><span class="time">',params.time,'</span></div>'];
///////////////////////////////HERE/////////////////////////////////
//this is where I want to use a function that is in a php file
sendSMS(params.author, params.text, params.time, params.to);
///////////////////////////////HERE////////////////////////////////
break;
}
return arr.join('');
}
This is the function that I want to use in my PHP file.
.php file:
function sendSMS($from, $message, $time, $to){
$objGsm = new COM("AxSms.Gsm", NULL, CP_UTF8 );
$objGsm->LogFile = sys_get_temp_dir()."Gsm.log";
//Windows default: 'C:\Windows\Temp\Gsm.log'
//Form submitted
$obj;
$strMessageReference;
$objSmsMessage = new COM("AxSms.Message", NULL, CP_UTF8 );
$objSmsConstants = new COM("AxSms.Constants" , NULL, CP_UTF8 );
$strName = 'Modem';
$strPincode = '';
$strRecipient = '$number';
$iDeviceSpeed = '0';
$objGsm->Clear();
$objGsm->LogFile = '';
$objGsm->Open($strName, $strPincode, $iDeviceSpeed);
if ($objGsm->LastError != 0){
$strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);
$objGsm->Close();
}
else{
//Message Settings
$objSmsMessage->Clear();
$objSmsMessage->ToAddress = $to;
$objSmsMessage->Body = $message;
$objSmsMessage->DataCoding = $objSmsConstants->DATACODING_UNICODE;
//Send the message !
$obj = $objSmsMessage;
$objGsm->SendSms($obj, $objSmsConstants->MULTIPART_ACCEPT, 0);
$objSmsMessage = $obj;
$strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);
$objGsm->Close();
}
}
If you pull in jQuery to your front-end, you'll be able to send an AJAX request to execute that PHP function for you. it would look something like this (inserted straight into that sendSMS section in the .js code:
$.ajax() {
url: "/send/sms",
type: "POST",
data: {
author: params.author,
text: params.text,
time: params.time,
to: params.to,
}
}
Now what you will have to do is create the file for the AJAX request to be sent to, they call this an "end point". In my example I set the path of this file to being /send/sms, so perhaps you have a directory called "send" where you could send off an email or SMS, etc. For each of those methods you would have a PHP file containing the logic for it. So for this example, create an sms.php file inside YOUR_ROOT_DIRECTORY/send .
Once you send an AJAX request to that file, the PHP function will be executed. To fetch the given data, use $_POST['author'], $_POST['text'], etc.

Response Email Activity Images in CRM 2011

How can I preserve images in a response to an email activity?
The images in the email show when viewed in CRM - they are added as attachments. When I click the 'respond' button, write a response, and send the response the images are stripped from the email and are not attached to the email.
I have been trying all sorts of things with JScript .
I would rather not have to write anything other than JScript.
This is possible with javascript. I don't know what you tried but this can be done. I.e. catch the send event of your form and create the attachment with Javascript.
Other options are:
You could use a workflow to attach the note of the parent email to
the response. But then you will be forced to save your email wait a
little while (execution of the workflow) and then send the email.
Write plug-in code (but you won't use anything else but Javascript
Javascript to delete attachment:
function deleteAttachments(){
var notesId = {GUID of notes};
var objNotes = new Object();
objNotes.DocumentBody = null;
objNotes.FileName = null;
objNotes.FileSize = null;
objNotes.IsDocument = false;
updateRecord(notesId, objNotes, “AnnotationSet”);
}
function updateRecord(id, entityObject, odataSetName) {
var jsonEntity = window.JSON.stringify(entityObject);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var updateRecordReq = new XMLHttpRequest();
var ODataPath = serverUrl + ODATA_ENDPOINT;
updateRecordReq.open(‘POST’, ODataPath + “/” + odataSetName + “(guid’” + id + “‘)”, false);
updateRecordReq.setRequestHeader(“Accept”, “application/json”);
updateRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8″);
updateRecordReq.setRequestHeader(“X-HTTP-Method”, “MERGE”);
updateRecordReq.send(jsonEntity);
}
I can access the attachments here: https:{org. URL}/xrmServices/2011/OrganizationData.svc/EmailSet(guid'3848cb4d-673f-e211-b9af-005056bd0001')/email_activity_mime_attachment
guid is the guid of the email.
The image is stored in d:Body as Base64.
Now all I need to do is rewrite img for each inline image with src="data:image/png;base64,theverylongstring...
All inline images will be preserved in the response as Base64.

Categories

Resources