I am using knockout js and the knockout mapping plugin.
My problem is after calling the ajax post my view (ui) is not updating.
Only if I reload the page the data will be updated.
<tbody data-bind="foreach: WorkData">
<td data-bind="text: id"></td>
<td data-bind="text: user_name"></td>
<button class="btn btn-xs btn-success" data-bind="click: $parent.postTmpData" role="button">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
</button>
</tbody>
<script>
function ViewModel() {
var self = this;
var data = <?php echo json_encode($this->data); ?> ;
self.WorkData = ko.mapping.fromJS(data);
self.postTmpData = function(entry) {
$.post("<?php echo Config::get('URL'); ?>/work/confirmWorkPost/", entry, function(returnedData) {
ko.mapping.fromJS(returnedData, self);
})
}
}
ko.applyBindings(new ViewModel());
</script>
Is returnedData what you want to replace WorkData with? It's only possible if they are in the same structure. In that case, try this:
$.post("<?php echo Config::get('URL'); ?>/work/confirmWorkPost/", entry, function(returnedData) {
ko.mapping.fromJS({'WorkData': returnedData}, self);
})
This was the solution for me:
ko.mapping.fromJS(JSON.parse(returnedData), self.WorkData);
Related
I have a vue component with a div and a button and into another div I have two components
<script>
export default {
name: 'excursion-backend-component',
methods:{
doRedirection: function () {
window.location = APP_URL+"/excursiones/create";
}
},
mounted() {
console.log(APP_URL+"/excursiones/create");
console.log("aaaa");
}
}
</script>
<template>
<div class="container">
<h3>Adicionar excursión</h3>
<div style="text-align: right">
<a class="btn btn-primary" :href="doRedirection"><i class="fa fa-plus"></i> Adicionar</a>
</div>
<br>
<div>
<excursion-list-component></excursion-list-component>
<excursion-add-component></excursion-add-component>
</div>
</div>
</template>
But I don't see the button on the navigator.
What is wrong?
Here is how I see the page
:href="" expecting string with url to navigation, but you using method.
Use #click instead :href, if you want to use method.
<a #click="doRedirect">... </a>
Or, may be, move it to computed block
computed: {
excursionesUrl () {
return APP_URL+"/excursiones/create";
}
}
I am new to AJAX and I am trying to send some data to the controller using the AJAX. on clicking the button "Start Event", nothing is happening..
This is my jsp page where I have written the AJAX code
<c:forEach items="${scheduledEvents}" var="event">
<div class="col-md-3" id="eventId">
<div class="card-counter primary">
<div id="head" class="card-counter head-color"></div>
<span class="count-head">${event.eventName}</span>
<br>
<span class="count-name">Date : ${event.date}</span>
<span class="count-name">Location : ${event.location}</span>
<span class="count-name">Hosted By : ${event.hostName}</span>
<span class="count-name">Description : ${event.description}</span>
<br>
<br>
<div class="count-join">
<button class=" btn" id="${event.linkId}" style="background-color: #cc3300;"><font style="color: white;">Start Event</font></button>
</div>
</div>
</div>
</c:forEach>
<script type="text/javascript">
$(function() {
$('.count-join').on('click',function(){
var eventData = $(this).attr("id")
.ajax({
url : 'startEvent?data=' +eventData,
type : 'GET',
contentType : 'application/json',
success : function(data){
$
.get(
'${pageContext.request.contextPath}/startEvent',
function(data,status) {
$("#eventId").html(data);
}
);
}
});
});
});
</script>
And this my controller mapping
#RequestMapping(value="/dashBoard/startEvent")
public ModelAndView startScheduledEvent(#RequestParam("data")String data)
{
System.out.println(data);
return new ModelAndView("DashBoard");
}
Where am I wrong? please give some detailed explanation as I do not know much about AJAX. Thanks in advance.
As per you controller #RequestMapping, you have missed the /dashBoard in ajax call.
I'm trying to get Vue to update value through an api call. I log the searches two times: ones outside the beforeCreate and once inside. Outside it gives the initial value of 'searches', inside the correct, new value.
The main problem is that I don't see the updated values.
<div id="app">
<!-- shows when there are no searches -->
<p class="text-center" v-if="searches === null">Er werden nog geen zoekopdrachten uitgevoerd.</p>
<!-- this div gets repeated for every search -->
<div class="search border border-info rounded p-3 m-3 row" v-for="search in searches">
<table class="col-6">
<tr>
<td class="text-info">Zoekwoorden</td>
<td v-for="keyword in search.keywords">#{{ keyword }}</td>
</tr>
<tr class="even">
<td class="text-info">Platforms</td>
<td v-for="platform in search.platforms">#{{ platform }}</td>
</tr>
<tr>
<td class="text-info">Gerelateerde zoekwoorden</td>
<td v-for="keyword in search.all_keywords">
#{{ keyword }}
</td>
</tr>
<tr class="even">
<td class="text-info">Locatie</td>
<td>Voskenslaan, Gent</td>
</tr>
<tr>
<td class="text-info">Datum</td>
<td>#{{ search.created_at }}</td>
</tr>
</table>
<div class="col-6 text-right">
<button type="button" class="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="search-id text-secondary">##{{ search.id }}</h3>
<a :href="'/searches/' + search.id " role="button" class="btn btn-info details-button">Details...</a>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
var $root = new Vue({
el: '#app',
data:
{
searches: [
{ id: 123, keywords: ['sample', 'sample'], platforms: ['sample', 'sample'] },
{ id: 123, keywords: ['sample', 'sample'], platforms: ['sample', 'sample'] }
]
},
beforeCreate: function ()
{
var vm = this;
$.get("api/searches", function(data, status){
vm.$set(vm,'searches', data); //zet de waarde van searches gelijk aan de opgehaalde
console.log(vm.searches); //geeft juiste opgehaalde searches
});
}
});
console.log($root.searches); //geeft de initiële twee sample searches
</script>
I think you may want to try beforeMount instead of beforeCreate.
beforeCreate fires before anything in the component is initialied, according to the docs:
Called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup.
I haven't tested it, but I would be willing to bet this is your issue. Since there are no watchers or data structures initialized, your call to vm.$set(vm,'searches', data) is being overwritten by the component data structure
Whereas beforeMount is called after data and events/watchers have been initialized:
Called right before the mounting begins: the render function is about to be called for the first time.
I would probably also just push to the existing array instead of replacing it as such as this (especially if you have populated the search array as in your example):
beforeMount: function () {
var vm = this;
$.get("api/searches", function(data, status){
vm.searches.push(...data); // assuming data is an array
console.log(vm.searches);
});
},
mounted: function(){
var vm = this;
console.log(vm.searches);
},
I have the following code:
<?PHP
if (isset($_POST['submit'])) {
header("Location: http://mysite.com");
}
?>
<form name="form1" action="" method="post">
Name: <input name="name" type="text">
<input type="submit" value="submit" name="submit">
</form>
The problem is that when I submit the form the redirection to mysite.com takes too long time, 5-10s.
I would like to display a messege "Loading... Please wait" och show an animated image so that I know that something is happening.
How do I do in javascript och ajax?
I don't know if it's possible (but I don't think so) but you could add exit(); after setting the header so the rest of the script isn't executed and sent to the browser. That could reduce the time a bit.
What you could try is to do the redirection with javascript instead of a http header.
<?php if (isset($_POST['submit'])): ?>
<script>
alert('Loading... Please wait');
document.location.href = 'http://mysite.com';
</script>
<?php endif; ?>
5-10 secs to submit the page. First of all try to figure out why it is taking that much time.
ANyways, If you just want to see some message when you press submit button, then simply you can add any div ( with initially hidden ). And on click of submit button you can show this div.
See the sample code:
<?PHP
if (isset($_POST['submit'])) {
header("Location: http://mysite.com");
}
?>
<div id='loadingDIV' style='display: none;'></div>
<form name="form1" action="" method="post">
Name: <input name="name" type="text">
<input type="submit" value="submit" name="submit" onclick='showLoadingAndSubmit();'>
</form>
function showLoadingAndSubmit(){
document.getElementById ('loadingDIV').innerHTML = 'Form submitting. Please wait...';
document.getElementById ('loadingDIV').style.display = 'block';
return true;
}
you should have something like this
the loading has image GIF moving until the ajax request end and then the loading become hidden
where result has the database result grid search on screen
<tr valign="top">
<td id="results" colspan="8" align="center" width="100%" height="250px">
</td>
</tr>
<tr valign="top" id="loading" style="display:none;">
<td colspan="8" width="100%" align="center">
<img name="loading_image" src="images/loading.gif" border="0" width="214" height="200">
</td>
</tr>
function search(tableEvent){
try
{
document.getElementById('loading').style.display="";
var params = 'formAction=' + document.mainForm.formAction.value;
params += '&tableEvent=' + tableEvent;
params += '&txtActionDivisionDesc=' + document.mainForm.txtActionDivisionDesc.value;
createXmlHttpObject();
sendRequestPost(http_request,'Controller',false,params);
ValidationResult();
}
catch(e)
{
alert(e.message);
}
}
function ValidationResult()
{
try
{
if (http_request.readyState == 4)
{
var errors = http_request.responseText;
errors = errors.replace(/[\n]/g, '');
if (window.ActiveXObject)
{// code for IE
xmlRecords=new ActiveXObject("Microsoft.XMLDOM");
xmlRecords.loadXML(errors);
}
else
{
xmlRecords=document.implementation.createDocument("","",null);
parser=new DOMParser();
xmlRecords=parser.parseFromString(errors,"text/xml");
}
document.getElementById('loading').style.display="none";
document.getElementById('results').innerHTML = errors;
http_request = false;
}
}//end try
catch(e)
{
document.getElementById('results').innerHTML = errors;
return;
}
}
I have a button "btnGetAddress" on my razor page .On clik of this button,I am calling a Jquery to get my addressItmes object to be displayed on to my View page.
On clicking "btnGetAddress" I am able to hit my "JsonResult GetAddresses()" and retrieve records within my Jquery (success: function (data)).and this data has multiple address records. But I do not know how to take this data to my view .Please help me to get my data to be displayed on to my View
When my page get loaded,the user will see only the "btnGetAddress" button .When the user click on the btnGetAddress, it will call the Jquery Click function to fetch all address records from database and display each set of records on the page
$("#btnGetAddress").click(function () {
debugger;
var selected = $("#ddlType").val();
if (selected == "")
{ selected = 0; }
var dataToSend = {
SelectedTypeId: selected
};
$.ajax({
type: "GET",
url: '#Url.Action("GetAddresses", "Content")',
data: { SelectedTypeId: selected },
success: function (data) {
debugger;
},
error: function (error) {
var verr = error;
alert(verr);
}
});
pasted below is my JsonResult GetAddresses() which gets called to retrieve addressItems
public JsonResult GetAddresses()
{
model.AddressItems = AddressService.RetrieveAllAddress();
// My AddressItems is of type IEnumerable<AddressItems>
return Json(model.AddressItems, JsonRequestBehavior.AllowGet);
}
Here is my razor View Page where the address records are to be displayed.
........................
<input type="submit" id="btnGetAddress" name="btnSubmit" value="Show Addresses" />
if (!UtilityHelper.IsNullOrEmpty(Model.AddressItems))
{
foreach (var AddressRecord in Model.AddressItems)
{
<fieldset >
<legend style="padding-top: 10px; font-size: small;">Address Queue(#Model.NumRecords)
</legend>
<table>
<tr>
<td>
<span>Index</span>
</td>
<td>
</td>
<td>
<input type="submit" id="btnDelete" name="btnSubmit" value="X" />
<br />
</td>
</tr>
<tr>
<td>
<span>Address1</span>
<br />
</td>
<td>
#Html.EditorFor(model => AddressRecord.Address )
#Html.ValidationMessageFor(model => AddressRecord.Address)
</td>
</tr>
<tr>
<td>
<span>Description</span>
<br />
</td>
<td>
#Html.EditorFor(model => AddressRecord.Description)
#Html.ValidationMessageFor(model => AddressRecord.Description)
</td>
</tr>
<tr>
<td>
<input type="submit" id="btnSave" name="btnSubmit" value="Save" />
</td>
<td>
<input type="submit" id="btnDelete" name="btnSubmit" value="Delete" />
</td>
</tr>
</table>
</fieldset>
}
}
<fieldset>
Or is there any better way to achieve my objective?
Since you are getting the data via ajax you should use a jquery template engine. Basically get the data the way you are and on success you do something like
<script language="javascript" type="text/javascript">
$(function () {
$.getJSON("/getprojects", "", function (data) {
$("#projectsTemplate").tmpl(data).appendTo("#projectsList");
});
});
</script>
<script id="projectsTemplate" type="text/html">
<section>
<header><h2>Projects</h2></header>
<table id="projects">
<th>Name</th>
{{tmpl(items) "#projectRowTemplate"}}
</table>
</section>
</script>
<script id="projectRowTemplate" type="x-jquery-tmpl">
<tr>
<td>${name}</td>
</tr>
</script>
<div id="projectsList"></div>
Now each template engine is different but the above gives you an idea of what you can do
If you want to return JSON object in your controller, you are going have to turn your view into a string and return it as part of the message. If you google there are some methods out there that can do this.
However, I really think that's the hard way, why not take the data you get from the JSON in the controller and put it in a MODEL and then return your VIEW with the model data passed in. I think that's the easier way.