Passing JSON data from JS to PHP - javascript
Looked for various solutions but haven't found one yet.
I'm stuck with the following bit of code and my hunch is that the jsondata arriving to the hphp script is empty, but I am clueless as to how to debug as this script is run in the background only.
Javascript:
var pdfdata = {};
function SendMail(){
let el = document.getElementById('content');
let el2 = document.getElementById("tilaus");
let opt = {
margin: 1,
filename: 'myfile.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'A4', orientation: 'portrait' }
};
html2pdf().set( opt ).from( el ).toPdf().output('datauristring').then(function( pdfAsString ) {
pdfdata["tilaus"] = {
'fileDataURI': pdfAsString,
};
//$.post( "../Laskuri/php/send_script.php", data);
} );
html2pdf().set( opt ).from( el2 ).toPdf().output('datauristring').then(function( pdfAsString ) {
pdfdata["tilausvahvistus"] = {
'fileDataURI2': pdfAsString,
};
} );
var jsondata = JSON.stringify(pdfdata);
console.log( JSON.stringify(pdfdata, null, " ") );
$.post( "../Laskuri/php/send_script.php", jsondata);
}
And then on the PHP side:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require './src/Exception.php';
require './src/PHPMailer.php';
$array = json_decode($_POST["jsondata"],true);
$mail = new PHPMailer;
$mail->setFrom( 'asiakas#kajonsteel.fi', 'website' );
$mail->addAddress( 'myynti#kajonsteel.fi', 'Kajon Steel Oy' );
$mail->Subject = 'Tilaus';
$mail->Body = 'Kiitos tilauksesta. Liitteenä tilausvahvistus ja tilaus.';
$pdfdoc = $array->tilaus->fileDataURI;
$b64file = trim( str_replace( 'data:application/pdf;base64,', '', $pdfdoc ) );
$b64file = str_replace( ' ', '+', $b64file );
$decoded_pdf = base64_decode( $b64file );
$pdfdoc2 = $array->tilausvahvistus->fileDataURI2;
$b64file2 = trim( str_replace( 'data:application/pdf;base64,', '', $pdfdoc2 ) );
$b64file2 = str_replace( ' ', '+', $b64file2 );
$decoded_pdf2 = base64_decode( $b64file2 );
$mail->addStringAttachment($decoded_pdf2, "tilausvahvistus.pdf");
$mail->addStringAttachment($decoded_pdf, "tilaus.pdf");
$mail->isHTML( true );
$mail->send();
?>
Am I accessing the jsondata correctly?
console.log gives an empty set first time round, but if I click the button that activates sendMail() again then console.log does show that is filled correctly (and this second email has corrupted pdf's as well).
I managed to use a workaround to get this fixed.
The issue I was experiencing was that I was calling the same php script twice, posting a value each time.
I fixed this by starting session variables and waiting for both of them to "fill up" before sending the email.
JS:
function SendMail(){
let el = document.getElementById('content');
let el2 = document.getElementById("tilaus");
let opt = {
margin: 1,
filename: 'myfile.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'A4', orientation: 'portrait' }
};
html2pdf().set( opt ).from( el ).toPdf().output('datauristring').then(function( pdfAsString ) {
//pdfdata.tilaus = {
let data={
'fileDataURI': pdfAsString,
};
$.post( "../Laskuri/php/send_script.php", data);
} );
html2pdf().set( opt ).from( el2 ).toPdf().output('datauristring').then(function( pdfAsString ) {
let data = {
'fileDataURI2': pdfAsString,
};
$.post( "../Laskuri/php/send_script.php", data);
} );
}
PHP:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require './src/Exception.php';
require './src/PHPMailer.php';
session_start();
$mail = new PHPMailer;
$mail->setFrom( 'asiakas#kajonsteel.fi', 'website' );
$mail->addAddress( 'myynti#kajonsteel.fi', 'Kajon Steel Oy' );
$mail->Subject = 'Tilaus';
$mail->Body = 'Kiitos tilauksesta. Liitteenä tilausvahvistus ja tilaus.';
if(isset($_POST["fileDataURI"])){
$_SESSION["fileDataURI"] = $_POST["fileDataURI"];
}
$pdfdoc = $_SESSION["fileDataURI"];
$b64file = trim( str_replace( 'data:application/pdf;base64,', '', $pdfdoc ) );
$b64file = str_replace( ' ', '+', $b64file );
$decoded_pdf = base64_decode( $b64file );
if(isset($_POST["fileDataURI2"])){
$_SESSION["fileDataURI2"] = $_POST["fileDataURI2"];
}
$pdfdoc2 = $_SESSION["fileDataURI2"];
$b64file2 = trim( str_replace( 'data:application/pdf;base64,', '', $pdfdoc2 ) );
$b64file2 = str_replace( ' ', '+', $b64file2 );
$decoded_pdf2 = base64_decode( $b64file2 );
$mail->addStringAttachment($decoded_pdf2, "tilausvahvistus.pdf");
$mail->addStringAttachment($decoded_pdf, "tilaus.pdf");
$mail->isHTML( true );
if(!empty($decoded_pdf) and !empty($decoded_pdf2)){
$mail->send();
session_destroy();
}
?>
Related
How to check JS Webauthn Assertion in PHP 8.1?
I'm trying to implement WebAuthn in a JavaScript/PHP project and I'm "stuck" at the final assertion verification process. In detail, I pass the "assertion" parameters from JavaScript (Jquery) to PHP script like this: navigator.credentials.get( { publicKey: { allowCredentials: [...], challenge: Uint8Array.from( ..., c => c.charCodeAt( 0 ) ), rpId: window.location.hostname, timeout: 60000, userVerification: 'preferred' } } ) .then( ( assertion ) => { $.ajax( { data: 'login=' + encodeURIComponent( JSON.stringify( { ..., 'rawid': new Uint8Array( assertion.rawId ), 'authenticatordata': new Uint8Array( assertion.response.authenticatorData ), 'clientdatajson': new Uint8Array( assertion.response.clientDataJSON ), 'signature': new Uint8Array( assertion.response.signature ) } ) ) } ) And once the "public key" corresponding to the authenticator employed by the user has been identified within a database, I try to validate in PHP 8.1 the "assertion" in this way: $jsonInput = json_decode( '{"authenticatordata":{"0":201,"1":157,"2":215,"3":147,"4":42,"5":142,"6":165,"7":93,"8":198,"9":108,"10":247,"11":140,"12":253,"13":224,"14":178,"15":122,"16":185,"17":204,"18":239,"19":151,"20":3,"21":24,"22":2,"23":25,"24":212,"25":39,"26":42,"27":95,"28":255,"29":195,"30":201,"31":113,"32":5,"33":0,"34":0,"35":0,"36":16},"clientdatajson":{"0":123,"1":34,"2":116,"3":121,"4":112,"5":101,"6":34,"7":58,"8":34,"9":119,"10":101,"11":98,"12":97,"13":117,"14":116,"15":104,"16":110,"17":46,"18":103,"19":101,"20":116,"21":34,"22":44,"23":34,"24":99,"25":104,"26":97,"27":108,"28":108,"29":101,"30":110,"31":103,"32":101,"33":34,"34":58,"35":34,"36":77,"37":68,"38":65,"39":119,"40":77,"41":68,"42":65,"43":119,"44":77,"45":68,"46":65,"47":119,"48":77,"49":103,"50":34,"51":44,"52":34,"53":111,"54":114,"55":105,"56":103,"57":105,"58":110,"59":34,"60":58,"61":34,"62":104,"63":116,"64":116,"65":112,"66":115,"67":58,"68":47,"69":47,"70":109,"71":111,"72":114,"73":109,"74":105,"75":110,"76":111,"77":46,"78":114,"79":101,"80":115,"81":105,"82":101,"83":108,"84":46,"85":99,"86":111,"87":109,"88":34,"89":44,"90":34,"91":99,"92":114,"93":111,"94":115,"95":115,"96":79,"97":114,"98":105,"99":103,"100":105,"101":110,"102":34,"103":58,"104":102,"105":97,"106":108,"107":115,"108":101,"109":125},"signature":{"0":48,"1":69,"2":2,"3":33,"4":0,"5":251,"6":22,"7":162,"8":18,"9":206,"10":81,"11":110,"12":4,"13":3,"14":217,"15":148,"16":51,"17":132,"18":130,"19":31,"20":122,"21":186,"22":65,"23":73,"24":195,"25":170,"26":106,"27":35,"28":90,"29":149,"30":56,"31":1,"32":58,"33":222,"34":51,"35":69,"36":212,"37":2,"38":32,"39":77,"40":161,"41":139,"42":133,"43":49,"44":79,"45":218,"46":34,"47":45,"48":115,"49":178,"50":156,"51":139,"52":185,"53":13,"54":197,"55":248,"56":116,"57":217,"58":81,"59":111,"60":117,"61":68,"62":44,"63":141,"64":197,"65":87,"66":68,"67":1,"68":89,"69":222,"70":154}}' ); $publickey = json_decode( '{"0":48,"1":89,"2":48,"3":19,"4":6,"5":7,"6":42,"7":134,"8":72,"9":206,"10":61,"11":2,"12":1,"13":6,"14":8,"15":42,"16":134,"17":72,"18":206,"19":61,"20":3,"21":1,"22":7,"23":3,"24":66,"25":0,"26":4,"27":229,"28":126,"29":127,"30":191,"31":207,"32":67,"33":42,"34":66,"35":212,"36":251,"37":1,"38":126,"39":36,"40":232,"41":163,"42":188,"43":151,"44":84,"45":50,"46":83,"47":251,"48":29,"49":196,"50":24,"51":208,"52":131,"53":96,"54":190,"55":14,"56":239,"57":104,"58":123,"59":78,"60":90,"61":70,"62":76,"63":54,"64":211,"65":91,"66":74,"67":243,"68":252,"69":69,"70":192,"71":132,"72":245,"73":206,"74":214,"75":67,"76":210,"77":165,"78":46,"79":230,"80":191,"81":6,"82":19,"83":241,"84":201,"85":188,"86":235,"87":232,"88":84,"89":130,"90":185}', TRUE ); $jsonInput->authenticatordata = ( array ) $jsonInput->authenticatordata; // [201,157,215,147,42,142,165,93,198,108,247,140,253,224,178,122,185,204,239,151,3,24,2,25,212,39,42,95,255,195,201,113,5,0,0,0,16] $jsonInput->clientdatajson = ( array ) $jsonInput->clientdatajson; // [123,34,116,121,112,101,34,58,34,119,101,98,97,117,116,104,110,46,103,101,116,34,44,34,99,104,97,108,108,101,110,103,101,34,58,34,77,68,65,119,77,68,65,119,77,68,65,119,77,103,34,44,34,111,114,105,103,105,110,34,58,34,104,116,116,112,115,58,47,47,109,111,114,109,105,110,111,46,114,101,115,105,101,108,46,99,111,109,34,44,34,99,114,111,115,115,79,114,105,103,105,110,34,58,102,97,108,115,101,125] $jsonInput->signature = ( array ) $jsonInput->signature; // [48,69,2,33,0,251,22,162,18,206,81,110,4,3,217,148,51,132,130,31,122,186,65,73,195,170,106,35,90,149,56,1,58,222,51,69,212,2,32,77,161,139,133,49,79,218,34,45,115,178,156,139,185,13,197,248,116,217,81,111,117,68,44,141,197,87,68,1,89,222,154] echo openssl_verify( implode( array_map( 'chr', $jsonInput->authenticatordata ) ) . hash( 'sha256', json_encode( implode( array_map( 'chr', $jsonInput->clientdatajson ) ) ) ), implode( array_map( 'chr', $jsonInput->signature ) ), "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split( base64_encode( implode( array_map( 'chr', $publickey ) ) ), 64 ) . "-----END PUBLIC KEY-----", OPENSSL_ALGO_SHA256 ); echo '<br />'; echo openssl_error_string(); // error:0D07803A:asn1 encoding routines:asn1_item_embed_d2i:nested asn1 error /*The processed Windows Hello (From Windows 11) authenticator-generated public key results at the end: -----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE5X5/v89DKkLU+wF+JOijvJdUMlP7 HcQY0INgvg7vaHtOWkZMNtNbSvP8RcCE9c7WQ9KlLua/BhPxybzr6FSCuQ== -----END PUBLIC KEY----- */ Another example with a different authenticator (Widows Hello from Windows 10): $jsonInput = json_decode( '{"authenticatordata":[201,157,215,147,42,142,165,93,198,108,247,140,253,224,178,122,185,204,239,151,3,24,2,25,212,39,42,95,255,195,201,113,5,0,0,0,2],"clientdatajson":[123,34,116,121,112,101,34,58,34,119,101,98,97,117,116,104,110,46,103,101,116,34,44,34,99,104,97,108,108,101,110,103,101,34,58,34,77,68,65,119,77,68,65,119,77,68,65,119,77,103,34,44,34,111,114,105,103,105,110,34,58,34,104,116,116,112,115,58,47,47,109,111,114,109,105,110,111,46,114,101,115,105,101,108,46,99,111,109,34,44,34,99,114,111,115,115,79,114,105,103,105,110,34,58,102,97,108,115,101,44,34,111,116,104,101,114,95,107,101,121,115,95,99,97,110,95,98,101,95,97,100,100,101,100,95,104,101,114,101,34,58,34,100,111,32,110,111,116,32,99,111,109,112,97,114,101,32,99,108,105,101,110,116,68,97,116,97,74,83,79,78,32,97,103,97,105,110,115,116,32,97,32,116,101,109,112,108,97,116,101,46,32,83,101,101,32,104,116,116,112,115,58,47,47,103,111,111,46,103,108,47,121,97,98,80,101,120,34,125],"signature":[94,96,8,15,78,8,75,244,177,242,61,244,7,240,100,98,176,74,243,176,215,209,229,61,5,137,178,77,240,88,160,220,9,110,33,171,52,255,65,140,191,209,29,49,26,111,164,65,47,1,90,77,95,196,60,132,185,189,145,0,138,65,212,242,210,222,55,91,211,208,15,216,252,81,6,132,159,42,234,186,78,81,121,187,45,71,22,178,83,210,196,161,31,247,188,218,211,159,5,102,249,213,142,158,230,99,182,166,78,62,153,107,53,133,150,96,95,99,213,172,19,44,243,114,127,167,155,195,88,172,236,229,233,212,65,100,127,98,4,4,71,124,29,174,104,65,190,218,221,16,228,85,137,216,250,89,49,77,245,120,146,72,7,23,67,144,108,160,195,204,216,51,100,159,32,208,151,249,87,146,54,31,230,48,241,67,235,8,171,198,53,8,83,178,8,203,6,173,76,213,212,128,241,72,129,162,159,13,234,49,6,140,253,159,107,115,91,151,195,25,203,27,98,81,41,96,254,88,92,126,78,207,59,114,214,238,153,34,100,49,59,246,249,99,255,49,71,178,42,226,62,246,149,193,91,140]}' ); $publickey = json_decode( '{"0":48,"1":130,"2":1,"3":34,"4":48,"5":13,"6":6,"7":9,"8":42,"9":134,"10":72,"11":134,"12":247,"13":13,"14":1,"15":1,"16":1,"17":5,"18":0,"19":3,"20":130,"21":1,"22":15,"23":0,"24":48,"25":130,"26":1,"27":10,"28":2,"29":130,"30":1,"31":1,"32":0,"33":226,"34":31,"35":139,"36":141,"37":197,"38":58,"39":76,"40":61,"41":52,"42":104,"43":160,"44":127,"45":66,"46":27,"47":61,"48":3,"49":107,"50":228,"51":250,"52":6,"53":98,"54":104,"55":214,"56":5,"57":33,"58":182,"59":247,"60":175,"61":107,"62":236,"63":71,"64":232,"65":98,"66":163,"67":112,"68":213,"69":174,"70":56,"71":131,"72":160,"73":93,"74":200,"75":85,"76":35,"77":234,"78":116,"79":212,"80":172,"81":0,"82":232,"83":78,"84":48,"85":90,"86":122,"87":93,"88":100,"89":212,"90":88,"91":250,"92":91,"93":228,"94":248,"95":14,"96":42,"97":228,"98":123,"99":149,"100":36,"101":205,"102":21,"103":172,"104":116,"105":44,"106":113,"107":229,"108":246,"109":50,"110":110,"111":219,"112":122,"113":219,"114":26,"115":72,"116":17,"117":120,"118":63,"119":148,"120":176,"121":94,"122":110,"123":133,"124":131,"125":199,"126":213,"127":219,"128":22,"129":29,"130":88,"131":178,"132":141,"133":62,"134":170,"135":76,"136":121,"137":62,"138":237,"139":192,"140":214,"141":82,"142":122,"143":113,"144":244,"145":124,"146":2,"147":5,"148":39,"149":83,"150":68,"151":252,"152":219,"153":233,"154":27,"155":128,"156":77,"157":160,"158":241,"159":92,"160":1,"161":0,"162":171,"163":214,"164":233,"165":178,"166":240,"167":207,"168":227,"169":74,"170":134,"171":206,"172":217,"173":193,"174":89,"175":79,"176":56,"177":217,"178":152,"179":229,"180":175,"181":47,"182":146,"183":145,"184":101,"185":173,"186":39,"187":106,"188":252,"189":194,"190":107,"191":221,"192":150,"193":30,"194":122,"195":73,"196":204,"197":49,"198":242,"199":60,"200":227,"201":208,"202":10,"203":223,"204":182,"205":195,"206":105,"207":113,"208":99,"209":119,"210":41,"211":215,"212":234,"213":227,"214":166,"215":69,"216":66,"217":160,"218":83,"219":131,"220":109,"221":111,"222":216,"223":9,"224":55,"225":176,"226":107,"227":4,"228":108,"229":37,"230":235,"231":100,"232":88,"233":14,"234":154,"235":247,"236":143,"237":102,"238":106,"239":48,"240":200,"241":8,"242":152,"243":187,"244":73,"245":126,"246":95,"247":139,"248":83,"249":140,"250":199,"251":151,"252":46,"253":174,"254":25,"255":82,"256":240,"257":199,"258":41,"259":126,"260":106,"261":126,"262":93,"263":201,"264":70,"265":217,"266":151,"267":46,"268":117,"269":139,"270":144,"271":29,"272":43,"273":76,"274":59,"275":180,"276":255,"277":208,"278":43,"279":124,"280":111,"281":168,"282":50,"283":221,"284":105,"285":134,"286":153,"287":113,"288":141,"289":2,"290":3,"291":1,"292":0,"293":1}', TRUE ); $jsonInput->authenticatordata = ( array ) $jsonInput->authenticatordata; $jsonInput->clientdatajson = ( array ) $jsonInput->clientdatajson; $jsonInput->signature = ( array ) $jsonInput->signature; echo openssl_verify( implode( array_map( 'chr', $jsonInput->authenticatordata ) ) . hash( 'sha256', implode( array_map( 'chr', $jsonInput->clientdatajson ) ) ), implode( array_map( 'chr', $jsonInput->signature ) ), "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split( base64_encode( implode( array_map( 'chr', $publickey ) ) ), 64 ) . "-----END PUBLIC KEY-----", OPENSSL_ALGO_SHA256 ); echo '<br />'; echo openssl_error_string(); // error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag /* -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4h+LjcU6TD00aKB/Qhs9 A2vk+gZiaNYFIbb3r2vsR+hio3DVrjiDoF3IVSPqdNSsAOhOMFp6XWTUWPpb5PgO KuR7lSTNFax0LHHl9jJu23rbGkgReD+UsF5uhYPH1dsWHViyjT6qTHk+7cDWUnpx 9HwCBSdTRPzb6RuATaDxXAEAq9bpsvDP40qGztnBWU842Zjlry+SkWWtJ2r8wmvd lh56Scwx8jzj0ArftsNpcWN3Kdfq46ZFQqBTg21v2Ak3sGsEbCXrZFgOmvePZmow yAiYu0l+X4tTjMeXLq4ZUvDHKX5qfl3JRtmXLnWLkB0rTDu0/9ArfG+oMt1phplx jQIDAQAB -----END PUBLIC KEY----- */ 1. However the "openssl_verify" function returns failure (0) instead of success (1). Where am I wrong? 2. Why does Windows Hello return a short public key in the first case? Is it equally valid? 3. Is this the correct way to convert to PEM and use the public key generated by credential.response.getPublicKey()? Note: in a different context, I transfer the public key from javascript (jquery) to PHP 8.1 like this: navigator.credentials.create( { publicKey: { attestation: 'none', authenticatorSelection: { userVerification: 'preferred' }, challenge: Uint8Array.from( ..., c => c.charCodeAt( 0 ) ), excludeCredentials: [], pubKeyCredParams: [], rp: { id: window.location.hostname, name: window.document.title }, timeout: 60000, user: { id: Uint8Array.from( ..., c => c.charCodeAt( 0 ) ), displayName: ..., name: ... } } } ) .then( ( credential ) => { $.ajax( { data: 'data=' + encodeURIComponent( JSON.stringify( { ..., 'publickey': new Uint8Array( credential.response.getPublicKey() ), 'authenticatordata': new Uint8Array( credential.response.getAuthenticatorData() ), 'transports': credential.response.getTransports() } ) ) } )
Router TP-Link blocking IP address when I upload file on html form
I don't have any idea where is a problem. I have a router TP-link TL-WR940N and this device blocking my computer (firewall blocking IP Address) when I upload image by html form. I thought the problem are a big POST request. I modifing this code to AJAX upload file. Now i send files one by one - I send first file, waiting to complete and sending next file. My TP-Link are still blocking IP. I find 3 options in router config which genrate problem: ICMP-FLOOD Attack Filtering UDP-FLOOD Filtering TCP-SYN-FLOOD Attack Filtering Has anyone had this problem? My actual js code: function uploadFileAsync(idProduct, alt, iteration, files) { var formData = new FormData(); var arrFilesLength = files.length; var file = files[iteration]; formData.delete('fileGal[]'); formData.set('fileGal[]', file, file.name); $.ajax({ url: documentDomain + 'admin.php?uploadFile=' + idProduct + '&imgAlt=' + alt, type: 'POST', async: true, data: formData, cache: false, contentType: false, processData: false, success: function(data) { iteration++; if (iteration == arrFilesLength) { $('progress').css('display', 'none'); $('.fileGal').val(''); $('.imurConvertGood').hide(); $('.productGalleryTitle').html('No file'); refreshPicturesList(idProduct); } else { $('progress').attr({ value: iteration, max: arrFilesLength, }); uploadFileAsync(idProduct, alt, iteration, files); } } }); } Upload PHP: private function uploadFile($idProduct = null, $fi = null, $imgAlt = null) { $config = new Config; $idProduct = htmlspecialchars($idProduct, ENT_QUOTES); $fi = htmlspecialchars($fi, ENT_QUOTES); $pathFilesServer = $this->AppModel->pathFilesServer(); $productSQL = $this->AppModel->selectData('products', array('name', 'aliasID'), array('id' => $idProduct)); $productArr = $productSQL->fetch_assoc(); $aliasNameSQL = $this->AppModel->selectData('alias', 'alias', array('id' => $productArr['aliasID'])); $aliasName = $aliasNameSQL->fetch_assoc(); if (is_array($_FILES['fileGal']['name'])) { if ($fi == null) $fi=0; $fc = count($_FILES['fileGal']['name']); $file_name = $_FILES['fileGal']['name'][$fi]; $file_tmp = $_FILES['fileGal']['tmp_name'][$fi]; $fi++; } else { $file_name = $_FILES['fileGal']['name']; $file_tmp = $_FILES['fileGal']['tmp_name']; } $file_name = strtolower($file_name); /* new name file */ $today = getdate(); $md=md5($today[0]+rand()); $tmp = explode(".", $file_name); $extension = end($tmp); if ($aliasName['alias'] != '') { $newName = $aliasName['alias'].'-'.rand(1000, 9999).'.'.$extension; } else { $newName = $md.'.'.$extension; } $path = $pathFilesServer.'/Store/imgProducts/orginal/'.$newName; $fileFromImagick = $this->helpers->resizeImage($file_tmp, 250, 250, Imagick::FILTER_LANCZOS, 1, true, null); file_put_contents ($pathFilesServer.'/Store/imgProducts/min/'.$newName, $fileFromImagick); $fileFromImagick = $this->helpers->resizeImage($file_tmp, 500, 500, Imagick::FILTER_LANCZOS, 1, true, null); file_put_contents ($pathFilesServer.'/Store/imgProducts/middle/'.$newName, $fileFromImagick); /* start upload file */ if(is_uploaded_file($file_tmp)) { move_uploaded_file($file_tmp, $path); } if ($imgAlt == null) { $this->AppModel->insertValue('pictures', array('id' => '', 'idProduct' => $idProduct, 'file' => $newName, 'alt' => $productArr['name'])); } else { $this->AppModel->insertValue('pictures', array('id' => '', 'idProduct' => $idProduct, 'file' => $newName, 'alt' => $imgAlt)); } if ($fi<$fc){ $this->uploadFile($idProduct, $fi); } else {} }
I am trying to retrieve the posts via ajax call but Wordpress Ajax gives server error 500
When I click on pagination link (page number) it gives me post_type, taxonomy, term_name. I passed the variables with JQuery Variables to Ajax wordpress function. The Ajax function is receiving the vaiables. But WP_Query loop does not work with the passed data. JavaScript Code: <script> $(".category--pagination").on("click", "a", function (e) { e.preventDefault(); var link = $(this).attr("href"); if (link.indexOf("/page/") >= 0) { brands_page = parseInt(link.substr(link.indexOf("/page/") + 6, 4)); } else { brands_page = 1; } mzm_filter_taxonomy(); }); // mzm_filter_tax function mzm_filter_taxonomy() { $("#brandCategoryItemDisplay").addClass("loading"); var post_type = $("#post_type").val(); var taxonomy = $("#taxonomy").val(); var term_slug = $("#term_slug").val(); var term_name = $("#term_name").val(); //console.log(post_type); // console.log(taxonomy); // console.log(term_name); if (brands_page == undefined) { brands_page = 1; } var data = { action: "mzm_filter_taxonomy", post_type: post_type, taxonomy:taxonomy, term_slug:term_slug, term_name:term_name, page:brands_page, }; $.post(mzm_filter.ajax_url, data, function (response, textStatus, jqXHR) { if (response.success) { console.log("executed success"); $("#brandCategoryItemDisplay").removeClass("loading"); $("#brandCategoryItemDisplay").html(response.data.items); $(".category--pagination").html(response.data.pagination); //$("#taxonomy_pagination").html(response.data.pagination); } }); } </script> Wordpress Ajax Function: function mzm_filter_taxonomy() { $post_type = isset($_POST['post_type']) ? filter_var(trim($_POST['post_type']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null; $taxonomy = isset($_POST['taxonomy']) ? filter_var(trim($_POST['taxonomy']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null; $term_slug = isset($_POST['term_slug']) ? filter_var(trim($_POST['term_slug']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null; $term_name = isset($_POST['term_name']) ? filter_var(trim($_POST['term_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null; $perpage = mzm_brand_perpage(); $paged = (isset($_POST['page']) && intval($_POST['page'])) ? intval($_POST['page']) : 1; // $sort = ( isset( $_POST['sort'] ) && intval( $_POST['sort'] ) ) ? intval( $_POST['sort'] ) : 1; // $sort = (isset($_POST['sort'])) ? intval($_POST['sort']) : 1; // $args = array( // 'post_type' => $post_type, // 'hide_empty' => false, // 'posts_per_page' => $perpage, // 'paged' => $paged, // 'post_status' => 'publish', // 'tax_query' => array( // array ( // 'taxonomy' => $taxonomy, // 'field' => 'slug', // 'terms' => $term_slug, // ) // ), // ); $the_query = new WP_Query( array( 'post_type' => $post_type, 'tax_query' => array( array ( 'taxonomy' => $taxonomy, 'field' => 'slug', 'terms' => $term_slug, ) ), ) ); // $the_query = new WP_Query($args); ob_start(); // echo $post_type . '<br>'; // echo $taxonomy . '<br>'; // echo $term_name . '<br>'; // echo $term_slug . '<br>'; if ($the_query->have_posts()) { while ($the_query->have_posts()) { the_post(); // echo mzm_render_single_brand_card(); echo the_title(); } wp_reset_postdata(); } else { echo '<div class="no-criteria-search">Sorry, no posts matched your criteria.</div>'; } $html = ob_get_clean(); $result = array( 'items' => $html, 'pagination' => 'mzm_render_pagination($the_query)', ); wp_send_json_success($result); } add_action('wp_ajax_nopriv_mzm_filter_taxonomy', 'mzm_filter_taxonomy'); add_action('wp_ajax_mzm_filter_taxonomy', 'mzm_filter_taxonomy'); I am trying paginate via Ajax request. Other all scripts are working. But this is a single taxonomy page. On this page the loop doesn't executes. It gives server error 500.
I solved it myself. The problem was in wp_query loop. I using custom $args and the loop object was $the_query. So, the_post(); //should be $the_query->the_post();
select file, crop and upload with angular and php
I'm following this tutorial I found on the web and I've installed the dependency correctly. But i'm not able to upload my file to the server JS imageChangedEvent: any = ''; croppedImage: any = ''; fileChangeEvent(event: any): void { this.imageChangedEvent = event; } imageCropped(event: ImageCroppedEvent) { this.croppedImage = event.base64; const formData = new FormData(); formData.append('file', this.croppedImage); this.http.post(this.global.baseUrl + upload.php', formData, { }).subscribe(data => { console.log(JSON.stringify(data)); // this.newfileName = (data); this.loader = false; }); } imageLoaded() { // show cropper } loadImageFailed() { // show message } HTML <image-cropper [imageChangedEvent]="imageChangedEvent" [maintainAspectRatio]="true" [aspectRatio]="4 / 4" [resizeToWidth]="128" format="png" (imageCropped)="imageCropped($event)" (imageLoaded)="imageLoaded()" (loadImageFailed)="loadImageFailed()" ></image-cropper> PHP $path = '../upload_imgs/'; if (isset($_FILES['file'])) { $originalName = $_FILES['file']['name']; $ext = '.'.pathinfo($originalName, PATHINFO_EXTENSION); $generatedName = md5($_FILES['file']['tmp_name']).$ext; $filePath = $path.$generatedName; $photo=array("generatedName"=>($generatedName)); if (!is_writable($path)) { echo json_encode(array( 'status' => false, 'msg' => 'Destination directory not writable.' )); exit; } if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) { echo json_encode(array($photo)); } } else { echo json_encode( array('status' => false, 'msg' => 'No file uploaded.') ); exit; } After cropping the console reads nothing. is there something i may be doing wrong?
Isn't an apostroph missing here: this.http.post(this.global.baseUrl + upload.php', formData, {
Highlighting words with Javascript, what am I missing?
I have been working with a basic javascript/PHP chatroom. I want certain words to be highlighted as they appear in the chat stream. The html output for the chatroom looks like: <div class="chat-container"> <div class="chat chat-message-111"><strong style="color: #840;">User 1</strong>: What is your favourite animal?</div> <div class="chat chat-message-112"><strong style="color: #840;">User 2</strong>: I vote for #dog. </div> <div class="chat chat-message-113"><strong style="color: #840;">User 3</strong>: I have a #cat!</div> </div> I have found one Javascript solution that is actually what I'm looking for (please see https://jsfiddle.net/4ny8adpg/2/ for a working example). But when I try to use it with the chatroom, it won't highlight any text in the "Chat-Container" div. Will it not work because the contents of the chatroom is an output of the PHP/Javascript and not just HTML like in the jsfiddle example? Or maybe I am missing something obvious. Any help or advise would seriously be appreciated. EDIT (to show code and provide more information): The chatroom is actually a wordpress plugin, it is made up of a PHP file and a Javascript file: Javascript: var last_update_received = 0; function chatroom_check_updates() { jQuery.post( ajaxurl, { action: 'check_updates', chatroom_slug: chatroom_slug, last_update_id: last_update_id }, function (response) { chats = jQuery.parseJSON( response ); if ( chats !== null ) { for ( i = 0; i < chats.length; i++ ) { if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length ) continue; jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) ); last_update_id = chats[i].id; jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100); } } } ); setTimeout( "chatroom_check_updates()", 1000 ); } function chatroom_strip_slashes(str) { return (str + '').replace(/\\(.?)/g, function (s, n1) { switch (n1) { case '\\': return '\\'; case '0': return '\u0000'; case '': return ''; default: return n1; } }); } jQuery(document).ready( function() { last_update_id = 0; chatroom_check_updates(); jQuery( 'textarea.chat-text-entry' ).keypress( function( event ) { if ( event.charCode == 13 || event.keyCode == 13 ) { chatroom_send_message(); return false; } }); }); function chatroom_send_message() { message = jQuery( 'textarea.chat-text-entry' ).val(); jQuery( 'textarea.chat-text-entry' ).val(''); jQuery.post( ajaxurl, { action: 'send_message', chatroom_slug: chatroom_slug, message: message }, function (response) { } ); } PHP: Class Chatroom { function __construct() { register_activation_hook( __FILE__, array( $this, 'activation_hook' ) ); register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) ); add_action( 'init', array( $this, 'register_post_types' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 ); add_action( 'wp_head', array( $this, 'define_javascript_variables' ) ); add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) ); add_action( 'wp_ajax_send_message', array( $this, 'ajax_send_message_handler' ) ); add_filter( 'the_content', array( $this, 'the_content_filter' ) ); } function activation_hook() { $this->register_post_types(); flush_rewrite_rules(); } function deactivation_hook() { flush_rewrite_rules(); } function register_post_types() { $labels = array( 'name' => _x( 'Chat Rooms', 'post type general name', 'chatroom' ), 'singular_name' => _x( 'Chat Room', 'post type singular name', 'chatroom' ), 'add_new' => _x( 'Add New', 'book', 'chatroom' ), 'add_new_item' => __( 'Add New Chat Room', 'chatroom' ), 'edit_item' => __( 'Edit Chat Room', 'chatroom' ), 'new_item' => __( 'New Chat Room', 'chatroom' ), 'all_items' => __( 'All Chat Rooms', 'chatroom' ), 'view_item' => __( 'View Chat Room', 'chatroom' ), 'search_items' => __( 'Search Chat Rooms', 'chatroom' ), 'not_found' => __( 'No Chat Rooms found', 'chatroom' ), 'not_found_in_trash' => __( 'No Chat Rooms found in Trash', 'chatroom' ), 'parent_item_colon' => '', 'menu_name' => __( 'Chat Rooms', 'chatroom' ) ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'show_in_nav_menus' => true, 'supports' => array( 'title' ) ); register_post_type( 'chat-room', $args ); } function enqueue_scripts() { global $post; if ( $post->post_type != 'chat-room' ) return; wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'chat-room', plugins_url( 'chat-room.js', __FILE__ ) ); wp_enqueue_style( 'chat-room-styles', plugins_url( 'chat-room.css', __FILE__ ) ); } function maybe_create_chatroom_log_file( $post_id, $post ) { if ( empty( $post->post_type ) || $post->post_type != 'chat-room' ) return; $upload_dir = wp_upload_dir(); $log_filename = $upload_dir['basedir'] . '/chatter/' . $post->post_name . '-' . date( 'm-d-y', time() ); if ( file_exists( $log_filename ) ) return; wp_mkdir_p( $upload_dir['basedir'] . '/chatter/' ); $handle = fopen( $log_filename, 'w' ); fwrite( $handle, json_encode( array() ) ); // TODO create warnings if the user can't create a file, and suggest putting FTP creds in wp-config } function define_javascript_variables() { global $post; if ( empty( $post->post_type ) || $post->post_type != 'chat-room' ) return; ?> <script> var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>'; var chatroom_slug = '<?echo $post->post_name; ?>'; </script> <?php } function ajax_check_updates_handler() { $upload_dir = wp_upload_dir(); $log_filename = $this->get_log_filename( $_POST['chatroom_slug'] ); $contents = $this->parse_messages_log_file( $log_filename ); $messages = json_decode( $contents ); foreach ( $messages as $key => $message ) { if ( $message->id <= $_POST['last_update_id'] ) unset( $messages[$key] ); } $messages = array_values( $messages ); echo json_encode( $messages ); die; } /** * AJAX server-side handler for sending a message. * * Stores the message in a recent messages file. * * Clears out cache of any messages older than 10 seconds. */ function ajax_send_message_handler() { $current_user = wp_get_current_user(); $this->save_message( $_POST['chatroom_slug'], $current_user->id, $_POST['message'] ); die; } function save_message( $chatroom_slug, $user_id, $content ) { $user = get_userdata( $user_id ); if ( ! $user_text_color = get_user_meta( $user_id, 'user_color', true ) ) { // Set random color for each user $red = rand( 0, 16 ); $green = 16 - $red; $blue = rand( 0, 16 ); $user_text_color = '#' . dechex( $red^2 ) . dechex( $green^2 ) . dechex( $blue^2 ); update_user_meta( $user_id, 'user_color', $user_text_color ); } $content = esc_attr( $content ); // Save the message in recent messages file $log_filename = $this->get_log_filename( $chatroom_slug ); $contents = $this->parse_messages_log_file( $log_filename ); $messages = json_decode( $contents ); $last_message_id = 0; // Helps determine the new message's ID foreach ( $messages as $key => $message ) { if ( time() - $message->time > 10 ) { $last_message_id = $message->id; unset( $messages[$key] ); } else { break; } } $messages = array_values( $messages ); if ( ! empty( $messages ) ) $last_message_id = end( $messages )->id; $new_message_id = $last_message_id + 1; $messages[] = array( 'id' => $new_message_id, 'time' => time(), 'sender' => $user_id, 'contents' => $content, 'html' => '<div class="chat-message-' . $new_message_id . '"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>', ); $this->write_log_file( $log_filename, json_encode( $messages ) ); // Save the message in the daily log $log_filename = $this->get_log_filename( $chatroom_slug, date( 'm-d-y', time() ) ); $contents = $this->parse_messages_log_file( $log_filename ); $messages = json_decode( $contents ); $messages[] = array( 'id' => $new_message_id, 'time' => time(), 'sender' => $user_id, 'contents' => $content, 'html' => '<div class="chat-message-' . $new_message_id .'"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>', ); $this->write_log_file( $log_filename, json_encode( $messages ) ); } function write_log_file( $log_filename, $content ) { $handle = fopen( $log_filename, 'w' ); fwrite( $handle, $content ); } function get_log_filename( $chatroom_slug, $date = 'recent' ) { $upload_dir = wp_upload_dir(); $log_filename = $upload_dir['basedir'] . '/chatter/' . $chatroom_slug . '-' . $date; return $log_filename; } function parse_messages_log_file( $log_filename ) { $upload_dir = wp_upload_dir(); $handle = fopen( $log_filename, 'r' ); $contents = fread( $handle, filesize( $log_filename ) ); fclose( $handle ); return $contents; } function the_content_filter( $content ) { global $post; if ( $post->post_type != 'chat-room' ) return $content; if ( ! is_user_logged_in() ) { ?>You need to be logged in to participate in the chatroom.<?php return; } ?> <div class="chat-container"> </div> <textarea class="chat-text-entry"></textarea> <?php return ''; } } $chatroom = new Chatroom(); Example of JSON: [{"id":129,"time":1428340673,"sender":1,"contents":"What is your favourite animal?","html":"<div class=\"chat chat-message-129\"><strong style=\"color: #840;\">User 1<\/strong>: What is your favourite animal?<\/div>"}, {"id":130,"time":1428351683,"sender":2,"contents":"I vote for #dog.","html":"<div class=\"chat chat-message-130\"><strong style=\"color: #840;\">User 2<\/strong>: I vote for #dog.<\/div>"}, {"id":131,"time":1428352376,"sender":3,"contents":"I have a #cat!","html":"<div class=\"chat chat-message-131\"><strong style=\"color: #840;\">User 3<\/strong>: I have a #cat!<\/div>"}]
If you want your highlighting code to run after an AJAX call has returned (when there are new HTML fragments), then try something along these lines: $.ajax({ ... success : function(data) { ... $('.chat').each(function(){ var hashtag = $(this).text() .replace(/#dog/g, "<span class='dog'>#DOG</span>") .replace(/#cat/g, "<span class='cat'>#CAT</span>"); $(this).html(hashtag); }); }, ... }); In your case, call your highlighting code after you have populated all your chat fragments: ... function (response) { chats = jQuery.parseJSON( response ); if ( chats !== null ) { for ( i = 0; i < chats.length; i++ ) { if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length ) continue; jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) ); last_update_id = chats[i].id; jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100); } // Call highlighting code here } } ... PS You can save time by caching the selector jQuery('div.chat-container') as a variable so that jQuery doesn't have to search your HTML each time.