Ajax Registration FOSUserBundle - ajax

I am trying to register a user via AJAX using FOSUserBundle.
The problem is that the name value in the form is fos_user_registration_form_[username] so it isn't accepted by javascript as array.
<input type="text" id="fos_user_registration_form_username" name="fos_user_registration_form[username]" required="required" />
How can I solve that?
Can I change the name parameter in FOSUserBUndle to fos_user_registration_form_username ?
How can I create an array with fos_user_registration_form_[username] value in Javascript?
$("#registerButton").click( function(){
data = {
fos_user_registration_form_[username]:$("#name").val(), // HERE IS WHERE IT CRASHES, IN THE [username] field.
fos_user_registration_form_[email]:$("#email").val(),
fos_user_registration_form_[plainPassword]:$("#password").val(),
};
$.ajax({
type: "POST",
url: serviceURL,
asyn:false,
data: data,
dataType: "json",
success: function(res) {
alert("success"); // JUST FOR TEST
}
});
I am testing a basic example..
This works (triggers the alert)
<script type="text/javascript">
data = {
fos_user_registration_form_username:"blabla"
};
alert(true);
</script>
This doesn't works: (do not trigger the alert)
<script type="text/javascript">
data = {
fos_user_registration_form_[username]:"blabla"
};
alert(true);
</script>

To fetch the data from your input fields, you need to combine the name_of_the_form_ + the name_of_the_field. For example:
fos_user_registration_form_ + username => fos_user_registration_form_username
data = {
fos_user_registration_form[username]:$("#fos_user_registration_form_username").val(),
fos_user_registration_form[email]:$("#fos_user_registration_form_email").val(),
fos_user_registration_form[plainPassword]:$("#fos_user_registration_form_plainPassword").val(),
};

Related

AJAX form redirecting on submit when using CKeditor

I am trying to submit an AJAX form with Laravel using the code shown below. After I submit the form, all the data is saved in the database as expected apart from the following field which is displayed as NULL in the database.
<textarea name="content" id="editor"></textarea>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form');
$.ajax({
type:'POST',
url: form.attr('action'),
data: form.serialize(),
success:function(data){
alert(data.successful);
}
});
})
});
</script>
public function addVideo(Request $request)
{
$addVideo = new cms_videos;
$addVideo->VideoStatus = $request->VideoStatus;
$addVideo->VideoTitle = $request->VideoTitle;
$addVideo->VideoStrapline = $request->VideoStrapline;
$addVideo->VideoURL = $request->VideoURL;
$addVideo->VideoDescription = $request->content;
$addVideo->VideoTags = $request->VideoTags;
$addVideo->MetaActName = $request->MetaActName;
$addVideo->MetaRegion = $request->MetaRegion;
$addVideo->MetaGenre = $request->MetaGenre;
$addVideo->MetaVenue = $request->MetaVenue;
$addVideo->VideoCoverPhoto = $request->VideoCoverPhoto;
$addVideo->save();
return response()->json(['successful'=>'Video successfully added']);
}
After doing some research I was told to add the following code to the top of the code shown above:
CKEDITOR.instances.SurveyBody.updateElement();
Now all the data is submitted to the database as expected. However when I now submit the form instead of an alert popping up saying "Successful" I am now redirected to the form action URL where it displays "Successful". How can I stop this redirection and display the alert on the page the form was submitted?
I'm not sure but I think the issue is here when you do e.preventDefault() because it works for the button click not for form submission. Try this out and hope it will help you.
Notice: you have to add upload_video class to your forms
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// If the button is type of submit you can remove this part of code
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form.upload_video');
form.submit();
})
});
//
$("form.upload_video").on('submit',function(e){
e.preventDefault();
let form = $(this),data=form.serialize();
//
let content=FCKeditorAPI.GetInstance('content').getData();
data['content']=content;
//
$.ajax({
type:'POST',
url: form.attr('action'),
data: data,
success:function(data){
alert(data.successful);
}
});
});
</script>
This part
let content=FCKeditorAPI.GetInstance('content').getData();
May not be true because I don't work with CKEDITOR right now and i can't test it but you can console.log() it before you send the ajax request and make sure the content exists in the variable as you expected.

Ajax submit an image with form - pass the FormData - trigger submit

I simply want to use ajax to submit a form with an image from a phone.
If I use the below code as a simple function - the form data is not passed.
If I use the code as is - it works but the user has to click the submit button.
How do I either pass the FormData properly to a simple $.ajax({}); submit?
OR
How do I trigger the code below when a picture is taken or selected?
I have this - it works fine when user clicks submit:
// how do I trigger this when image file is selected?
$("#Upload_Form").submit(function(e){
e.preventDefault();
// OR - how do I get FormData with image without using: '$("#Upload_Form").submit(function(e)'
var formData = new FormData(this);
$.ajax({
// POST details are here etc.
});
});
Bind the change event for the file input like below and then trigger the submit event of the form or make an ajax call right away with the FormData see below demo.
If you want to know how to submit image using FormData and ajax see this answer
$("#my-form").on('submit', function(e) {
e.preventDefault();
// OR - how do I get FormData with image without using: '$("#Upload_Form").submit(function(e)'
var formData = new FormData(this);
console.log("sending Ajax call now");
$.ajax({
// POST details are here etc.
});
});
$("#my-file").on('change', function() {
//you can either trigger the form submit here
var form = $("#my-form");
$("#my-form").submit();
//OR
//use this to send the ajax call to upload the image
// var form=$("#my-form")[0];
// var formData = new FormData(form);
// $.ajax({
// type: "POST",
// url: 'your/url',
// data: formData,
// processData: false,
// contentType: false,
// success: function (data) {
// console.log("SUCCESS : ", data);
// },
// error: function (e) {
// console.log("ERROR : ", e);
// }
// });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form" enctype="multipart/form-data">
<input type="file" name="my-file" id="my-file" />
<input type="submit" name="submit" value="submit" />
</form>
Update
Note: if you want to use an ajax call to send the formData you need to set the processData and contentType to false. contentType: false only available from jQuery 1.6 onwards.

Ajax request type POST returning GET

I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>

Load images to server from mobile site

I am developing a mobile site using asp.net and jquery. no plugin. just simple jquery.I am using the
<input type="file"/>
of HTML5.
So few questions to get the big picture:
1.Can i load files without jquery plugin, but only simple jquery? Just picking the file, send it using ajax and catch it on server side?
2. I have noticed the Request.Files attribute of the Request object. Will it get filled only with post of the whole page or can i get my files there using Ajax?
3.In case the answer in 2 is "No!", how do i exclude the files data on the server side?
Thanks
This is the solution i have found:
JS:
<script type="text/javascript">
$(document).ready(function () {
$('#inputFile').on('change', function () {
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
var formData = new FormData();
formData.append(file.name, file)
$.ajax({
url: 'AjaxPage.aspx',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (response) {
alert(response);
},
error: function (e) {
alert(e);
}
});
});
});
</script>
CS: (On ajax page to catch the files and manipulate them as you will)
var files = Request.Files;
HTML:
<body>
<div>
<input type="file" id="inputFile" />
</div>
</body>

Pass Ajax POST variable to JQuery UI dialog

Below is an Ajax POST variable I use to return some information to an ASP MVC3 View. However, I cannot get the .dialg() pop-up function to work. Right now you click on the icon that calls GetProgramDetails(pgmname), and nothing happens. First time using Ajax, so any suggestions would be appreciated. Thx!
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
function GetProgramDetails(pgmname) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
});
request.done(function (data) {
$('#data').dialog();
});
</script>
EDIT
I've updated the request.done function to include a simple alert to see if the code was being called. After stepping through with Chrome's debugger, I saw that the code inside was completely skipped over.
request.done(function (data) {
alert("HERE!");
$('#programExplanation').html(data);
});
SECOND EDIT
Here is the controller code the ajax is returning a value from:
[HttpPost]
public string PopDetails(string programName)
{
BatchPrograms batchprograms = db.BatchPrograms.Find(programName);
if (batchprograms == null) return string.Empty;
StringBuilder s = new StringBuilder();
s.Append(batchprograms.ProgramName + " - " + batchprograms.ShortDescription);
s.Append("<br />Job Names: " + batchprograms.PrdJobName + ", " + batchprograms.QuaJobName );
s.Append("<br /> " + batchprograms.Description);
return s.ToString();
}
You need to use the success method to handle the callback, like so:
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(function(data){ $('#data').dialog()} );
This will launch the dialog for you, but if you want to get the response data to work with it, you can have GetProgramDetails take a second parameter which is a callback for after the data is loaded like so:
function GetProgramDetails(pgmname, callback) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(callback);
}
This way after the response is received you can handle what to do with the data in your implementation of the callback, in this case it seems like you will be setting data in the dialog and launching the dialog.

Resources