Manipulating data from AJAX call in Ember js - ajax

I'm new to Ember js and I'm having some difficulty seeing why this isn't working. Essentially i'm sending a GET request to a server and it is giving me an array. I would like to take that array display its contents.
app.js
App.TestRoute = Ember.Route.extend({
model: function(){
return App.Test.findAll();
}
});
App.Test = Ember.Object.extend();
App.Test.reopenClass({
findAll: function() {
var dummyArray = [];
$.ajax({
type: 'GET',
url: 'myurl',
headers: {'myheader'},
success: function(data){
data.dummyArray.forEach(function (item){
dummyArray.push(App.Test.create(item));
});
return dummyArray;
},
error: function(request, textStatus, errorThrown){
alert(errorThrown);
console.log();
}
});
}
});
When you to the test page the action should fire and an array should be returned to the model where the data can be grabbed to populate the page
and in my HTML I have this:
script type="text/x-handlebars" id="test">
<ul>
{{#each item in model}}
<li>{{item.ID}}</li>
{{/each}}
</ul>
{{outlet}}
</script>
In the console when I log the data that I returned it looks something like this:
Object {dummyArray: Array[4]}
dummyArray: Array[4]
0: Object
ID: 1111
1: Object
ID: 1112
2: Object
ID: 1113
3: Object
ID: 1114
The app runs with no errors but when I navigate to my test page the page does not populate with any data.

Your problem is that your synchronous code is returning nothing. Your model function returns App.Test.findAll(), which is never anything. You need to return a promise.
findAll: function () {
var result = [];
return new Ember.RSVP.Promise(function (resolve, reject) {
Ember.$.ajax({
type: 'GET',
url: 'myurl',
headers: { 'myheader' },
success: function (data) {
data.dummyArray.forEach(function (item) {
result.push(App.Test.create(item));
});
resolve(result);
},
error: function (request, textStatus, error) {
console.log(error);
reject(error);
}
});
});
}

Related

Make 2 AJAX calls on button Click

I am working on ASP.NET MVC project. In my home page, I have a search box with a search button.
When User types a Keyword and Click Search, I need to perform 2 independent search Operations (I am using Elasticseach, so two calls to Elasticsearch).
Make a call to SearchItems action method, which will go and get Items from Elasticsearch and returns ItemsPartialView.
Make a call to SearchCategory action method which goes and gets categories from Elasticsearch and returns CategoryPartialView.
In my home page, I want to make 2 ajax calls, to these action methods using AJAX, to display the result.
This Image explains what I want to achieve
Question: Is it possible to make 2 calls to 2 action methods on one event using AJAX?
It's possible. The only real issue is whether you want the ajax requests to be sent in a certain order (and the usual issues of efficiency of code to avoid repeats, the format of the data returned etc). One way of doing this (where the ajax second call is made after the first completes successfully) is sketched out:
<input type="text" id="search-query" value="" />
<button id="test-button">Test Ajax</button>
<div id="ajax-one-result"></div>
<div id="ajax-two-result"></div>
<script>
$(function(){
$(document).on("click", "#test-button", function(){
var qry = $("#search-query").val();
func1(qry);
function func1(queryString) {
var urlOne = "/Path/To/AjaxOne";
return $.ajax({
type: "GET",
url: urlOne,
timeout: 30000,
data: { query: queryString },
dataType: "json",
beforeSend: function () {
},
success: function (transport) {
$("#ajax-one-result").html(transport);
func2(transport);
console.log("AjaxOne success");
},
error: function (xhr, text, error) {
console.log("ERROR AjaxOne");
},
complete: function () {
}
});
}
function func2 (ajaxOneResult) {
var urlTwo = "/Path/To/AjaxTwo";
$.ajax({
type: "GET",
url: urlTwo,
timeout: 30000,
data: { query: ajaxOneResult },
dataType: "json",
beforeSend: function () {
},
success: function (transport) {
$("#ajax-two-result").html(transport);
console.log("AjaxTwo success");
},
error: function (xhr, text, error) {
console.log("ERROR AjaxTwo");
},
complete: function () {
}
});
}
});
});
</script>
with Controller Actions:
public async Task<JsonResult> AjaxOne(string query)
{
// For testing only
System.Threading.Thread.Sleep(5000);
var result = "AjaxOne Result: " + query;
return Json(result, JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> AjaxTwo(string query)
{
// For testing only
System.Threading.Thread.Sleep(2000);
var result = "AjaxTwo Result: " + query;
return Json(result, JsonRequestBehavior.AllowGet);
}

ajax code to check new records at database

I am using laravel, and I want to check if there are new records inserted into the database, I want an Ajax code the returns with the result, I don't know ajax so please help me
this is my controller
public function newrecord($target_id){
$record = Message::where('target_id', $target_id)->get();
return $record->count();
}**strong text**
and this is my ajax code
$(document).ready(function(){
var ajaxCall=function()
{
$.ajax({
url:"{{ url('/record/'.$auth->id) }}" ,
type: "GET",
datatype:"html",
data:{},
success:function(data) {
$('.msgnum').html(data)
console.log('new record);
},
error: function(data) {
console.log('error');
}
});
}
setInterval(ajaxCall,5000);
});
all I get is just a loop or " new record " in the console log
Do I need to return anything to tell that there is a new file, any help?
Try this, of course modify the code to how you want it to work but wrap the whole thing in setInterval, you don't even need the document.ready()
<script type="text/javascript">
setInterval(function() {
$.ajax({
url:"{{ url('/record/'.$auth->id) }}",
type: "GET",
datatype:"html",
data:{},
processData:false,
success: function(data){
$('.msgnum').html(data)
console.log('new record');
error: function(data) {
console.log('error');
}
},
error: function(){}
});
}, 5000);
</script>

Duplicate entires into database while using ajax to insert

I am trying to user ajax to insert into the database for my laravel project but each time i insert i see duplicates of every item with a unique id.
Inserting normally with the form itself, this behavior doesn't repeat.
My ajax code s below.
`$('#saveCat').on('click', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = '/admin/storecat';
var type = "post";
var data = {spec: $('#cat').val() };
$.ajax({
type: type,
url: url,
data: data,
dataType: 'json',
success: function (data) {
console.log(data);
$('#catform').trigger('reset');
//show success alert msg
$('#alert-suc').html(data);
$('#ac-alert').show('slow', function () {
setTimeout(function () {
$('#ac-alert').hide('slow');
}, 3000);
});
},
error: function (data) {
console.log('Error:', data);
}
});
});
My controller action here
public function storeCat(Request $request) {
$Category = new Category;
$Category->name = $request->spec;
$Category->save();
return response()->json('New service category ' . $request->spec . ' has been added.');
}
try to use:
e.stopImmediatePropagation();
stopImmediatePropagation will prevent any parent handlers and also any other handlers from executing.

Checking all JSON values for a specific attribute/parameter

I am trying to check a JSON for the "start" object, and what it value is.
For example, if my AJAX is
$(document).ready(function () {
$.ajax({
url: "Content/events/document.json",
type: "GET",
success: function (resp) {
alert(JSON.stringify(resp)); //Stringify'ed just to see JSON data in alert
},
error: function () {
alert("failed");
}
});
});
and it returns
[
{"title":"Bi-weekly Meeting1","start":"2014-07-09","color":"red"},
{"title":"Bi-weekly Meeting2","start":"2014-08-06","color":"red"},
{"title":"Bi-weekly Meeting3","start":"2014-07-23","color":"red"},
{"title":"Test Event","url":"http://google.com/","start":"2014-07-28"}
]
How can I check every "start" value? and if it is today, store that event in a different array?
I just want to keep track of today's events and I am not sure how to iterate through a JSON Object.
Note you should set dataType: "json" so that JQuery will parse the ajax response coming back as JSON automatically. Then just iterate through the array you receive, like so:
function sameDay( d1, d2 ){
return d1.getUTCFullYear() == d2.getUTCFullYear() &&
d1.getUTCMonth() == d2.getUTCMonth() &&
d1.getUTCDate() == d2.getUTCDate();
}
$(document).ready(function () {
$.ajax({
url: "Content/events/document.json",
type: "GET",
dataType: "json",
success: function (resp) {
resp.forEach(function(item) {
console.log(item.start);
if (sameDay( new Date(item.start), new Date)){
// This one has today's date!
}
});
},
error: function () {
alert("failed");
}
});
});

Rendering a simple ASP.NET MVC PartialView using JQuery Ajax Post call

I have the following code in my MVC controller:
[HttpPost]
public PartialViewResult GetPartialDiv(int id /* drop down value */)
{
PartyInvites.Models.GuestResponse guestResponse = new PartyInvites.Models.GuestResponse();
guestResponse.Name = "this was generated from this ddl id:";
return PartialView("MyPartialView", guestResponse);
}
Then this in my javascript at the top of my view:
$(document).ready(function () {
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});
function SetData(data)
{
$("#divPartialView").html( data ); // HTML DOM replace
}
});
Then finally my html:
<div id="divPartialView">
#Html.Partial("~/Views/MyPartialView.cshtml", Model)
</div>
Essentially when a my dropdown tag (which has a class called SelectedCustomer) has an onchange fired it should fire the post call. Which it does and I can debug into my controller and it even goes back successfully passes back the PartialViewResult but then the success SetData() function doesnt get called and instead I get a 500 internal server error as below on Google CHromes console:
POST http:// localhost:45108/Home/GetPartialDiv/1 500 (Internal Server
Error) jquery-1.9.1.min.js:5 b.ajaxTransport.send
jquery-1.9.1.min.js:5 b.extend.ajax jquery-1.9.1.min.js:5 (anonymous
function) 5:25 b.event.dispatch jquery-1.9.1.min.js:3
b.event.add.v.handle jquery-1.9.1.min.js:3
Any ideas what I'm doing wrong? I've googled this one to death!
this line is not true: url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
$.ajax data attribute is already included route value. So just define url in url attribute. write route value in data attribute.
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: '#Url.Action("GetPartialDiv", "Home")',
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});

Resources