I´ve searching but with no luck, i´ve tried implementing many things but nothing lead to success, so this is my scenario:
At certain point the user is in a view where after filling some fields, he has the ability to save or save and create.
The first one it is working ok, i´m posting with ajax to my controller method and returning a json response, but the user stays normally in the same view.
The second one(when he saves and create) i´m sending a variable to say exactly that, and because of that choice, the user must be directed to another view to "create" BUT i need the data that was previously saved to automatically fill some fields on the new form that is suppose to be created...so my code is:
my ajax:
$.ajax({
method: 'POST',
url: '/Cliente/insertEditCliente',
dataType: "json",
data: {"_token": "{{ csrf_token()}}", "mainId":$('#mainId').val(),values,"btnId":this.text},
success: function(response){
if(response.titulo != "Erro!"){
let dados = response['dados'];
window.location = '{{ route("formAngariacao",[null]) }}'+'/?dados='+dados;
}
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
// console.log(JSON.stringify(jqXHR));
// console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
in my controller method, i have that if statment to detect if it was just save or save and create:
if($request->post('btnId') == "Guardar"){
return response()->json(["titulo"=>"Ok!","mensagem"=>"Cliente Alterado com sucesso!","tipo"=>"success"]);
}
else{
return response()->json(["titulo"=>"Ok!","mensagem"=>"Cliente Alterado com sucesso!","tipo"=>"success","dados"=>$request]);
}
But now, in my blade view, i need to read that array "dados" which corresponds to the $request variable and has all the data i need.
How do i do that? and is this the best practice?
thanks for your time reagards.
Related
The task is to get the value of some field from k2 with an ajax request. I Googled that it seems like a simple task and is solved by referring to the desired method in the controller
$.ajax({
type: "POST",
url: 'index.php?option=com_k2&task=photo',
dataType: 'json',
success: function (json) {
console.log('success '+json);
},
error: function (jqXHR, text, error) {
console.log('error '+text+' '+error);
}
});
in folder components/com_k2/controllers/item.php
i create function - public function photo(){return 1;} http://joxi.ru/a2XxYpJFwxvRV2
when trying to get my "1" :) I get "File Not Found" as soon as I did not try to access the k2 controller, everything is without success.
Recently, I tried to build my own Laravel system, but I met a huge problem.
I'm using FullCalendar on the page 1 and I want to pass the "date data" to page 2.
However, I can get the "date data" on page 1 which is using jQuery (the variable name is 'selectedDate').
I even tried to use AJAX to pass data to controller
The following is my AJAX code on page1.blade.php
$.ajax({
url: 'step1getdate',
type: "get",
data: {date: selectedDate},
success: function(data){
console.log(data);
},
error: function (xhr, b, c) {
console.log("xhr=" + xhr + " b=" + b + " c=" + c);
}
});
web.php code is as following
Route::get('campustour/step1getdate', 'CampusTourStep1Controller#showDate');
CampusTourStep2Controller code is as following
public function showDate(Request $request){
$date = $request->input( 'date' );
return view('campusTour.step2', compact('date'));
}
but I still stuck on the same page and get the Step2 full html code on the console log window. When I checked the $date parameter on the console.log, it's passing data correctly. But what I want to do is return the whole page (step2) not just in the console.log.
Can anyone give me some guidance or keywords and let me keep moving?
Thanks a lot.
Isend the some aruguments to controller using ajax but it does not return the value.
My concept : selected #html.dropdownlist value i send to the controller , using this value thats perfrom the get the valus for bind the property to another dropdownlist using mvc3
IGot this answer : verfif given link
verfif given link
you are passing type option in ajax twice and the url is not formatted properly
function onChange(bookid) {
$.ajax({
type: "GET",
url: '#Url.Action("books","subject")',
data : { bookid: bookid},
dataType: "json",
success: function (result) {
alert('success');
//do whatever you want
},
error: function(result){
}
});
};
You are passing dataType as json. So, if you want to hit the success result for $.ajax, you need to return Json from your action result instead of returning as View.
When you return as View it gives error always.
public ActionResult books(string bookid)
{
var books= service.books(projectId);
// books are stored in list format
return Json(books);
}
Hope it helps you.
I am about to do my head in over this problem. I am using very simple jQuery ajax calls to get values from a database and populate a few select elements with the values, all returned as JSON. It works seamlessly for me on most browsers, however the client is reporting that neither them nor their clients are seeing the result.
I added some Console.log() commands along the way to make sure the code was executing, and it was. Sometimes the ajax GET to the URL in question works, other times is STILL returns 200 OK but the code simply does not execute further, and NO ajax error messages are shown in the error callback.
Here is the code I am using, can someone spot something obvious that may result in some browsers choking? If so, I'd be grateful if you could point it out:
var $j = jQuery.noConflict(true);
$j(document).ready(function(){
//console.log("jQuery has loaded");
//console.log("attempting to load country list via AJAX call now");
$j.ajax({
url: 'http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=countries&rand='+Math.random(),
success: function(data){
//console.log("Successfully got country list, going to populate the dropdown now");
if(data.length){
$j("#country").children("option:not(:first)").remove();
$j("#country").attr("disabled", false);
$j.each(data, function(resultIndex, result){
var o = new Option();
$j(o).html(result.country).val(result.country);
$j("#country").append(o);
})
//console.log("Country list should be populated now?");
}
},
error: function (xhr, ajaxOptions, thrownError){
//console.log(xhr.responseText);
console.log(thrownError);
},
dataType: 'json',
cache: false
})
$j("#country").live('change', function(){
var id = $j(this).val();
if(id == ""){
$j("#province").attr("disabled", "disabled");
$j("#town").attr("disabled", "disabled");
return false;
}
$j.ajax({
url: 'http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=provinces&c='+id+'&rand='+Math.random(),
success: function(data){
if(data.length){
$j("#province").children("option:not(:first)").remove();
$j("#province").attr("disabled", false);
$j.each(data, function(resultIndex, result){
var o = new Option();
$j(o).html(result.province).val(result.province);
$j("#province").append(o);
})
}
},
dataType: 'json',
cache: false
})
});
$j("#province").live('change', function(){
var id = $j(this).val();
if(id == ""){
$j("#town").attr("disabled", "disabled");
return false;
}
$j.ajax({
url: 'http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=towns&p='+id+'&rand='+Math.random(),
success: function(data){
if(data.length){
$j("#town").children("option:not(:first)").remove();
$j("#town").attr("disabled", false);
$j.each(data, function(resultIndex, result){
var o = new Option();
$j(o).html(result.town).val(result.town);
$j("#town").append(o);
})
}
},
dataType: 'json',
cache: false
})
});
})
I have commented out the Consol.log commands for the pure fact that the client was receiving error messages on IE as there is no console.
EDIT: I failed to mention that this a same domain request and therefore obeys the Same Origin Policy
The full site is here: http://www.topplaces.co.za/
On the right is a dynamic select group that starts with country and initiates AJAX calls until a Province is selected. The issue, a lot of people say that Country is no loading for them...
Kind regards,
Simon
Check if your server application always returns valid JSON object, otherwise it will not be accepted because you set dataType: 'json'. In this case, error function will be executed instead of success.
Remove dataType parameter and see what happens, try to parse incoming data with $.parseJSON() - it will throw an exception if you JSON is invalid.
I tried your site but no province is loading. The Json is empty. I tried accesing the php directly and it returns empty as well. Did you check your script?
URL Called
http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=provinces&c=Zambia&rand=0.12686952343210578&_=1335360594228
This are the params is see:
q:provinces
c:Zambia
rand:0.12686952343210578
_:1335360594228
Json Result:
[]
It's really random so I bet it's the php script not returning the json.
I also experienced this browser issue with json returned from an ajax call. The problem was that I had to look at different parts of the returned data in Firefox compared to IE. For Firefox, data.text was undefined so I had to use data.documentElement.firstChild to find the json:
var list = typeof data.text === 'undefined' ? jQuery.parseJSON(jQuery(data.documentElement.firstChild).text()) : jQuery.parseJSON(data.text);
I have an operation on my Page that then requires 3 long (few seconds each) operations to be performed in series. After each operation is performed though, I would like the controller to return a partial view and have the page update with a status (keeps the user informed, I find that if people know that stuff is happening they worry less). Is there a MVC 'way' of doing this, or should I just use jQuery to do it?
Thanks.
You will want to use jQuery to issue three separate calls to three separate control methods and update the three areas of the page upon return separately.
The only way to "bunch" up calls would be to combine it all into one, but you can't get return values fired back to the client upon return of more than one call (almost like streaming, there's nothing listening on the client end after you return your first result set, that connection is closed).
So I have created a slight hack, that seems to work:
On the client side I have:
function onClickHandler() {
updateUI("Beginning Batch...");
setTimeout(klugeyClick, 0);
}
function klugeyClick() {
$.ajax({ type: "GET", dataType: "json", url: "/ControllerName/Action1", success: function(msg) { updateUI(msg) }, async: false, error: function(XMLHttpRequest, textStatus, errorThrown) { updateUI("Action1 Error: " + XMLHttpRequest + " -- " + textStatus + " ---- " + errorThrown); } });
setTimeout(klugeyClick2, 0);
}
function klugeyClick2() {
$.ajax({ type: "GET", dataType: "json", url: "/ControllerName/Action2", success: function(msg) { updateUI(msg) }, async: false, error: function(XMLHttpRequest, textStatus, errorThrown) { updateUI("Action2 Error: " + XMLHttpRequest + " -- " + textStatus + " ---- " + errorThrown); } });
setTimeout(klugeyClick3, 0);
}
function klugeyClick3() {
$.ajax({ type: "GET", dataType: "json", url: "/ControllerName/Action3", success: function(msg) { updateUI(msg) }, async: false, error: function(XMLHttpRequest, textStatus, errorThrown) { updateUI("Action3 Error: " + XMLHttpRequest + " -- " + textStatus + " ---- " + errorThrown); } });
}
function updateUI(result) {
$("#UIelement").text(result);
}
On the server side I have:
Function Action1() As JsonResult
System.Threading.Thread.Sleep(3000)
Return Json("Operation One Complete...")
End Function
Function Action2() As JsonResult
System.Threading.Thread.Sleep(3000)
Return Json("Operation Two Complete...")
End Function
Function Action3() As JsonResult
System.Threading.Thread.Sleep(3000)
Return Json("Operation Three Complete...")
End Function
Now I have two problems. First, I would like to have a follow up message that displays "Batch Complete" but following the same pattern and just adding another 'klugeyClick' with a call to UpdateUI (with or without a seTimeout) causes the last operation message not to be displayed. I think the callback within the jQuery.ajax method makes this kluge work somehow but without an ajax call, I can't put any follow-up messages.
The next problem is that although all my calls are getting to my webservice and are returning json results just fine, I always get an error coming back from the jQuery callback. Any ideas why this might be?
Thanks.
So as far as I can tell, the only way to get a Follow up message to appear the way I want it do (i.e. a few seconds after my last operation) is to have a dummy webservice method that I call that returns the last message after a delay... crumby.
Now my last problem is that all of my calls to my jsonResult actions come back with a textStatus of 'error' to the client. Now according to the docs this means an http error, but how could there be an http error if the method was called on the server side correctly and a Json result was produced (verified by setting a breakpoint on the server)?
For our site we have a big action that requires some time. That action is composed by subactions, we aggregate the results and we build a nice view.
One year ago:
We were doing that in a sequence: action1, then action2, etc.
We had that typical page of: please wait.
Tricks that can help you:
We do parallel requests on the server side.
We wait for results in a results page. The javascript there needs some time to load, so while the server searches, we load the page.
We ask the server every second: have you finished? And we get partial results as the different actions complete.
I don't know if you can apply all of these things to your problem but some of then can be really nice.
We don't use MVC, we use some asmx services with jQuery and ajax.
The reason your "kludgy" solution works is because the setTimeout() method creates an event. Thus your logic is:
Update UI
Setup event for step 1:
Start "ajax" call
Wait for "ajax" to finish
Setup event for step 2
Start "ajax" call
Wait for "ajax" to finish
Setup event for step 3
Start "ajax" call
This is precisely what the callback feature of ajax() is for.
function Step1() {
$.ajax({
type: "GET",
dataType: "json",
url: "/ControllerName/Action1",
success: function(msg) {
updateUI(msg);
Step2(); // call step 2 here!
},
async: true, // don't block the UI
error: function(XMLHttpRequest, textStatus, errorThrown) {
updateUI("Action1 Error: " + XMLHttpRequest + " -- " + textStatus + " ---- " + errorThrown);
}
});
}
function Step2() {
// similar to step one
}