Ajax request results in attempted 302 redirect instead of returning JSON - ajax

I am using an ajax request on click to trigger a controller JsonResult in MVC. When I click, I receive an HTML response instead of JSON, here is my code:
$('.platform-list-item').click(function (e) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "#Url.Action("PlatformClick", "To")",
data: JSON.stringify({ "platform": $(this).find(".platform-click").val() }),
success: function (data) {
console.log("worked!");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
});
The $(this).find(".platform-click").val() is a string value. Here is my controller code in ToController.cs:
[HttpPost]
public JsonResult PlatformClick(string platform)
{
Debug.WriteLine("PlatformClick");
Debug.WriteLine(platform);
return Json("test");
}
Here are the two new events that show up in my Network Tab through Developer tools. Where did I go wrong? Thank you!
EDIT: Adding HTML View per request:
<div class="platform-to-container">
<div id="platform-container">
<div class="album-container">
<div class="album-img-container">
<img crossorigin="anonymous" id="album-img" src="https://i1.sndcdn.com/artworks-9vhl8uXrclxW-0-t500x500.jpg" />
</div>
</div>
<div class="platform-links-container">
<div class="artist-song">#Model.Album.AlbumName</div>
<div class="artist-song-container">
<img class="artist-img" src="https://i1.sndcdn.com/avatars-000438614124-cca9kq-t500x500.jpg" />
<div class="artist-name">#Model.Artist.ArtistName</div>
</div>
<div class="platform-list-container">
#if (!String.IsNullOrWhiteSpace(Model.Album.SpotifyLink))
{
<div class="platform-list-item">
<div class="platform-logo-container">
<img class="platform-logo" src="https://s3.amazonaws.com/unlink/platform-images/music-service_spotify_v3.svg" />
</div>
<div class="platform-btn-container">
<div class="link-btn"><i class="fas fa-play"></i>Stream</div>
</div>
<input type="hidden" class="platform-click" value="spotify" />
</div>
}
#if (!String.IsNullOrWhiteSpace(Model.Album.ItunesLink))
{
<div class="platform-list-item">
<div class="platform-logo-container">
<img class="platform-logo" src="https://s3.amazonaws.com/unlink/platform-images/music-service_itunes_v2.svg" />
</div>
<div class="platform-btn-container">
<div class="link-btn"><i class="fas fa-play"></i>Download</div>
</div>
<input type="hidden" class="platform-click" value="itunes" />
</div>
}
#if (!String.IsNullOrWhiteSpace(Model.Album.AppleMusicLink))
{
<div class="platform-list-item">
<div class="platform-logo-container">
<img class="platform-logo" src="https://s3.amazonaws.com/unlink/platform-images/music-service_applemusic_v2.svg" />
</div>
<div class="platform-btn-container">
<div class="link-btn"><i class="fas fa-play"></i>Stream</div>
</div>
<input type="hidden" class="platform-click" value="appleMusic" />
</div>
}
</div>
</div>
</div>
</div>

Related

Laravel Post or GET data with html but as raw text

Laravel Post html but as raw text
i'm use tinymce and normal input
i try to normal post and get with url and ajax
<div class="modal fade" id="addpromotion" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="addpromotionLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form action="{{ route('admin.blog.create') }}" id="addpromotionform" method="post" enctype="multipart/form-data">
#csrf
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="modal-header">
<h1 class="modal-title fs-5" id="addpromotionLabel">เพิ่มโปรโมชั่น</h1>
{{-- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> --}}
</div>
<div class="modal-body">
<div class="mb-3 mx-5">
<input type="file" class="form-control" name="image" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<input type="text" name="title" class="form-control" placeholder="Title" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<input type="text" name="description" class="form-control" placeholder="Description" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<textarea id="tinymcecreate" class="tinymce" name="body"></textarea>
</div>
<input type="hidden" name="type" value="promotion">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger">บันทึก</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">ปิด</button>
</div>
</form>
</div>
</div>
</div>
body=%3Cp%3E%3Cstrong%3Ecustom%3C%2Fstrong%3E%3C%2Fp%3E
when console.log ( data before post )
_token=bNPyuZroL8QIJN3beZJyFYaVELWIyNb9kpvX48Zn&csrf_token=bNPyuZroL8QIJN3beZJyFYaVELWIyNb9kpvX48Zn&title=qwqgqw&description=qgqg&body=%3Cp%3E%3Cstrong%3Ecustom%3C%2Fstrong%3E%3C%2Fp%3E&type=promotion
$('#addpromotionform').on('submit', function(ed) {
tinymce.triggerSave();
ed.preventDefault();
var TinyAjaxPost = $('#addpromotionform').serialize();
var formData = new FormData(this);
console.log(TinyAjaxPost);
$.ajax({
type: "post",
url:'{{URL::to("/admin/blog/create")}}',
data: formData,
cache:false,
dataType: 'html',
contentType: false,
processData: false,
success: function(data) {
console.log('success'+Object.values(data.message));
},
error: function(error) {
console.log('error'+error);
}
});
});
but when post to controller i check with dd($request)
body don't have html tag but have only raw text ... custom
public function admin_blog_create(Request $request)
{
$file_name = time() . '.' . request()->image->getClientOriginalExtension();
$request->image->move(public_path('image/tinymce'), $file_name);
$tiny = [
'image' => $file_name,
'title' => $request->title,
'description' => $request->description,
'body' => $request->body,
'type' => 'blog',
];
blog::create($tiny);
return response()->json(['status'=>true, 'message' => $request->body]);
/* return redirect()->back(); */
}
and i try to use Get with url when check data with dd($request) have only raw text custom
Tools
Laravel 9
TinyMCE 6
How i post or get with full html to database ?
XSS Protection it is a problem.
i'm try to disable xss in controller
$this->middleware('XSS');
Can post ( request ) html data to database
enter image description here
Type this code if you are experiencing error 419
// Ajax CSRF Setup Code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The correct way to send, in addition to viewing the data in the console
$('#addpromotionform').on('submit', function(ed) {
ed.preventDefault();
//console log data
var TinyAjaxPost = $('#addpromotionform').serialize();
var copy = $("#addpromotionform iframe").contents().find('#tinymce').clone();
copy = $(copy).html();
console.log(TinyAjaxPost,copy);
$.ajax({
type: "post",
url:'{{URL::to("/admin/blog/create")}}',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('success'+Object.values(data.message));
},
error: function(error) {
console.log('error'+error);
}
});
});

Laravel-7: Edit Image via modal and ajax

So I'm done with trying to upload image using modal and ajax, now I want to edit it. So my modal trigger is the uploaded picture itself. My problem is how do I get the data from the database and display it on my modal? Am also having this error:
Uncaught ReferenceError: data is not defined
MODAL TRIGGER: (user/gallery.blade.php)
#foreach($galleries as $art)
<div class="card" style="width: 20rem;">
<img class="card-img-top" src="/storage/upload/{{$art->upload}}" alt="Card image cap" id="editUpload" data_id="{{$art->id}}">
</div>
#endforeach
MODAL: (scripts/editUploadModal.blade.php)
<div class="modal .modal-lg bg-white" tabindex="-1" id="editUploadModal">
<div class="container">
<h3 class="text-center">EDIT UPLOAD</h3>
<form id="editForm" enctype='multipart/form-data'>
<div class="modal-body">
<input type="text" name="id" id="editId">
<input type="file" name="upload" id="editUpload"><br>
<img class="card-img-top" src="#" id="imageResult"><br>
<label>CAPTION</label>
<input type="textarea" class="form-control bg-white border-dark" name="description" id="description">
</div>
<button class="btn btn-danger">DELETE UPLOAD</button>
<button class="btn btn-success">SAVE</button>
</form>
</div>
</div>
SCRIPT: (scripts/editUpload_script.blade.php)
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('body').on('click','#editUpload', function(){
$('#editUploadModal').modal('show');
console.log($(this).attr('data_id')); //DISPLAYS ID
data_id = $(this).attr('data_id');
//THIS IS WERE AM STUCK FROM BECAUSE IT IS NOT DISPLAYING THE DATA IN CONSOLE
$.get("{{route('gallery.index')}}" + '/' + data_id + '/edit', function(Data){
console.log(data.upload + " " + data.description)
$('#editId').val(data.id);
$('#editUpload').val(data.upload);
$('#description').val(data.description);
//display image
reader.onload = function () {
$('#imageResult').attr("/storage/upload/" + data.upload);
});
});
});
</script>
CONTROLLER: (GalleryController.php) btw, I added use Response;
public function edit(Gallery $gallery)
{
return Response::json($gallery);
}

Getting 422 Unprocessable Entity while submitting Form with ajax in Laravel

I'm submitting my form using ajax in laravel
Output:
{"message":"The given data was invalid.","errors":{"name":["The name field is required."],"image":["The image field is required."]}}
View:
{{ Form::open(array('route' => 'ajax-add-record','enctype' => 'multipart/form-data','files'=> true,'class'=>'add','id'=>'frmadd')) }}
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<h2 class="card-inside-title">Name</h2>
<div class="form-line focused">
{{ Form::text('name','',['class'=>'form-control','placeholder'=>'Name','id'=>'name']) }}
</div>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6">
<div class="form-group">
<h2 class="card-inside-title">Image</h2>
<div class="form-line focused">
{{ Form::file('image',['class'=>'form-control']) }}
</div>
</div>
</div>
</div>
<button class="btn btn-info add_button btn-xs p-3 hide" type="button"><i class="material-icons">add</i> Add</button>
</div>
{{ Form::close()}}
Script:
$('#frmadd').submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: APP_URL+'/add',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response)
{
},
error: function(data)
{
}
});
});

Laravel - How to capture Ajax Request Payload Data?

Not a Duplicate Question!!!
Here is my code, using Laravel 5.4.
Form in .blade.php file:
<form id="read-data-form" name="form" method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input name="comCode" id="comCode" type="hidden" value=""/>
<label><span class="text-danger">*</span> Upload File :</label>
<input name="file" id="fileToUpload" type="file" accept="text/*" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6 ">
<div class="text-right">
<button type="submit" class="btn operations-btn btn-default" id="upload">Upload</button>
<button type="button" class="btn operations-btn btn-default" id="stop">Stop</button>
</div>
</div>
</div>
</form>
Ajax-request in .js file:
$("form #read-data-form").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var promise = $.ajax({
url: 'read_data/file/check',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
encode: true
});
promise.done(function(response){
});
promise.fail(function(error){
});
promise.always(function(){
});
}
Browser Console > Network > Headers > Request Payload:
Route in web.php file:
Route::post('read_data/file/check', 'ReadDataController#checkFile');
checkFile() method in ReadDataController.php file:
public function checkFile(Request $request)
{
$comCode = trim($request->comCode);
$file = $request->file('file');
dd($file);
}
Browser Console > Network > Preview > Request Payload:
This is how output of dd().
Issue:
File could not be captured as in a normal 'multipart/form-data' form without ajax request.
OK. Finally, I have a solution which is given by a senior person.
Removed this code:
$file = $request->file('file');
Added the following codes:
$uploadDirPath = 'C:/uploaded_files/';
$uploadFile = "moved_uploded_file.txt";
$request->file('file')->move($uploadDirPath, $uploadFile);
$uploaded_file = $uploadDirPath.$uploadFile;

AJAX - Complex user activation for login

Now this may sound complicated but I have a page called activation.php where after the user has registered using my reg.php page, they get sent an email with their activation link - activation.php then a get method of k to make activation.php?k=activation-code-here
I made it so it returns the status of the activation, e.g - success of error.
On my reg.php page, I want to make it so it uses ajax to open a sweetAlert popup saying 'Activation Success'. It will get the popup depending on if the users 'activ_status' changed from 0 to 1 in the database when they access the activation.php page with a correct activation key.
Here is my code :
Activation.php
<?php
include('inc/conf/db_.php');
$result = '';
if(empty($_GET['k']) || (!$_GET['k']))
{
header('Location: login.php');
exit();
$result = 'Hacker Tried Accessing Auth Page';
}
$key = mysqli_real_escape_string($con,$_GET["k"]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php
if (!empty($key))
{
$query = "SELECT * FROM users WHERE activ_key = '$key'";
$result = mysqli_query($con,$query) or die('error');
if (mysqli_num_rows($result))
{
$row = mysqli_fetch_array($result);
if ($row['activ_status']!='1')
{
$query = "update users set activ_status='1' where activ_key='$key'";
$result = mysqli_query($con,$query) or die('error');
$result = 'Successfuly Activated, Return To Your Other Page.';
}
else
{
$result = "Account Already Activated";
}
}
else
{
$result = 'Invalid Access Token';
}
}
else
{
$result = 'Error';
}
?>
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<br>
<center><div id="result"></center>
<br>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Activation Status</b></h4>
<br>
<center><img src="assets/images/loading.gif"></center>
<br>
<center><div class="alert alert-info"><button type="button" class="close"></button><?php echo $result; ?></div></center>
<?php return $result; ?>
</body>
</html>
My reg.php page
<?php
include('inc/conf/db_.php');
if (session_status() == PHP_SESSION_ACTIVE) {
session_start();
}
if(isset($_SESSION['user_i']) || isset($_SESSION['login'])) {
header('Location: index.php');
exit();
}
else if (session_status() == PHP_SESSION_NONE) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="assets/plugins/bootstrap-sweetalert/sweet-alert.css" rel="stylesheet" type="text/css">
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<center><img src="assets/images/loading.gif" id="loading-image" style="display:none"/></center>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Sign Up</b></h4>
<form id="registered_form" class="form-horizontal m-t-20">
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="email" type="email" required="" placeholder="Email"></div>
<span class="fa fa-envelope form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="username" type="text" required="" placeholder="Username"></div>
<span class="fa fa-user form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="password" type="password" required="" placeholder="Password"></div>
<span class="fa fa-lock form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LeGFxYUAAAAAOqjyovTS3H0D1HS4IBgoHMvG4y_"></div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="checkbox checkbox-primary" style="text-align: center;"> <input type="checkbox" name="checkbox" value="agree"> <label for="checkbox-signup"> I accept Terms and Conditions </label></div>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12"> <button class="btn btn-primary w-md waves-effect waves-light" type="submit" id="reg_button" style="width: 100%;" >Register</button></div>
</div>
<div class="form-group m-t-30 m-b-0">
<div class="col-sm-12 text-center"> Already have an account?</div>
</div>
</form>
</div>
</div>
</div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.validate.js"></script>
<script src="assets/plugins/bootstrap-sweetalert/sweet-alert.min.js"></script>
<script>
$(document).ready(function()
{
jQuery.validator.addMethod("noSpace", function(value, element)
{
return value.indexOf(" ") < 0 && value != "";
}, "Spaces are not allowed");
$("#registered_form").submit(function()
{
if ($("#registered_form").valid())
{
$('#loading-image').show();
var data1 = $('#registered_form').serialize();
$.ajax({
type: "POST",
url: "inc/pgs/register.php",
data: data1,
success: function(msg)
{
$('#loading-image').hide();
console.log(msg);
if(msg == '')
{
swal({
title: "Registration Success!",
text: "Your registration was successful! Check your email and click on your activation link to be able to access your account. NOTE: Keep this page open",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
else
{
swal("Registration Error!", msg, "error");
}
}
});
$.ajax({
type: "GET",
url: "activation.php",
data: data1,
success: function(msg)
{
if(msg == 'Successfuly Activated, Return To Your Other Page.')
{
swal({
title: "Activation Success",
text: "You can now login!",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
}
});
}
return false;
});
});
</script>
</body>
</html>
<?php } ?>
I found a piece of code that might help me. It doesn't seem to be loading the modal up though:
$.ajax({
url: 'activation.php',
type: 'GET',
dataType: 'jsonp',
cache: 'false',
timeout: 32000,
success: function(data) {
if(data == 'Successfuly Activated, Return To Your Other Page.')
{
swal("Activation Completed!", "You can now login using the link at the bottom of the page - Already have an account?", "success")
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
ajaxCall();
},
});
Please clearly explain the problem you are having that is preventing the code from working as you intend.
If my interpretation is correct, you want to update the registration page that user keeps open while activating in another window, and then reflect the change on the registration page using AJAX. In fact, in this case you want to send data from the server to your client (you want something to change when a change happens on the server in the database). In this case, a simple solution is to repeatedly request the status (for instance every 2 seconds) using setTimeout. Other solutions exist but are probably overkill, such as long polling or web sockets.

Resources