I am working on ZEND Framework that is new to me and same is the case with the AJAX. I tried lots of example but non of them work.
Please tell me I am wrong in this code.
home.phtml
<select name="year" onchange="saveChanges(this);">
<option value="najam">Najam</option>
<option value="Ali">Ali</option>
<option value="Hassan">Hassan</option>
<option value="Hassam">Hassam</option>
</select>
<script type="text/javascript">
function saveChanges(object){
$.ajax({
method :'POST',
url: 'home',
data: object.value,
cache: false,
error: function(e){
alert(e);
console.log("error" + e);
},
success: function(response){
// A response to say if it's updated or not
alert("Success" + object.value);
console.log("Success");
}
});
}
</script>
HomeAction
if($this->_request->isXmlHttpRequest()){
//do this
}
else {
//do this
// It always in the else Part.
}
Although it print success message on console and also on the javascript alert message.
Help me if am wrong with this code
method :'POST'
to
type: "POST"
I always use $this->_request->isXmlHttpRequest() to detect a ajax request and always working.
Sorry i speak English not well
Update:
Controller:
final class IndexController extends Zend_Controller_Action
{
final public function indexAction(){
if($this->_request->isXmlHttpRequest()){
header('Content-type: application/json;charset=UTF-8');
exit(json_encode(($this->_request->getPost())));
}
}
}
View:
<select id="year" name="year">
<option value="najam">Najam</option>
<option value="Ali">Ali</option>
<option value="Hassan">Hassan</option>
<option value="Hassam">Hassam</option>
</select>
<script type="text/javascript">
$(function(){
$("#year").change(function(){
var _this = $(this);
$.ajax({
type :'POST',
url: "", // empty string means current URL
data: {year: _this.attr("value")},
dataType: 'json',
cache: false,
error: function(e){
console.log(e);
},
success: function(response){
console.log(response);
}
});
});
});
</script>
Here is the source code:
http://www.mediafire.com/?hvv4830macfl0wm
Hope the help!
In Zend Framework you can add a ContextSwitch to your actions.
Based on the Context the action will render in the relevant template.
e.g.
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'xml')
->initContext();
}
In your case
$contextSwitch->addActionContext('home', 'ajax')
See here http://framework.zend.com/manual/1.8/en/zend.controller.actionhelpers.html
Edit: That's for ZF1 though, if you're using ZF2 you might want to look into View Strategy
http://framework.zend.com/manual/2.0/en/modules/zend.view.quick-start.html#creating-and-registering-alternate-rendering-and-response-strategies
Related
When I try to pre-select the value with ajax everything except the shown value is working.
Does anyone know where I've made the mistake?
I call the pre_select() function for each <select>.
When I look in to the code, everything is OK, but the label on the page is showing me the ID instead of myTitle. After submitting the form, the data is also ok! I need only the right label...
function pre_select(pre_id, query_id) { //my ID of selection, the query
var mySelect = $('#form_my_id'+pre_id);
$.ajax({
type: 'GET',
dataType:'json',
url: '?search&id='+query_id
}).then(function (data) {
var option = new Option(data.myTitle, data.id, true, true);
mySelect.append(option).trigger('change');
mySelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
}
Here is the HTML output
<select name="form_select[]" class="form-control select2bs4 select2-hidden-accessible" id="form_my_id1" width="100%" required="" data-select2-id="form_stok_id1" tabindex="-1" aria-hidden="true">
<option value="1" selected="" data-select2-id="5">The Title Of Product</option>
</select>
This function has done my job :-)
function pre_select(pre_id, query_id) { //my ID of selection, the query
var mySelect = $('#form_my_id'+pre_id);
$.ajax({
type: 'GET',
dataType:'json',
url: '?search&id='+query_id
}).then(function (data) {
mySelect.select2("trigger", "select", {
data: data
});
});
}
I'm trying to populate html select with an ajax call using jquery. I can see that the dom is getting updated with data from database , however the updated options are not visible on brower.
Here is the static html:
<td>
<div>
<select data-placeholder="-Role-" multiple class="chosen-select"
style="width:170px;">
<option value="TEST_ROLE1">TEST_ROLE1</option>
<option value="TEST_ROLE2">TEST_ROLE2</option>
</select>
<span userId="grouproleError" class="alert alert-danger col-sm-4"
style="display:none"></span>
</div>
</td>
Following is the script code :
$(document).ready(function () {
$('.chosen-select').chosen({}).change(function (obj, result) {
console.debug("changed: %o", arguments);
console.log("selected: " + result.selected);
});
/**
* Get All roles
**/
console.log('Getting all roles..' + new Date().toLocaleString());
$.ajax({
url: "http://localhost:8081/admin/roles/getallroles",
context: document.body,
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
var list = $(".chosen-select");
$.each(data, function (index, item) {
list.append(new Option(item.rolesShortName, item.rolesShortName));
});
console.log('Roles fetched:' + JSON.stringify(data));
},
error: function () {
window.location.replace("http://localhost:8081");
}
});
$('form').submit(function (event) {
register(event);
});
});
$(document).ajaxStop(function () {
$(".log").text("Triggered ajaxStop handler.");
});
}
You can see that the static options are the only options getting displayed.
Options retrieved from the database are updated in the DOM however they are not getting displayed. What do you think I'm doing wrong?
As per the documentation $('.chosen-select').trigger('chosen:updated') was required after the DOM was modified.
I have 2 select input fields.
first select input field contains static data.
second select input field needs to be populated depending on first input field selected value.
Below is my code
<select id="filter_type" name="filter_type" class="selectpicker form-control" style="width:30%;">
<option value>Select Filter Type..</option>
<option value="abc">Abc</option>
<option value="def">Def</option>
<option value="ghi">Ghi</option>
<option value="jkl">Jkl</option>
</select>
<select id="search" name="search" class="selectpicker form-control" style="width:70%;" disabled="disabled">
<option value>Select Filter type first..</option>
</select>
Javascript
<script type="text/javascript">
$(document).ready(function()
{
$("#filter_type").change(function()
{
var id=$(this).val();
console.log(id);
var dataString = 'id='+ id;
console.log(dataString);
$.ajax
({
type: "GET",
url: "{{url('/users/abc')}}",
data: dataString,
cache: false,
success: function(data)
{
console.log(data); // I get error and success function does not execute
}
});
});
});
</script>
Controller
public function get_onchange_data(Request $request)
{
if($id == 'abc')
{
$searches = Abc::select('field_name')->get();
return response(view('/users/Def', compact('searches'))->render());
}
}
I am unable to get returned ajax data.
I get this error:
GET http://localhost:8000/users/abc?id=year&_=1496176229318 500 (Internal Server Error)
I think my check in if condition is wrong. I am considering $id as the value passed from dataString.
I don't know how to do this. Get the data, compare it with if condition and finally return array result of the data.
Edited code
$("#filter_type").change(function()
{
var id=$(this).val();
console.log("1:"+id);
var dataString = '{id:'+ id+'}';
console.log("2:"+dataString);
$.ajax
({
type: "GET",
url: "{{url('/users/abc')}}",
data: dataString,
cache: false,
success: function(data)
{
console.log("3:"+data);
}
});
});
public function get_search_data(Request $request)
{
return response($request->input('id'));
}
Two/Three issues here:
You haven't defined $id in the context of your method. Access it via your request object $request->input('id');
Don't send your data as a string, send it as an object data: {id: id}
Always return a response. If the statement evaluates to false, the request will not be answered.
I am making two AJAX calls in the form. The first is to change the second select based on the first select which calling a PHP page to process the data. The second is to prevent the default post and post the data in another PHP page.
Both Functions are working if I delete the other one. I also have another problem which is the redirect to a new page (using CleanURL). Where should I redirect in the posting page, or once return to the form page?
$('#brand').change(function() {
var brandID2 = $(this).val();
$.ajax({
url: "Calling the models after selecting the brand",
method: "POST",
data: {
brandID: brandID2
},
dataType: "text",
success: function(data) {
$('#model').html(data);
}
});
});
$("#testform").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "Calling the post page",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
//window.location.href = "<?php echo $_SESSION['toRedirectToAfterFilters']; ?>";
}
});
}));
<form name="testform" action="" method="POST">
<select name="brand" id="brand">
<option value=''>Select a Brand</option>
//function to load all the brands
</select>
<select name="model" id="model">
<option value="">Please Select Brand First</option>
</select>
<button type="submit" name="submit" class="">FILTER</button>
</form>
You are missing the id on testform
<form id="testform">...
I would remove the CleanURL dependency and try out each AJAX request one at a time. Then you will immediately see the point of failure. If not, throw a debugger; inside each event handler and step through.
Personally, I would redirect from the server after a successful database write, to simplify the logic and not have to store the success callback URL inside the $_SESSION array.
I am new to "AJAX" and I have been trying to send a request "ONSELECT" using "AJAX" and receive a "JSON" response in "laravel 5".
Here is my View
<select>
<option data-id="a" value="a">a</option>
<option data-id="b" value="b">b</option>
<option data-id="c" value="c">c</option>
</select>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
$('select').change(function(){
var data = $(this).children('option:selected').data('id');
$.ajax({
type :"POST",
url :"http://localhost/laravel/public/form-data",
dataType:"html",
data :{ data1:data },
success :function(response)
alert("thank u");
}),
});
</script>
Here is my Controller to receive ajax request
public function formdata(){
$data = Input::get('data1');
//somecodes
return Response::json(array(
'success' => true,
'data' => $data
));
}
Here is my Route
Route::post('form-data',array('as'=>'form-data','uses'=>'FormController#formdata'));
I also have tried to change the URL of ajax with just only form-data and {{Url::route('form-data')}}.
Laravel 5 uses csrf token validation for security reasons....try this...
In routes.php
route post('form-data', 'FormController#postform');
In master layout file
<meta name="csrf-token" content="{{ csrf_token() }}" />
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: '/form-data/',
type: 'POST',
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (data) {
console.log(data);
}
});
Add error callback to your ajax request to find if an error is thrown,
$.ajax({
type :"POST",
url :"http://localhost/laravel/public/form-data",
dataType:"json",
data :{ data1:data },
success :function(response) {
alert("thank u");
},
error: function(e) {
console.log(e.responseText);
}
});
its better to use console.log() to see detailed information even if the response is a json string. Try the code and let us know if something is logged to the browser console
Your jQuery code has syntax error in success callback, that's why its not making any post request to Laravel, please try below javascript it will work
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select>
<option data-id="a" value="a">a</option>
<option data-id="b" value="b">b</option>
<option data-id="c" value="c">c</option>
</select>
<script type="text/javascript">
$(function () {
$('select').on('change', function (e) {
var data = $(this).children('option:selected').data('id');
$.ajax({
type :"POST",
dataType:"json",
url :"http://localhost/laravel/public/form-data",
data :{ data1:data },
success :function(response) {
alert("thank u");
}
});
});
})
</script>
In Laravel , you can just return array or object and it will automatically convert it to json response
return ['success' => true, 'data' => $data];
You made error in code ,please write it properly.
$.ajax({
type :"POST",
url :"http://localhost/laravel/public/form-data",
dataType:"json",
data :{ data1:data },
success :function(response){
alert("thank u");
}
});
Update
I just saw your Returning datatype is json , so use
dataType:"json",
or
dataType:"jsonp",
The problem was type should be "GET" instead of "POST" and
route get('form-data', 'FormController#postform');
Thank U every one for your help
Better if you are sending all form data then use data: $(this).serialize() in ajax, and inside form use {{ csrf_field() }}