How to show json object data into my view Layer(JSP)? - ajax

In my project i am using springMVC+Hibernet .When EndUser click his/her profile Link i want to show his/her Information .For that i am using ajax in spring MVC .Now my controller return data in the form JSON object but i don't know How to update the object in my view Page.In That Object i have more than 25 fields any one help me how to update JSON object data to my jsp lables(FirstName,LastName.....)
MY code like this
$.ajax({
type: "GET",
url: "AjaxActionController?",
dataType: "json",
success: function(data){
alert(data);
var firstName = data.getFristName();
}
}
NOW i want to Update this data into my view layer

One "simple" way to do it is to set an id on the html element you want the data in and use jQuery to set it. This will get less and less "simple" as your application grows.
html:
<div id="firstName"/>
javascript:
success:function(data){
var firstName = data.getFirstName();
$('#firstName').text(firstName);
}
If you want something more manageable for a large app, the concept is called "data binding". Try a javascript databinding framework, such as Knockout, Ember/Backbone, Angular, Epoxy/Backbone. jQuery can do it too, with some work.

Related

How to insert data using ajax with id and without using forms in laravel

I try to insert data using id in my url like this.
absent
present
My route is:
Route::get('/present/{id}', 'UserController#present')->name('present');
Route::get('/absent/{id}', 'UserController#absent')->name('absent');
Route is working. but the page is loading, I try to insert data without loading. I know how to insert data using ajax HTML form way. but how to insert using id use ajax?
If you want to insert data without reloading you have to bind JavaScript functions to the HTML links you specified. This example is different but you can use the same approach to achieve your need.
I propose, that you change your anchor tags to buttons and add a class to them and save their routing endpoints in data attributes:
<button class="action_buttons" data-route="{{route('absent', $User->id)}}">absent</button>
<button class="action_buttons" data-route="{{route('present', $User->id)}}">present</a>
And, then use JQuery event handling to detect when they are clicked and then simply use Ajax to get the related route from the button's data attribute and send a GET request to that route:
$('.action_buttons').on('click', function(){
// Get the route data from the tag.
let route = $(this).data('route');
$.ajax({
url: route,
type: 'GET',
success: function(resp) {
console.log(resp);
}
});
});

success function equivalent for httppost in mvc

What is the equivalent for success function when I am using [HttpPost] in MVC instead of ajax calls
in ajax, for calling controller in MVC I use something like
$.ajax({
url: '#Url.Action("SomeConroller", "ActionName")',
dataType: 'html', //be sure to use html dataType
contentType: 'application/json; charset=utf-8',
success:someFunctionName
});
I stopped using ajax calls and started using ajax and started using [HttpPost] so that all input type="submit" will come to that and i will handle the events to be done.
Now there is a scenario where I am selecting and moving an item to a different list, and after its done i am doing a this.RedirectToAction("ActionName", "ControllerName");
The problem is, once it is done how can i alert that it is moved? if it is ajax i will handle it in success function. Where can i handle that here?
Since you are redirecting to another action, the page will refresh. If you want to display an alert on new page, the action view can display it with the data you pass to the view.
So something like this should give action data that it pass to the view:
return RedirectToAction("TargetAction", "Controller", new {id = userId});
The "TargetAction" will prepare a view model object and return a view with the view model:
return View(viewModel);
View will have logic to display a alert with custom text. E.g. if you want to display javascript alert on load, just define
$(document).ready(function () {
alert("Item moved: " + '#Model.Id');
});

Update Symfony's form collection prototype through ajax

I've built a form with Symfony, based on a Doctrine entity. The form contains form collections. Let's say the outer form is used to create a task. Many sub-tasks can be added to this task (the form collections part).
The task-form contains a choice field "category". De sub-task forms contain choice field "subcategory". The values of the subcategory field depend on the value chosen for the category field. To achieve this, I want to update the form prototype through AJAX when a main category has been chosen.
The JS-part of this is probably not that hard, so I'm sure I'd manage that. But I've got no idea what to do on the server/Symfony side to achieve this. Any hints in the right direction would be appreciated.
You need to create a route that link to a new function(action) in the controller lets name it "ajaxGetSubCategoriesAction()"
implement it to get all the sub categories, then return them like this :
//get the category id from ajax request
$categoryID = $request->request->get('category_id');
//get all subcategories and return your result like this
return new Response(json_encode($result));
then in the twig that renders the category put a data field inside the form tag or div tag like
this data-path you get it inside the JS file to know the path of the function you created to get the subcategories.
$posturl = $formelement.data('path');
var categoryid = //get it here with from your input field.
$.ajax({
type: "POST",
url: $posturl,
async: false,
dataType: "json",
data: {
category_id: categoryid
}
}).done(function (response) {
inside response you will have all the subcategories returned from your ajaxGetSubCategories function
}

What else can I pass to the `form` property of Ext.Ajax.request?

Normally one posts an ExtJS form to the backend using form.submit({...}). I want to make my form submission synchronous now, so I'm switching to using Ext.Ajax.request({async: false, ...}). The form property of Ext.Ajax.request() usually looks like so:
Ext.Ajax.request({
url: 'formsubmit',
form: 'formid',
method:'POST',
success: function(response, opts) {
alert("successfull");
},
failure:function(res,opt) {
alert("request failed");
}
});
I'm dealing with a bunch of anonymous forms right now. Is there any way around this?
Given a var form = {xtype: 'form', items: [...]}
I've tried replacing 'formid' with form.getEl(), form.getForm(), and form.getForm().getFieldValues() which all don't work.
There's no other way around this other than assigning a generated id to each of my anonymous forms, is there.
Thanks for any input
It looks like you could just do this as an alternative to the form attribute:
var form = this.down('form');
Ext.Ajax.request({
url: 'test.xyz',
params: form.getValues()
// etc...
});
getValues gives you the name/value pairs you need for your submission.
It looks like the ExtJS forms do not actually use form elements in the markup. When the submit function is called on an ExtJS form, an HTML form element is crafted as part of the process, and that's the form that is used for the submission.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.action.Submit-method-buildForm
Ideally, you could modify the options that are used in the Ajax request called within the doSubmit function. Since you can't, you might want to consider overriding Ext.form.action.Submit such that you can, then calling the form.submit() function you mentioned in your question.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.action.Submit-method-doSubmit

Ajax username and date Instagram API

Currently, I'm trying to create a page using instagram's api, showing recent pictures with a specific tag, as well as the user who posted it and the date posted. I'm also trying to have the infinite loading functionality, with ajax loading in more instagram posts as the page reaches the bottom.
Heres a link to the live site http://www.laithazzam.com/work/nukes/indexnew.php
Clicking the red yes will skip the video, and go straight to the instagram feed.
I'm currently using Christian Metz's solution found here, https://gist.github.com/cosenary/2961185
I am also having an issue with posting the date, in the first initial load, as well in the ajax loads. I was previously able to use this following code, before trying to implement Christian's php/ajax solution.
var date = new Date(parseInt(data.data[i].created_time) * 1000);
<p class='date'>"+(date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear()+"</p>
I guess what I don't understand, is how the ajax loading function, is actually functioning. How would I also pull the name, and date through the ajax loading success function as well?
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$("#instafeed").append('<img src="' + src + '">');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
The data parameter of the success handler function is populated from whatever JSON ajax.php returns and the structure will match accordingly. It looks like the images attribute of that object only has an array of URLs for the images and no other data.
You'll need to update this section of the PHP script to return more than just the array of URLs for the images and also include the additional data retrieved from the Instagram API.
Try updating the last part to this:
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $media->data
));
Then you'll have full access to all the media data, not just the URL.

Resources