How post login form data in YII2 - ajax

Login page is on index when i click on login menu then popup display when i fill up all then post all data in site controller after success redirect to customer panel,But i am getting error in ajax code url,How resolved this problem?
$("#login").submit(function () {
var formData = new FormData($(this)[0]);
$.ajax({
url: "<?php echo Url::toRoute(["site/customerloged"]); ?>",
type: "POST",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if(data == 1){
window.location.href = 'customer/home';
return false;
}else{
alert(data);
return false;
}
}
});
return false;
});

Related

laravel - ajax formdata wont show in controller

I have tried many different combination for AJAX Setup in order to send the formData to controller. Somehow I cannot get the form input inside my controller despite trying to return it will all type of ways. May I know what did I miss that causing me not be able to get the input in controller?
$("#formCropUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
console.log(Array.from(formData));
$.ajax({
url: url,
type: "PATCH",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
cache: false,
dataType: false,
contentType: false,
processData: false,
data:formData,
success: function (response) {
console.log(response);
return false;
},
});
});
public function update(Request $request){
$UserId = Auth::user()->id;
$Company = Company::where('id', Auth::user()->company_id)->first();
return $request->all();
}
use
<meta name="csrf-token" content="{{ csrf_token() }}">
in head
and jQuery code
$('#form_submit').submit(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var base = window.location.origin;
let formData = new FormData(this);
let my_url = base + "/article-store";
$.ajax({
type: 'post',
url: my_url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: (data) => {
},
error: function (data) {
}
});
});
After quite a bit of digging, since what I am doing is using the PATCH request, it's still not working as of now with FormData. To solve it, we need to spoof the method by appending the PATCH method to formData and our AJAX settings to be changed to POST. Then you'll receive all the request inside your controller.
Reference:
https://laracasts.com/discuss/channels/laravel/ajax-formdata-and-put-fails
https://laracasts.com/discuss/channels/javascript/axiosajax-http-patch-requests-with-file-not-working
$("#formCropUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
formData.append('_method', 'PATCH');
console.log(Array.from(formData));
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: url,
data:formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
return false;
},
});
});

merge ajaxform with ajax to upload image

I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).

Ajax Form Submit with attachment

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.
How can i get this to work?
Here is my ajax code:
$('#submit_btn').click(function () {
$.ajax({
type: 'POST',
url: '/contact.php',
dataType: "json",
data: $('#contactform').serialize(),
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});
On the php side i have phpmailer setup and am handling the file so:
if(!empty($_FILES['file'])) {
$_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
}
$('#submit_btn').click(function () {
var formData = new FormData($('#contactform'));
$.ajax({
type: 'POST',
url: '/contact.php',
// dataType: "json",
data: formData ,
processData: false,
contentType: false,
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});

display values returned by json

I have simple question to display data on html page. Following code displays array of json data on screen. but, I want to display it by each element such as "url", "img_url" and so on.
could you please let me know who to do it ?
ajax code
var dataString = 'url=' + pathname + '&img_name=' + img_name + "&tag=" + tag;
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
//handleError();
alert("error");
} else {
var data = xhr.responseText;
$('#tt').html("<div id='message'></div>");
$('#message').html(data);
}
}
});
json return
{"cid":"14","url":"http:\/\/localhost\/","img_url":"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg","img_name":"mat_173317134c.jpg","html":"<div id=\"hotspot-19\" class=\"hs-wrap hs-loading\">\r\n<img src=\"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg\">\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"95\" data-y=\"64\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nasdf\r\n<\/div>\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"168\" data-y=\"53\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nrere\r\n<\/div>\r\n<\/div>\r\n","jscript":""}
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
success: function (data) {
for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}
}
});
I hope this is what you need.

using success event ofjquery / ajax to fill and set dropdownlist value

i have a Ajax request to Fill an edit form like..
function FillLiveDetail(event, LiveID)
{
$.ajax
({
type: "POST",
url: MyUrl + '/GetLiveDetail',
data: '{LiveID: "' + LiveID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
var LiveDetail = data.d;
$('#ClassName').val(LiveDetail[0].Title);
$('#ClassDesc').val(LiveDetail[0].Desc);
$('#SearchKey').val(LiveDetail[0].Keys);
$('#Date').val(LiveDetail[0].Date);
$('#Hour').val(LiveDetail[0].Hours);
$('#Minute').val(LiveDetail[0].Minuts);
$('#AM_PM').val(LiveDetail[0].AmPm);
$('#Duration').val(LiveDetail[0].Duration);
$('#rdbLivePrivacy).prop('checked',true);
CategoryList(event, 'MyddlCategory');
$('#MyddlCategory').val(LiveDetail[0].CategoryID);
}
});
}
function CategoryList(event, ddl_Category_ID)
{
var ddl_Category = $('#'+ddl_Category_ID);
event = event || window.event || e.srcElement;
event.preventDefault();
$.ajax
({
type: "POST",
url: ServiceUrl +'/FillAllCategories',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
var MyCategoryList = data.d;
$(ddl_Category).html('<option value="0" selected="selected">All Category</option>');
for(var m=0; m<MyCategoryList.length; m++)
{
var row = ['<option value="'+MyCategoryList[m].CategoryID+'">'+MyCategoryList[m].CategoryName+'</option>'].join('\n');
$(ddl_Category).append(row);
}
}
});
}
My problem is, I can not change the definition of my function CategoryList() because i used it at many places in my project...
In this context the success: event of CategoryList() function Fire when success: event of FillLiveDetail() function completes that is why i am unable to set the value of MyddlCategory...
please suggest me any thing that may work..
Close the selector quote in this line $('#rdbLivePrivacy').prop('checked',true);
Try setting async property of ajax call to false
$.ajax
({
type: "POST",
async: false,
url: ServiceUrl +'/FillAllCategories',
...

Resources