HTML value within JSON being truncated when received via ajax in ie - ajax

Weird sentence.. weird issue.
I have some json like this:
{
"id":"1246",
"cost":"62.1603017827",
"material":"Blue",
"class":"veroblue",
"label":" ($62.16)",
"mlabel":"Blue",
"html":"<div class=\"quote\">\r\n\t<input type=radio name=\"QuoteUploads[selectedMaterial]\" value=\"1246\" checked=checked id=\"quote_uploads_quote_1246\" data-color=\"#A9BCF5\"\/>\r\n\t<label for=\"quote_uploads_quote_1246\" ><span class=\"swatch veroblue\"><span class=\"big veroblue\"><\/span> <\/span><span class=\"text\">Blue <span class=\"cost\">($62.16)<\/span><\/span><\/label>\r\n<\/div>\t"
},
When my page loads the above is already in an object qobj. When I console.log(qobj.html) I get:
<div class="quote">
<input type=radio name="QuoteUploads[selectedMaterial]" value="1250" id="quote_uploads_quote_1250" data-color="#FBF8EF"/>
<label for="quote_uploads_quote_1250" ><span class="swatch duruswhite"><span class="big duruswhite"></span> </span><span class="text">Polypropylene-Like <span class="cost">($62.21)</span></span></label>
</div>
Now, when an input changes I reload the JSON via AJAX and store it in qobj. After it is reloaded console.log(qobj.html) outputs:
</span> </span>Polypropylene-Like ($62.21)</span></span></label>
</div>
The json string is encoded and rendered the same way when it is injected and received via ajax. Does anyone have any idea why this is happening?

Related

PHP doesnt read textarea content sended by ajax call

i'm dealing with this ajax call:
HTML:
A form has a textarea in which user can type some text
<div id="step-3">
<h2 class="StepTitle">Testo</h2>
<form id="text" class="form-horizontal form-label-left">
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Textarea <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea id="textarea" name="testo" data-parsley-required="true" class="form-control col-md-7 col-xs-12"></textarea>
</div>
</div>
</form>
<ul id="error3_ul" class="list-unstyled">
<li id="error3_li"></li>
</ul>
</div>
JS:
This function is called by smartwizard. When user types some text and pushes button, an ajax call starts to do a server side check before to effectively insert text into db.
function onFinishCallback()
{
var data = $('#textarea').val();
$.ajax({
method: 'post',
data: data,
dataType: 'html',
url: "include/library/pull_sim.php",
success: function(result) {
successmessage = 'Data was succesfully captured';
$("#error3_li").text(result);
},
});
}
PHP:
Php receives the posted textarea value, check if a similar_text is already into db and if yes, it alerts that to user by the ajax call result.
if((!ISSET($_POST['testo'])))
$val='';
else
$val=$_POST['testo'];
$q_sim='select nciarfata from nciarf.nciarfata';
$s_sim=mysqli_query($conn,$q_sim);
$n_sim=mysqli_num_rows($s_sim);
if ($n_sim>0)
{
$simil=array();
for ($i=0;$i<$n_sim;$i++)
{
$rou=mysqli_fetch_row($s_sim);
similar_text($val, $rou[0], $percent);
if ($percent>=95.0)
{
array_push($simil,$rou[0]);
}
}
echo"val=$val, rou[0]=$rou[0], percent=$percent";
}
Question:
In my opinion something goes wrong in server side, probably in the 1st if.
Php doesnt recognized the posted value and then assign val="" instead of real text typed by user before..
Why?
Thanks for helping me.
I find the solution here:
Can't figure out why PHP not receiving POST data from $.ajax call
It wasn't a textarea issue but an ajax jquery one (data option).

WebAPI Knockout JS Image Binding

I am using Knockoutjs to render a user profile page. For which I am calling a Web API service which returns User details with its Profile Picture.
var MessageFrom = {
FromUserProfileId: self.FromUserProfileId,
FromUserName: self.FromUserName,
FromUserPictURL: self.FromUserPictURL
}
<div id="comments" class="comments" data-bind="with: viewModel">
<div class="comment clearfix" data-bind="foreach: Messages">
<div class="comment-avatar">
<img class="img-circle" data-bind="attr:{'src': FromUserPictURL}" alt="avatar">
</div>
<header>
<h3 data-bind="text: FromUserName"></h3>
<div class="comment-meta"><p data-bind="text: moment(DatePosted).format('LLL')"></p> </div>
</header>
<div class="comment-content">
<div class="comment-body clearfix">
<p data-bind="text: MessageBody"></p>
</div>
</div>
</div>
</div>
The URL of the Image returned from WebAPI is Relative URL like ~/Content/Member/Image1.jpg. While its bind with Image URL shows like "http://sitename.com/profile/~/Content/Member/Image1.jpg".
Everything works great accept Profile Picture
I need to work something on binding as as I cannot change the Path coming from Database.
Appreciate your suggestions.
Regards,
Your binding looks okay. For starters I would use your IE or Chrome developer tools ( F12 ) and change the src manually of the image to find out what exactly works for you.
You say you recieve this: ~/Content/Member/Image1.jpg
Setting the src to this should work: /Content/Member/Image1.jpg
You can change your message object client-side like this, once you're sure what is needed, but I think this should suffice:
var MessageFrom = {
FromUserProfileId: self.FromUserProfileId,
FromUserName: self.FromUserName,
FromUserPictURL: self.FromUserPictURL.replace('~','')
}

Refresh g:each tag via AJAX call in Grails

I have a statistical panel which displays the last registered users. I want to implement a AJAX call to upload the panel without having to reload the full page.
I have the following code in my view:
<g:each in="${lastUsers}" var="user">
<div class="mt-comments">
<div class="mt-comment">
<div class="mt-comment-img">
<g:if test="${user?.avatar}">
<img src="${createLink(controller:'controllerUser',
action:'image', id: user?.id)}" />
</g:if>
<g:else>
<img class="img-circle"
src="${resource(dir: 'img/profile', file: 'user_profile.png')}"/>
</g:else>
</div>
<div class="mt-comment-body">
<div class="mt-comment-info">
<span class="mt-comment-author">${user?.username}</span>
<span class="mt-comment-date">
<g:formatDate date="${user?.dateCreated}"/>
</span>
</div>
<div class="mt-comment-text">${user?.email}</div>
<div class="mt-comment-details">
<g:if test="${user?.enabled}">
<span class="mt-comment-status label label-sm label-success circle">
</g:if>
<g:else>
<span class="mt-comment-status label label-sm label-info circle">
</g:else>
<g:formatBoolean boolean="${user?.enabled}"/>
</span>
<ul class="mt-comment-actions">
<li>
<g:link controller="user" action="edit" id="${user?.id}">Edit</g:link>
</li>
</ul>
</div>
</div>
</div>
</div>
</g:each>
Also, I have a button when it is clicked calls the AJAX function. The Ajax function receives the data successful in JSON format. From there, I don't know upload my g:each tag.
I have tried the remoteFunction of Grails to use the upload attribute, but an error appears: No javascript provider is configured and I have searched the solution but anything works me.
The AJAX call:
$('.button').click(function() {
$.ajax({
url: URL,
success: function(data) {
console.log(data[index]);
console.log(val.username);
console.log(val.dateCreated);
console.log(val.email);
console.log(val.enabled);
console.log(val.avatar);
console.log(val.id);
},
error: function(){
},
});
Thanks for helping me.
Instead of Using JSON Data, You can do this using grails templates and jQuery load method. Here is a quick POC.
Template (_userComments.gsp)
This will act as a reusable view which can be called via AJAX or can be included directly in other views.
<g:each in="${lastUsers}" var="user">
<div class="mt-comments">
.....
</div>
</g:each>
View (main.gsp)
Our Main View.
<div class="userComments">
<!-- When the Page is Loaded, We need render this without an Ajax Call -->
<g:render template="userComments" model="['lastUsers':lastUsers]"/>
</div>
Javascript
$('.button').click(function() {
$( ".userComments" ).load( "user/userComments" );
});
Controller
We are defining two methods one for the main view and one for the ajax call.
def index() {
def lastUsers = User.list();
render(view:'main', model: [lastUsers: lastUsers])
}
// Ajax Call
def userComments() {
def lastUsers = User.list(); // what ever your fetch logic is
render(template:'userComments', model: [lastUsers: lastUsers])
}

How do I use an Angular.JS generated form to upload a file (and other fields) through AJAX to Symfony2?

I'm trying to send a form generated by Angular.js through an AJAX call to a Symfony controller action in order to be saved. The form is generated in an ng-repeat after receiving some JSON data (including an entry ID). The code looks as follows.
<div ng-repeat="job in sc.careers">
<div>
<h2>{[{job.title}]}</h2>
<span ng-if="job.super">{[{job.super}]}</span>
<div>
<h4>Role</h4>
<span ng-bind-html="job.role"></span>
</div>
<div class="col-md-4">
<h4>Required Skills</h4>
<span ng-bind-html="job.skills"></span>
</div>
<div class="col-md-4">
<h4>Media</h4>
Some other content \ media
</div>
</div>
<hr/>
<div class="join-us">
<button ng-click="sc.joinUs[$index] = true" ng-hide="sc.joinUs[$index]">Apply for this position</button>
<div ng-show="sc.joinUs[$index]">
<h4>Join Us</h4>
<span>Some random text</span>
<form>
<input type="hidden" name="job_id" value="{[{job.id}]}" />
<label for="email">E-Mail</label>
<input type="email" id="email" name="email" />
<label for="motivation">Cover Letter & CV link</label>
<textarea id="motivation" name="motivation"></textarea>
<label for="resume">Upload your resume</label>
<input type="file" name="resume">
<button type="submit">Send your application</button>
</form>
</div>
</div>
</div>
* most class names have been redacted to keep the code as relevant to the question as possible
I have not yet placed an ng-click -> submit directive. Also, my Angular is configured for the use of the "{[{" and "}]}" delimiters so as not to interfere with TWIG.
I have searched the internet for possible answers but they all pertain to Symfony generated forms (which include validation tokens). Other answers (such as this one) don't quite describe the Angular side of things or don't describe sending the entire form.
In the end, I'm not exactly sure how to approach this. If it's too complicated I'd even settle for not using AJAX at all and submitting directly to Symfony. (actually, the only reason I want to use AJAX is to make the site feel more "snappy").
For what it's worth I'm using the latest stable versions of PHP, Symfony and Angular.JS at the time of writing.
Update
So i managed to send the data back to the controller by using an Agular JS module that enables the use of ng-model on file inputs and by using FormData like so:
var formObject = new FormData;
formObject.append('email', self.careers[index].application.email);
formObject.append('motivation', self.careers[index].application.motivation);
formObject.append('resume', self.careers[index].application.file);
formObject.append('jobID', self.careers[index].id);
$http.post('/app_dev.php/jobs/apply', formObject, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined } // Allows angular to choose the proper Content-Type
})
The only problem left now is that Symfony does not recognize my form data as being valid. The controller action looks like this (for now).
public function applyAction(Request $request) {
$jobApplication = new JobApplications(); // This is the entity I use to store everything.
$form = $this->createFormBuilder($jobApplication)
->add('jobId')
->add('email')
->add('coverLetter')
->add('file')
->getForm();
$form->handleRequest($request);
$response = array (
'isValid' => $form->isValid(), // false
'isSubmitted' => $form->isSubmitted(), // false < that's why the form is invalid
'isErrors' => $form->getErrorsAsString() // empty array
);
if ($form->isValid()) { // is not valid so the following section is not complete
$em = $this->getDoctrine()->getManager();
$jobApplication->upload();
$em->persist($jobApplication);
$em->flush();
//return $this->redirect($this->generateUrl('idea_presentation_careers'));
}
return new JsonResponse($response);
}

Form Submit using a Javascript to invoke webflow transition, doesn't take the updated value on form

I am trying to invoke a form submit using javascript (jquery) to invoke a webflow transition. It works and the submit invokes the desired transition. But, the updated radio button values is not reflected on the model object which is posted.
Here is the code:
<form:form method="post" action="#" commandName="infoModel" name="pageForm">
<form:input type="input" path="testMsg" id="success" />
<input type="button" id="clearSelections" value="Clear Selections">
<div class="question">
<h4><c:out value="${infoModel.questionInfo.description}"/> </h4>
<form:radiobuttons path="infoModel.answerId"
itemValue="answerId" itemLabel="answerDescription" items="${infoModel.answers}" delimiter="<br/>" />
</div>
<input type="submit" name="_eventId_saveQualitativeInput" value="Save" id="save" />
$(document).ready(function() {
$('#tabs').tabs();
//Clear selections (copy is server-side)
$('#clearSelections').click(function() {
//$('input[type="radio"]').prop('checked', false);
$('input[type="radio"]').removeAttr('checked');
$('#save').trigger('click');
});
});
</form:form>
The form:radiobutton, generates the below html:
<div class="question">
<h4>Is this a general obligation of the entity representing a full faith and credit pledge? </h4>
<span>
<input type="radio" checked="checked" value="273" name="infoModel.answerId" id="infoModel.answerId1">
<label for="infoModel.answerId1">Yes</label>
</span>
<span><br>
<input type="radio" value="274" name="infoModel.answerId" id="infoModel.answerId2">
<label for="infoModel.answerId2">No</label>
</span>
<br>
<span class="error"></span>
</div>
The input id= "success" value is registered and when the control goes to the server, the value of input id= "success" is updated in the "infoModel" object. But the value of answerId is not updated on the "infoModel" object.
Thoughts if i am missing something in the form:radiobutton element or if there is something else wrong?
Thanks in advance!
EDIT:::::::
Thanks mico! that makes sense. I stripped of some of the code first time to make it precise, but i have a list which is being used for building the radio-buttons, below is the code:
<c:forEach items="${infoModel.list["index"]}" var="qa" varStatus="rowCount">
<div class="question">
<h4><c:out value="${question.questionInfo.description}"/> </h4>
<form:radiobuttons path="list["index"][${rowCount.index}].answerId" itemValue="answerId" itemLabel="answerDescription" items="${question.answers}" delimiter="<br/>" />
<br>
</div>
</c:forEach>
Could you please suggest how i could try this one out?
NOTE: The same code works on a regular form submit on click of a button of type submit. Its the javascript form submit which is not working. I also tried to do whatever i want to do in javascript and then invoke the button.trigger('click'); form got submitted but the changes made on form in my javascript didnt reflect.
With commandName inside a form:form tag you set "Name of the model attribute under which the form object is exposed" (see Spring Documentation). Then in path you should tell the continuation of the path inside the model attribute.
With this said I would only drop the extra word infoModel from path="infoModel.answerId" and have it rewritten as path="answerId" there under the form:radiobutton.

Resources