I want to change the URL of the update operation. The end point of the URL should be gotten from an input. How can I achieve this? The following doesn't work.
$(document).ready(function(){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return {"issue":o};
};
<form role="form">
<div class="form-group input-group">
<div class="row">
<div class="col-md-6">
<label>Issue ID * </label>
<select class="form-control selectclass" id="issueid"></select>
</div>
<div class="col-md-6">
<label>Tracker * </label>
<select class="form-control" name="tracker" id="tracker">
<option value="1">Bug</option>
<option value="2">Feature</option>
<option value="3">Support</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label>Subject </label>
<input class="form-control" placeholder="Issue Subject" name="subject" id="subject">
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" rows="6" name="description" id="description"></textarea>
</div>
<button type="submit" id="submit" class="btn btn-default">Submit Button</button>
<button type="reset" class="btn btn-default">Reset Button</button>
</form>
$('#submit').on('click', function(){
var x=document.getElementById('issueid').value;
$.ajax({
type : 'PUT',
url: 'http://localhost/redmine/issues'+ x +'.json',
contentType:'application/json',
data:JSON.stringify($('form').serializeObject()), // post data || get data
success : function(msg, status, jqXHR) {
console.log(msg, status, jqXHR);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
console.log(x);
});
});
Inputs are gotten from a form and sent to Redmine API. URL should look like below, http://localhost/redmine/issues/2.json
When dynamically populating your id="issueid" select make sure that you properly set the value attribute of the options:
$('.selectclass').append('<option value="' + value.id + '">' + value.id + '<option>');
Also fix the url for your next AJAX request by adding a trailing / after issues:
url: 'http://localhost/redmine/issues/' + x + '.json'
Related
Hi im doing an App with Datatables and i have a problem when i want to try to edit a record in the datatables this is my js function in app.blade.php
$(document).on('click', '.editButton', function(e) {
e.preventDefault();
var id = $(this).data("id");
var editRoute = "{{ url('admin/user/' . auth()->user()->id . '/messages') }}";
console.log(id);
token();
$.ajax({
/* url: "{{ route('admin.messages.edit', ['user' => auth()->user()->id, 'message' => ':id']) }}".replace(':id', id), */
url: editRoute + "/" + id,
type: "GET",
/* dataType: 'json', */
success: function(result) {
console.log(result)
var message = result.data;
console.log(message);
$('.id').val(message.id);
$('.text').val(message.text);
$('.url').val(message.url);
$('.note').val(message.note);
$('.tipes').val(message.tipes);
$('.start_time').val(message.start_time);
$('.end_time').val(message.end_time);
$('.active').val(message.active);
$('#modalEdit').modal('show');
$('.modal-title').text('Update Message');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
the console.log(result) is empty and console.log(message) is undefined
this is the edit function in the controller
public function edit(Request $request)
{
$result = Message::where('id', $request->id)->first();
if ($result) {
return response()->json([
'message' => "Data Found",
"code" => 200,
"data" => $result
]);
} else {
return response()->json([
'message' => "Internal Server Error",
"code" => 500
]);
}
}
i want to edit the message with a modal, but the js fuction doesnt work properly, the var message is undefined
this is my route file
Route::middleware('auth')
->namespace('Admin')
->name('admin.')
->prefix('admin')
->group(function () {
Route::get('/', 'HomeController#index')->name('home');
Route::resource('/user', 'UserController');/* ->except(['edit', 'update']); */
Route::resource('/user/{user:id}/messages', 'MessagesController');
/* Route::resource('user.messages', MessagesController::class); */
});
Route::get('messages', 'Admin\MessagesController#getMessages')->name('get.messages');
Auth::routes();
this is my table structure
enter image description here
and its my form for edit the message
<div id="modalEdit" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal Header</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="update">
<div class="modal-body">
<div class="form-group">
<label for="text">Testo</label>
<input type="text-area" class="form-control text" id="text" name="text">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="text" class="form-control" id="url" name="url">
</div>
<div class="form-group">
<label for="note">Note</label>
<input type="text" class="form-control" id="note" name="note">
</div>
<div class="form-group">
{{-- <label for="tipes">Tipo</label>
<input type="text" class="form-control" id="tipes" name="tipes"> --}}
<label for="tipes">Tipo</label>
<select name="tipes" id="tipes">
<option value="A">A</option>
<option value="B">B</option>
</select>
</div>
<div class="form-group">
<label for="start_time">Inizio</label>
<input type="date" class="form-control" id="start_time" name="start_time">
</div>
<div class="form-group">
<label for="end_time">Fine</label>
<input type="date" class="form-control" id="end_time" name="end_time">
</div>
<div class="form-group">
<label for="active">Attivo</label>
{{-- <input type="text" class="form-control" id="active" name="active"> --}}
<label for="active">Attivo</label>
<select name="active" id="active">
<option value="1">Si</option>
<option value="0">No</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
public function edit(Request $request,$id)
{
$result = Message::where('id', $id)->get();
if ($result) {
return response()->json([
'message' => "Data Found",
"code" => 200,
"data" => $result
]);
} else {
return response()->json([
'message' => "Internal Server Error",
"code" => 500
]);
}
}
you need to pass $id parameter into function edit! try it! may be it works
$(document).ready(function() {
$('.editbutten').on('click', function(e) {
e.preventDefault();
var id = $(this).data("id");
var editRoute = "{{ url('admin/user/' . auth()->user()->id . '/messages') }}";
console.log(id);
token();
$.ajax({
/* url: "{{ route('admin.messages.edit', ['user' => auth()->user()->id, 'message' => ':id']) }}".replace(':id', id), */
url: editRoute + "/" + id,
type: "GET",
/* dataType: 'json', */
success: function(result) {
console.log(result)
var message = result.data;
console.log(message);
$('.id').val(message.id);
$('.text').val(message.text);
$('.url').val(message.url);
$('.note').val(message.note);
$('.tipes').val(message.tipes);
$('.start_time').val(message.start_time);
$('.end_time').val(message.end_time);
$('.active').val(message.active);
$('#modalEdit').modal('show');
$('.modal-title').text('Update Message');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
});
I have a from with button to submit it. Now i would like to pass same variables to another page to inset them in database. For that, i would like to pass the variables using an anchor link with GET with id's.
But how do it add an anchor link to the form where when i submit the form using the button the anchor link also gets triggered..
function splitAndResolve() {
var errorIds = [];
$('[name="error-selection-checkboxes"]:checked').each(function() {
errorIds.push($(this).val().split("-")[1]);
});
var taskVersion = 1;
if (errorIds.length > 0 && errorIds.length < $('[name="error-selection-checkboxes"]').length) {
var dataObj = {
'errorReportIdsToRemove': errorIds,
'user': 'user#mail.com'
};
var baseUrl = $(location).attr("href").substring(0, $(location).attr("href").lastIndexOf('/') + 1);
var splitTaskResponse = $.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70/split",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
}).responseJSON;
var taskId = splitTaskResponse.newTaskId;
// We need to update the version without which version on the UI and the DB are different.
taskVersion = splitTaskResponse.currentTaskPostSplit.version;
window.open(baseUrl + taskId, '_blank');
}
dataObj = {
'taskResolutionStatus': $("#inputResolution").val(),
'taskResolutionStatusDetail': $("#inputResolutionDetail").val(),
'taskResolutionNote': $("#inputNotes").val(),
'changeset': $("#inputChangeset").val(),
'requiresReview': $("#requiresReviewCheckBox").is(':checked'),
'version': taskVersion
};
$.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
});
enableStatusDropdown();
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal clearfix" onsubmit="return splitAndResolve()">
<div class="form-group">
<label for="changeset" class="col-sm-2 control-label">Changeset</label>
<div class="col-sm-10">
<input class="form-control" type="text" name="changeset" id="inputChangeset" readonly="">
</div>
</div>
<div class="form-group">
<label for="taskResolutionStatus" class="col-sm-2 control-label">Resolution</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatus" id="inputResolution">
<option disabled="" selected="" value=""> -- Choose one -- </option>
<option value="ESCALATE">Escalate</option>
<option value="ALREADY_FIXED_IN_OSM">Already fixed in osm</option>
<option value="NOT_ENOUGH_INFORMATION">Not enough information</option>
<option value="NO_FIX_REQUIRED">No fix required</option>
<option value="FIXED">Fixed</option>
</select>
</div>
</div>
<div class="form-group" id="inputResolutionDetailDropdown">
<label for="taskResolutionStatusDetail" class="col-sm-2 control-label">Detail</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatusDetail" id="inputResolutionDetail">
<option value="LOW_PRIORITY_AREA">Low priority area</option>
<option value="KNOWN_BUG">Known bug</option>
<option value="ERROR_BASED_ON_BAD_DATA">Error based on bad data</option>
<option value="TRUE_EXCEPTION">True exception</option>
</select>
</div>
</div>
<div class="form-group">
<label for="taskResolutionNote" class="col-sm-2 control-label">Notes</label>
<div class="col-sm-10">
<textarea class="form-control" name="taskResolutionNote" id="inputNotes" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<label for="requiresReview" class="col-sm-2 control-label">Requires review</label>
<div class="col-sm-2">
<input class="form-control" name="requiresReview" type="checkbox" style="box-shadow: none" id="requiresReviewCheckBox">
</div>
</div>
<input id="taskResolutionButton" type="submit" class="btn btn-primary">
<button id="taskCancelButton" type="button" class="btn btn-default" onclick="hideResolutionOverlay()">Cancel</button>
</form>
<input id="taskResolutionButton" type="submit" class="btn btn-primary" onclick="$('#your_form_id').submit();>
I have a basic bootstrap form, and I want to pass the input type through to php via ajax. I can get the input name & value with serializeArray().
How would I extend the output from serializeArray to also include the input 'type'?
Some more info... Here's my current form...
<form id="second_example_form" class="form-horizontal core_form_submission" action="#" method="post" data-callback="<?php echo __DIR__ . '/form-second-example.callback.php'; ?>">
<div class="form-group">
<label class="col-sm-2 control-label" for="email">Email</label>
<div class="col-sm-5">
<input id="email" class="form-control" required type="email" placeholder="Email" name="email">
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
And here's the ajax calling js...
$('#form').on('submit', function(e) {
e.preventDefault();
var data = form.serializeArray();
$.post('ajax/forms.ajax.php', {
data: data
}, function(r) {
var json = JSON.parse(r);
}
});
var data = form.serializeArray(); works great to pass the name and value... but doesn't include input type.
Can anyone help?
Serialize does not provide that, you would have to construct name value of all the types and pass that to your server.
$('form').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serializeArray();
$('input, select', this).each(function() {
formData.push({
name: $(this).attr('name') + '_type',
value: $(this).prop('tagName').toLowerCase()
});
});
console.log(formData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="second_example_form" class="form-horizontal core_form_submission" action="#" method="post" data-callback="<?php echo __DIR__ . '/form-second-example.callback.php'; ?>">
<div class="form-group">
<label class="col-sm-2 control-label" for="email">Email</label>
<div class="col-sm-5">
<input id="email" class="form-control" required type="email" placeholder="Email" name="email">
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
You can not do this normal serializeArray function I did quick fix and sharing code with two alternative.
$(document).ready(function(){
//Make sure name and id will be same id=email_email name = email_email
var fields = $( "#second_example_form" ).serializeArray();
fields = fields.map(function(val){
val.type = $( "#"+val.name ).attr("type");
return val;
});
console.log(fields);
//Change only name and add type with name seprated by _ like this name = name_type
var fields = $( "#second_example_form" ).serializeArray();
fields = fields.map(function(val){
val.type = val.name.split("_")[1]
return val;
});
console.log(fields);
});
body, select {
font-size: 14px;
}
form {
margin: 5px;
}
p {
color: red;
margin: 5px;
}
b {
color: blue;
}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<form id="second_example_form" class="form-horizontal core_form_submission" action="#" method="post" data-callback="<?php echo __DIR__ . '/form-second-example.callback.php'; ?>">
<div class="form-group">
<label class="col-sm-2 control-label" for="email">Email</label>
<div class="col-sm-5">
<input id="email_email" class="form-control" required type="email" placeholder="Email" name="email_email">
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
I ended up doing a mixture of the other answers, to create a new array from scratch.
// Collect all of the fields in the form, their values and types
function gather_form_fields(form)
{
var output = {};
form.find(':input').each(function(){
var type = $(this).attr('type'),
name = $(this).attr('name'),
val = $(this).val();
// If it's a select or other element without a 'type', return the element
if (type == null) {
type = $(this).prop('tagName').toLowerCase();
}
// remove the submit button
if (type == 'submit') {
return true;
}
output[name] = {
type: type,
name: name,
value: val
};
});
return output;
}
This then produces an object with the type, name and value e.g.
data = {
first_name: {
name: "first_name",
type: "text",
value: "joe"
},
email: {
name: "email",
type: "email",
value: "jbloggs#test.com"
}
}
You can send the type within the value or the name.
In your php you can use explode to separate the type from the value/name. Here's how to send it within the value.
$('#form').on('submit', function(e) {
e.preventDefault();
var fields = e.serializeArray();
for(var i = 0; i < fields.length; i++){
var item = e.find(':input').eq(i);
var fieldType = item.attr("type") === null ? item.prop("tagName") : item.attr("type");
fieldType = fieldType === null ? item.prop("tagName") : fieldType;
data.push({"name": fields[i].name, "value": fieldType + "|" + fields[i].value })
}
$.post('ajax/forms.ajax.php', {
data: data
}, function(r) {
var json = JSON.parse(r);
}
});
I have a form, after document.ready() I load data into this form, but form values (device name) was cleared on mobile browsers, after tap on screen.
$.ajax({
type: 'GET',
url: "api.ashx",
data: "operation=device.get&deviceid=" + deviceid,
success: function(response) {
var apiResponse = jQuery.parseJSON(response);
if (apiResponse.result == 'true') {
$("#name").val(apiResponse.name);
if (apiResponse.online == 'true') {
$("#status").html('<span class="label label-success">online</span>');
} else {
$("#status").html('<span class="label label-red">offline</span> Был в сети: ' + apiResponse.lastvisit);
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form id="deviceinfoform" action="#" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label class="col-sm-3 control-label">Device name <span class="require">*</span>
</label>
<div class="col-sm-6 controls">
<input id="name" name="name" required="" type="text" placeholder="Device name" maxlength="100" class="form-control"></input>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Device status</label>
<div class="col-sm-6 controls">
<div id="status" class="form-control">
<span class="label label-success">online</span>
</div>
</div>
</div>
</div>
</form>
Problem is solved. The problem was in bootstrap-responsive-tabs plug-in.
fakewaffle.toggleResponsiveTabContent = function () {
var tabGroups = $('.nav-tabs.responsive');
$.each(tabGroups, function () {
var tabs = $(this).find('li a');
$.each(tabs, function () {
var href = $(this).attr('href').replace(/#/g, ''),
tabId = "#" + href,
panelId = "#collapse-" + href,
tabContent = $(tabId).html(),
panelContent = $(panelId + " div:first-child").html();
//!!!clear all dynamic content
$(tabId).html(panelContent);
$(panelId + " div:first-child").html(tabContent);
});
});
};
Updating to the latest version solved a problem.
I have this textarea in my MVC project
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
but when I try to send this to a Json call like this
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>
I get the original value of #Model.content instead of the new value.
Edit
my script.js code
function updateComment(id, title, content) {
return $.get("/Chapter/GetJSON_Update",
{
id: id,
title: title,
content: content
},
'json');
};
the entire code from my Edit.cshtml
#model Academia_Unitate.Models.Chapter
#{
ViewBag.Title = "Edit " + Model.title;
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.Partial("~/Views/Shared/_TinyMCE.cshtml")
<div id="edit">
<h1>
Edit #Model.type.name
</h1>
<div class="" role="form">
<div class="form-group">
<label class="sr-only" for="title">Title</label>
<input class="form-control" type="text" id="edit-title" placeholder="Enter a title" value="#Model.title" required="required" />
</div>
<div class="form-group">
<label class="sr-only" for="content">Content</label>
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
</div>
<button type="submit" class="btn btn-success" id="save-btn" onclick="save()"><span class="glyphicon glyphicon-ok"></span> Save</button>
<span id="message-edit-loading" class="alert hidden"></span>
<span id="message-edit-error" class="alert alert-danger hidden"></span>
</div>
</div>
<input type="hidden" value="#Model.id" id="edit-id"/>
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>
You most likely have more than one on your page, either make their id attributes unique or target the index in your jQuery.