Friends,
How I integrate Ajax with zendframework.I need some good tutorials.
Put this in your controller
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('test', 'json')
->initContext();
}
create a test action
public function testAction()
{
$this->view->var1 = "I'm testing";
}
Then use jquery to perform the request in your view
<script type="text/javascript">
$(document).ready(function(){
$('#display').ajaxStart(function(){
$(this).html('Loading...');
});
str = $('#test').val();
$('#link').bind('click',function(event){
event.preventDefault();
$.post(
this.href,
{ var1: str, format: 'json' },
function(data){
$('#display').html(data.var1);
},
"json"
);
});
});
</script>
<input type="text" name="test" id="test" value="just testing" />
<p>
Testar
</p>
<div id="display">...</div>
You can use something like this in your controller:
public function testAction() {
// Remove all of your HTML stuff
$this->_helper->layout->disableLayout();
// PHP to create an array form database or something
// This will return the info as json. It takes care of the header and everything else!
return $this->_helper->json->sendJson( array('test') );
}
Related
I have this ajax call in my view, Form.cshtml
<form id="myForm">
<input id="btnSubmit" type="submit" value="Load data" />
<p id="result"></p>
</form>
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
debugger
$.get('/Form/',function (data) {
debugger
console.log('test');
});
})
});
</script>
}
and in my Razor Pages code behind, Form.cshtml.cs
public class FormModel : PageModel
{
public JsonResult OnPost()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}
The problem is it doesn't reach OnPost method. If I put in OnGet, it will automatically load before I click the Submit button.
I try to create another Razor page called Filter.cshtml and in Filter.cshtml.cs. And then in my Form.cshtml, I changed my url to /Filter/, it did reach OnGet in Filter.cshtml.cs
public class FilterModel : PageModel
{
public JsonResult OnGet()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}
The default behaviour of clicking a submit button in a form is that the form gets submitted. At the moment, your form has no method specified, so the submission will default to the GET method. If you want to submit the form by AJAX POST rather than the usual behaviour, you need to do two things:
Cancel the default action of the button click (which is what currently causes the OnGet handler to execute)
Change the jQuery code to use the POST method:
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function (e) { // include the event parameter
e.preventDefault(); // prevents the default submission of the form
$.post('/Form/',function (data) { // change from 'get' to 'post'
console.log('test');
});
});
});
</script>
}
the $.get() makes Ajax requests using the HTTP GET method, whereas the $.post() makes Ajax requests using the HTTP POST method.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Filter/OnGet",
success: function (result) {
}
});
I'm getting this error:
GET http://auto.test/autocomplete?query= 500 (Internal Server Error)
My Route (web.php):
Route::get('search', 'SearchController#index')->name('search');
Route::get('autocomplete', 'SearchController#autocomplete')->name('autocomplete');
My SearchController:
use App\Item;
use Input;
use Responce;
public function index()
{
return view('search');
}
public function autocomplete(Request $request)
{
$data = Item::select("name")->where("name", "LIKE", "%{$request->input('name')}%")->get();
return responce()->json($data);
}
And in my main view (search.blade.php):
<body>
<div class="container">
<h1>Search Name by Auto Complete</h1>
<input type="text" class="typeahead form-control" name="" id="">
</div>
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$("input.typeahead").typeahead({
source:function(query, process) {
return $.get(path, {query:name}, function(data) {
return process(data);
})
}
});
</script>
</body>
Included are the latest JQuery files and the bootstrap3-typeahead.js from cloudflare. Am I doing something wrong. Any help or suggestion is highly appreciated.
You are passing ajax request parameters wrongly. But in your code you expected to receive input parameter 'name' so it could be as follows
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$("input.typeahead").typeahead({
source:function(query, process) {
return $.get(path, {name:query}, function(data) {
return process(data);
})
}
});
</script>
I starting using this function today. And I still learning. So... I think you forgot the name and id of your input.
I have a problem that I was stacked on for a while. I am rather new to this stuff so please be patient. I think it is like very simple to solve but I am running circles now. My intention is to make a simple alert that informs that method was completed. As you can see below my first attempt was made with simple string and if statement. I dont want to reload the page any more but now I have a problem that method ends later than alert script starts.
So I have a controller:
[HttpPost]
public ActionResult Executor(LMCMainViewModel model)
{
var curlsExecutor = _curls;
var applicationPurgeCurl = curlsExecutor.GetApplicationCurl(model);
var temporary = model.SuccessExecutionStatus = curlsExecutor.CurlCaller(model.ApplicationList.ApplicationCurl);
var tempListOfApplications = PopulateModel(model);
model.ApplicationList.ListOfApplications = tempListOfApplications.ApplicationList.ListOfApplications;
model.SuccessExecutionStatus = temporary;
return View("ListOfApplications", model);
}
And I have my view:
#model LMC.Models.LMCMainViewModel
#{
ViewData["Title"] = "Liberation";
}
#using (Html.BeginForm("HeaderString", "LMC"))
{
}
#using (Html.BeginForm("Executor", "LMC", FormMethod.Post))
{
<div class="col-sm-2" asp-action="ListOfApplications">
#Html.DropDownListFor(x => x.ApplicationList.ChosenApplication, Model.ApplicationList.ApplicationListItem, new { #id = "DropdownID" })
</div>
<div class="col-sm-2 col-sm-push-5">
#Html.HiddenFor(x => x.ApplicationList.ApplicationListItem)
<input class="btn ctn-success" id="submit" type="submit" value="Submit" />
<button id="submitButtonAjax" type="button" class="btn btn-success">Ajax button</button>
<div class="col-sm-12">
#Html.Label(null, (Model.SuccessExecutionStatus ? "Success" : " "),
new { Style = Model.SuccessExecutionStatus ? "color: green;" : "color: red;" })
</div>
</div>
}
Than I tried to implement many variations of Ajax script but I got so twisted that I can't even post you the best one... One thing I know is that when I remove: #using (Html.BeginForm("Executor", "LMC", FormMethod.Post)) and try to place it into Ajax it simply doesn't work. My intention is to have something that would work like this:
<script type="text/javascript">
$("#submitButtonAjax").on("click", function () {
$.ajax({
type: 'POST',
url: "/LMC/Executor",
success: function () {
alert("Went well");
}
});
</script>
I tried to convert controller method return into Json but it didnt work as well. I would appreciate any advices, where I can read about anything similar(I am aware that there are probably many similar topics, but I wan't able to implement anything that was working into my code, because I find my question one step backwards in comparison to others), or maybe it is that easy and I am missing something and you can just post a solution. Anyway, many thanks for any help.
The ajax call should look like bellow
$( document ).ready(function() {
$("#submitButtonAjax").on("click", function () {
var postData = {
FirstPropertyOfTheModel: ValueForTheFirstProperty,
SecondPropertyOfTheModel: ValueForTheSecondProperty,
};
$.ajax({
type: 'POST',
url: "/LMC/Executor",
data:postData,
success: function () {
alert("Went well");
},
error: function () {
alert("Opssss not working");
}
});
});
});
data is the value for the model of ActionResult method of the controller. The FirstPropertyOfTheModel and SecondPropertyOfTheModel will be replaced by the name of property and assign the corresponding value respectably. At url you can use
'#Url.Action("Executor", "LMC")'
so the ajax will look like
$( document ).ready(function() {
$("#submitButtonAjax").on("click", function () {
var postData = {
FirstPropertyOfTheModel: ValueForTheFirstProperty,
SecondPropertyOfTheModel: ValueForTheSecondProperty,
};
$.ajax({
type: 'POST',
url: '#Url.Action("Executor", "LMC")',
data:postData,
success: function () {
alert("Went well");
},
error: function () {
alert("Opssss not working");
}
});
});
});
I have a button with the class "btn" and span with id "ajaxtest". When I click on the button I want to put text "test" in my span tag. And this to be done in ASP.NET MVC.
In the View I have the following ajax call:
<span id="ajaxtest"></span>
<input type="submit" class="btn" name="neverMind" value="Test BTN"/>
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/MyController/MyAction",
dataType: 'string',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
In MyController I have the following code:
public string MyAction()
{
return "test";
}
I know how Ajax works, and I know how MVC works. I know that maybe the error is because we are expecting something like this in the controller:
public ActionResult MyAction()
{
if (Request.IsAjaxRequest())
{
//do something here
}
//do something else here
}
But actually that is my problem. I don't want to call some partial View with this call. I just want to return some string in my span and I'm wondering if this can be done without using additional partial views.
I want to use simple function that will only return the string.
Change dataType: 'string' to dataType: 'text'
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/login/MyAction",
dataType: 'text',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
I check it my local it will work for me
Now, I am using angular-xeditable.I want to send edit data to server.
<div ng-controller="Ctrl">
{{ user.name || "empty" }}
</div>
and js code is
<script type="text/javascript">
var app = angular.module("app", ["xeditable"]);
app.controller('Ctrl', function($scope,$http) {
$scope.user = {
name: 'awesome user'
};
$http.post("<?php echo base_url(); ?>index.php/welcome/test", {"name":name})
.success(function(data, status, headers, config) {
$scope.data = data;
})
.error(function(data, status, headers, config) {
$scope.status = status;
});
});
</script>
I received name variable is empty value.
This code doesn't work.I can't find error.
You need to invoke your code that posts to the server on the onaftersave event, which is documented here: http://vitalets.github.io/angular-xeditable/#onaftersave
This event is called after the changes in the inputbox have been set on the model.
In your HTML put the function call in the onaftersave attribute like this:
<div ng-controller="Ctrl">
{{ user.name || "empty" }}
</div>
In your controller create the postName function which actually posts the data to the server. Your code would look like this:
<script type="text/javascript">
var app = angular.module("app", ["xeditable"]);
app.controller('Ctrl', function ($scope, $http) {
$scope.user = {
name: 'awesome user'
};
// Called on the onaftersave event of xeditable
$scope.postName = function () {
$http.post("<?php echo base_url(); ?>index.php/welcome/test", {"name": $scope.user.name})
.success(function (data, status, headers, config) {
$scope.data = data;
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
});
</script>