zf2 and ajax I can't get the parametrs - ajax

I can not get the data passing from the controller ajax me there any solution?
button click action
$(".bajaAlumno").click(function () {
var urlform = "<?php echo $this->url(null, array('controller'=>'Academius','action' =>'bajaAlumnos' ) ); ?>";
var dato= $(this).attr('id');
var myData = {textData:dato};
$.ajax({
type:"POST",
url:"/Academius/bajaAlumnos",
data:{data:myData},
success: function(data){
//The callback function, that is going to be executed
//after the server response. data is the data returned
//from the server.
// Show the returned text
//$("#answer").text(data.text);
//$("#answer").text(data.text);
alert('enviado');
}
});
});
and controller
public function bajaAlumnosAction()
{
die(var_dump($this->params()->fromPost()));
}
one answer?

Related

Django: correct way to pass AJAX

I've a view that recives parameters from the frontend via AJAX.
I've passing AJAX parameters in a maner, but this time my way didn't work.
I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work:
Why?
My friend's AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/?d_name=" + val_d + "&p_name=" + val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
</script>
My AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
d_name: val_d,
p_name: val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
});
</script>
View
def get_district(request):
d_name = request.GET.get("d_name")
p_name = request.GET.get("p_name")
data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True)
# data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True)
return render(request, "accounts/district_dropdown.html", {
"districts": set(list(data))
})
You need to pass the the d_name and p_name properties in a separate object specified by data. Currently you're passing them as top level properties of the ajax settings object, which won't have any effect.
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
data: { // Pass parameters in separate object
d_name: val_d,
p_name: val_p
},
}).done(function (result) {
$("#id_shipping_district").html(result);
});
The data object is converted into a query string and appended to the URL.
In your friend's case, they are building up the query string manually when they create the URL - hence their version works.

ajax query without passing page data laravel 5.6

I have a button and when it's clicked, I basically want to load the Auth::user()->name and a date into the database. I can't figure out how to do an ajax call without passing in some sort of data. This is my ajax query.
var url2 = "/application-background-sent/{{$application->id}}";
$(document).ready(function(){
$('#bgSubmit').click(function(e){
$.ajax({
url: url2,
success: function(data) {
alert(data);
},
type: 'GET'
});
});
});
My route:
Route::get('/application-background-sent/{id}', 'ApplicationsController#backgroundSent');
My controller:
public function backgroundSent($id)
{
$application = Application::findOrFail($id);
$application->bg_check_submitted_by = Auth::user()->name;
$application->save();
return response()->json(['success'=>'Data is successfully added']);
}

Laravel 5.2 post route returns plain html text

whenever I send a post request to 'tasks/add' i want the user to return to a new page, but all I get is plain html text in a popup.
Route.php code
Route::post('tasks/add', function() {
return view('secrets');
});
this is my ajax request :
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=customer]").val();
var details = $("input[name=details]").val();
var dataString = 'customer='+customer+'&details='+details;
$.ajax({
url: "tasks/add",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data : dataString,
success:function(data){
console.log(dataString);
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
});
Anybody has had this issue before?
You are using Ajax to call your Route method. So when Route::post(...) returns the view 'secrets', it returns it to the Ajax method and becomes held by the data variable. Saying return in your Routes file doesn't magically mean redirect to a certain view, it is just like any other function that returns a value.
You currently have alert(data) which just says make an alert with whatever is held by data which in this case is the html text of your view.
Instead, take out the alert() and put
window.location.replace('<path/to/secrets>')
to redirect to the page you want upon success.
Assuming your Routes file has something like :
Route::get('/secrets', function() {
return view('secrets');
});
You could say
window.location.replace('/secrets')

Call ajax inside a custom method and return ajax result to called method

in my JSP I have link and button, for both I want to call Ajax action and use with result.
I am creating events for both link and button and calls Ajax. I need to return the result to the calling method.
//event for button
$(document).on('click', ".addComponent", function(){
var htmlContent=$(this).html();
$('.addComponent').html('Loading...').fadeIn();
var urlAction=$(this).attr("id");
var dataFields=$(this).data('val');
var data=callActionUsingAjax(urlAction, dataFields); //data not returning from ajax
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
return false;
});
//event for link
$(document).on('click', "#dimComponentList >TBODY > TR > TD > a", function(){
$("body").css("cursor", "progress");
var urlAction=$(this).attr("href");
var dataFields="";
var data=callActionUsingAjax(urlAction, dataFields);
var ajaxActionResult=ajaxResult(data); //ajax not returning data
$("body").css("cursor", "auto");
$('#applicationList').html(ajaxActionResult);
return false;
});
Here is my method to call Ajax
function callActionUsingAjax(urlAction,datafields)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
return data;
}
});
}
I tried this link but I don't know how to use call back on my custom method like that. There are some other events also I need to call this Ajax. That's why I used Ajax inside a custom method.
Can anyone give me a solution?
The Ajax call is asynchronous and takes its time to complete, while the execution goes on and that's why you don't have any data in the "return".
You need to pass a callback function to your callActionUsingAjax and call it in your success handler (or complete or error that depends on the logic.
Like this:
$(document).on('click', ".addComponent", function(){
//... other stuff
callActionUsingAjax(urlAction, dataFields, function (data) { //this is tha callback (third argument)
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
// all of the above happens when ajax completes, not immediately.
});
return false;
});
function callActionUsingAjax(urlAction, datafields, callback)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
callback(data);
}
});
}

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Resources