For some reason I can't get the post variables from the controller
The AJAX/Javascript
function uploadImage(userActionPath,type)
{
if( (userActionPath == 'undefined') || (type == 'undefined')) {
console.error("no parameters for function uploadImage defined");
}
if((base64code == 'undefined') || (base64code == null))
{
console.error("please select an image");
}
var xml = ( window.XMLHttpRequest ) ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
alert(base64code); //<- shows the base64 code, so its there
var params = userActionPath+"?imagebase64="+base64code+"&type="+type;
xml.open("POST",userActionPath,true);
xml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xml.onreadystatechange = function()
{
if( xml.readyState === 4 && xml.status === 200 )
{
var serverResponse = JSON.parse(xml.responseText);
switch(serverResponse.f)
{
case 0:
console.log('love sosa'); //<- I get the response
break;
}
}
};
xml.send(params);
}
The controller
class LiveuploadController extends Controller
{
/**
* #Route("/LiveUpload",name="fileLiveUpload")
* #Template()
*/
public function indexAction(Request $request)
{
//I have tried these but 'imagebase64' returns null
//returns null
$value = $request->request->get('imagebase64');
//returns null
$value = $request->query->get('imagebase64');
//returns null
$value = $this->get('request')->request->get('imagebase64');
$response = array('f'=>0,'base64'=>$value);
return new Response(json_encode($response));
}
}
The request headers also show that the variables are being sent.But both the type AND the imagebase64 variables return null on the controller
The problem is with the way that you have setup the XmlHttpRequest. You have set it up like it should be using GET, but when you want to POST, it is a bit different. Take a look at this question for more info on how to send a POST request. The quick and dirty of it is:
var xml = ( window.XMLHttpRequest ) ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
var params = "imagebase64="+base64code+"&type="+type;
xml.open("POST", userActionPath, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.setRequestHeader("Content-length", params.length);
xml.setRequestHeader("Connection", "close");
xml.onreadystatechange = function()
{
if( xml.readyState === 4 && xml.status === 200 )
{
var serverResponse = JSON.parse(xml.responseText);
switch(serverResponse.f)
{
case 0:
console.log('love sosa'); //<- I get the response
break;
}
}
};
xml.send(params);
In your example code, you are setting the header to expect JSON, but your params are urlencoded. Setting the proper header should do the trick.
And in your controller, if you are using POST, then you should get the request variables like this:
// Use this for getting variables of POST requests
$value = $request->request->get('imagebase64');
// This is used for getting variables of GET requests
$value = $request->query->get('imagebase64');
This line of code in your JS:
xml.open("POST",userActionPath,true);
You are actually supplying userActionPath instead of params variable. It should be:
xml.open("POST",params,true);
As for the controller's code you should use:
$value = $request->query->get('imagebase64');
Hope this helps...
Related
I wrote different code (at least twice) where Ajax is supposed to change an innerHTML-value by a database call (GET). While the first requests succedes in a 100 % of the time (changing a value in the database) the next commands that extracts the new Information to update the HTML-file fails in about 20-30 % of the time, receiving the wrong response from the xerver (an old value).
I tried tracking the error but can't find it since it only appears sometimes after a call. The following code is just the relevant part of my problem.
<p>I like <b><span id="numCom"><?php echo liked_comments(); ?></span></b> comments.</p>
// Each comment has a likeComment and CountComments function that triggers the Ajax:
let likeIcon = document.getElementsByClassName("like-icon");
for(let i = 0; i < likeIcon.length; i++){
likeIcon[i].addEventListener("click", likeComment);
likeIcon[i].addEventListener("click", countComments);
}
function likeComment(){
let child = this.children[0];
let mainID = this.parentElement.parentElement.id;
url = "ajax/like_comment.php";
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function(){
if(this.status == 200){
let result = this.responseText;
if(result == "t"){
child.classList.remove("red-text");
} else if (result == "f") {
child.classList.add("red-text");
}
}
}
xhr.send("com_id=" + mainID);
}
function countComments(){
let numCom = document.getElementById("numCom");
let xhr = new XMLHttpRequest();
let url = "ajax/count_liked_comments.php";
xhr.open("GET", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onload = function(){
if(this.status == 200){
numCom.innerHTML = this.responseText;
}
}
xhr.onerror = function(){
console.log("Error");
};
xhr.send();
}
// In the php-files these functions are executed:
function like_comment($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
if($l == 0){
// UPDATE TO 1
$query = "UPDATE comments SET liked = 1 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
} else if($l == 1) {
// UPDATE TO 0
$query = "UPDATE comments SET liked = 0 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
}
}
function is_liked($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
return $l;
}
function liked_comments(){
global $db;
$query = "SELECT comment_id FROM comments WHERE liked = 1";
$result = mysqli_query($db, $query);
return mysqli_num_rows($result);
}
The code ist just a demonstration and not really neccessary to understand the problem. In another project. I change the value of a table row via Ajax and afterwards want to update the result. This only happens in about 70 to 80% of the time. All the other times and old value is returned
When I try to parse a reponseText using JSON.parse I get this error:
Uncaught SyntaxError: Unexpected token < in JSON at position 0 at
JSON.parse () at XMLHttpRequest.xhr.onreadystatechange
(index.js:75)
Any time i run the code below.
javascript/ajax code
function calculateMeasurements() {
clearResult();
clearErrors();
var form = document.getElementById("measurement-form");
var action = form.getAttribute("action");
// gather form data
var form_data = new FormData(form);
for ([key, value] of form_data.entries()) {
console.log(key + ': ' + value);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', action, true);
// do not set content-type with FormData
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
var json = JSON.parse(result);
if (json.hasOwnProperty('errors') && json.errors.length > 0) {
displayErrors(form, json.errors);
} else {
postResult(json.volume);
}
}
};
xhr.send(form_data);
}
var button = document.getElementById("ajax-submit");
button.addEventListener("click", calculateMeasurements);
})();
process.php
<?php
function is_ajax_request(){
return $_SERVER["HTTP_X_REQUESTED_WITH"] && $_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest";
}
$length = isset($_POST['length']) ? (int) $_POST['length'] : '';
$width = isset($_POST['width']) ? (int) $_POST['width'] : '';
$height = isset($_POST['height']) ? (int) $_POST['height'] : '';
$errors = [];
if(empty($length)){$errors[] = "length";}
if(empty($width)){$errors[] = "width";}
if(empty($height)){$errors[] = "height";}
if(!empty($errors)){
$result_array = array('errors' => $errors);
echo json.encode($result_array);
exit;
}
$volume = $length * $width * $height;
if(is_ajax_request()) {
echo json.encode(array('volume' => $volume));
} else {
exit;
}
?>
I noticed this error anytime I use the JSON.parse on result variable gotten from the ajax response.
i dont think their is anything wrong with your javascript code. please try using the php function properly. it should like this
echo json_encode(array('volume' => $volume));
echo json_encode($result_array);
AND NOT :
echo json.encode(array('volume' => $volume)); // json.encode as you have used in your code is wrong.
echo json.encode($result_array) // json.encode as you have used in your code is wrong.
it should work properly once this change is made
I got the action "pega" in controller Posts:
public function pega($id = null)
{
$posts = $this->Post->findById($id);
foreach($posts as $pok)
{
$foda = $pok['love'];
}
$this->set('foda', $foda);
$this->set('_serialize', array('foda'));
}
In my layout I try to do a requestto catch the data from function "pega" and put inside tag html:
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:81/booklandia/posts/pega/<?php echo $post['Post']['id'];? >.json";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var out = JSON.parse(xmlhttp.responseText);
function loap (){
var arr = out[0];
document.getElementById("id01").innerHTML = arr;
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
I have a webform and mymodule which alters it. The webform has a field stelle which gets populated based on the url query. For instance, if ?stelle=10 the field gets populated by the title of node with nid 10. If the query ?stelle is non-existant or followed by a nid which does not exist (is not of a certain content type) or does not contain a certain string the form will be redirecting to mynode?stelle=initiativ. The form has 2 fields to upload files via ajax, works good so far. Here is my code:
<?php
/**
* Altering the form! this will add class to the file upload/ remove buttons
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
$conf = mymodule_defaults();
if ($form_id == 'webform_client_form_' . $conf['nid']) {
if (isset($form['submitted']['field1'])) {
$form['submitted']['field1']['#process'] = array('mymodule_my_file_element_process');
}
if (isset($form['submitted']['field2'])) {
$form['submitted']['field2']['#process'] = array('mymodule_my_file_element_process');
}
$nid = $form['#node']->nid;
$form['actions']['submit']['#ajax'] = array(
'callback' => 'mymodule_webform_js_submit',
'wrapper' => 'webform-client-form-' . $nid,
'method' => 'replace',
'effect' => 'fade',
);
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
$hide_components = array(
'einleitung_standard',
'einleitung_initiativ',
);
$unhide_components = array();
if ($form['submitted']['stelle']['#default_value'] == '') {
$redirect_form = true;
}
elseif (is_numeric($form['submitted']['stelle']['#default_value'])) {
$nid = $form['submitted']['stelle']['#default_value'];
$node = node_load($nid);
if ($node === false || (isset($node->type) && $node->type !== 'job')) {
$redirect_form = true;
}
else {
$type = $node->type;
if ($type == 'job') {
$form['submitted']['stelle']['#default_value'] = $node->title;
$form['submitted']['stelle']['#attributes']['disabled'] = 'disabled';
$form['submitted']['related']['#value'] = $nid;
$unhide_components = array(
'einleitung_standard'
);
}
}
}
elseif ($form['submitted']['stelle']['#default_value'] == 'initiativ') {
// unset($form['submitted']['stelle']);
$form['submitted']['related']['#value'] = 'initiativ';
$unhide_components = array(
'einleitung_initiativ'
);
}
}
else {
// $redirect_form = true;
// this causes an error
}
This is the weird part:
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
...
else {
// $redirect_form = true;
// this causes an error
}
When I active the line to redirect the form when the if condition is false, the button to upload a file via ajax throws an error alert on click (see bottom for error). To me, this looks like the form alter hook is being called again when the file upload button is clicked without having my field stelle available - is that right? How to fix this?
And now the rest of the module, basically just alterings:
else {
// $redirect_form = true;
// this causes an error
}
foreach ($unhide_components as $key => $component) {
if (is_array($component)) {
foreach ($component as $_key => $_component) {
$index = array_search($_component, $hide_components[$key]);
if ($index !== false) {
unset($hide_components[$key][$index]);
}
}
}
else {
$index = array_search($component, $hide_components);
if ($index !== false) {
unset($hide_components[$index]);
}
}
}
// hide
foreach ($hide_components as $k=>$hc1){
if (is_array($hc1)) {
foreach ($hc1 as $hc2) unset($form['submitted'][$k][$hc2]);
} else {
unset($form['submitted'][$hc1]);
}
}
if ($redirect_form) drupal_goto('node/'.$conf['nid'], array('query'=>array('stelle'=>'initiativ')), 301);
}
}
function mymodule_my_file_element_process($element, &$form_state, $form) {
$element = file_managed_file_process($element, $form_state, $form);
$element['upload_button']['#attributes'] = array('class' => array('button'));
$prefix = '<label class="browse-slave">';
$prefix .= '<span class="button">' . t('Choose a file') . '</span>';
$element['upload']['#prefix'] = $prefix;
$element['upload_button']['#prefix'] = '</label>';
$element['remove_button']['#attributes'] = array('class' => array('button'));
$element['remove_button']['#prefix'] = '</label>';
return $element;
}
function mymodule_webform_js_submit($form, $form_state) {
// define the $sid variable (submission id from webform)
$sid = $form_state['values']['details']['sid'];
// if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
if ($sid) {
// first we have to load up the webform node object
$node = node_load($form_state['values']['details']['nid']);
// create an array up with the confirmation message, retreived from the webform node
$confirmation = array(
'#type' => 'markup',
'#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
);
// return the confirmation message
return $confirmation;
}
else {
// return the form
return $form;
}
}
The AJAX error is something like described here. Changing server/php settings didnt help it.
Thanks!
The form builder (and any hook alters) will be run when a form is validated, which happens on #ajax actions.
I like to throw static custom data in $form['#someProperty'] so that it's available in the build, validate, and submit functions. Something like this should help you:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
// ...
if (isset($_GET['stelle'])) {
$form['#stelle'] = $_GET['stelle']; // This will always be there.
}
// ...
}
Another option would be to throw the $node that you load in the form, like $form['#stelle_node'] = node_load(...) and obviously only do that when the nid is actually available to you, so that you don't overwrite it with empty data when the form builder runs again in the future.
When i was working with ajax in drupal 6 the hash symbol in url or request caused an error everytime..... so i replaced url with this
data.url.replace(/%2523/, '%23');
I need to check language already Exist condition{ without page reload/load }, so that i called ajax at End of my function.
I have a doubt, that can i call function inside ajax call to get a responce before return true statement execute????
my code :
function languageValid(){
if( field1 === '' ){
return false;
}
if( field2 === '' ){
return false;
}
if( field3 === '' ){
return false;
}
// e.g : ajax call
$.post(sitePath+"candidate/index/langues-update",{},function(responce){
// responce as '0' or '1'
exist = $.trim(responce);
if(exist){
return false;
}else{
return true;
}
});
return true;
}
calling function
languageValid();
function does not wait for ajax call respond,
it will execute return true before ajax call
pls share your suggestion!!!!
Your bloc below returns a value from the $.post() function.
if(exist){
return false;
}else{
return true;
}
If you want to get the response, you can try:
function languageValid(){ .....
var result = $.post('url',{},function(responce){}).responseText;
exist = $.trim(result);
if(exist){
return false;
}else{
return true;
}
}