I have number of values.
I need to pass these values to another page without using the window.location
function sample(cID){
var clg = ${param.clg};
$.ajax({
type : "post",
url : "sampleShow?clg="+clg+"&cID="+cID+"&level="+level,
dataType : "json",
cache : false,
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success : function(response) {
window.location= "cc"
},
error : function(xhr) {
console.log("error"+xhr.status);
},
complete : function() {
}
});
}
This is my controller ajax function:
#RequestMapping(value = "sampleShow", method = RequestMethod.POST)
public #ResponseBody
String showc(HttpServletRequest request,Model model)
{
model.addAttribute("ccID", request.getParameter("cID"));
model.addAttribute("clg", request.getParameter("clg"));
model.addAttribute("level", request.getParameter("level"));
return "{\"sucess\":\"true\"}";
}
I need to get the values in cc page.
Your ajax call should like:
$.ajax({
type : "post",
url : "sampleShow",
data : {clg: clg, cID: cID, level: level },
success : function(response) {
window.location= "cc"
},
error : function(xhr) {
console.log("error"+xhr.status);
},
complete : function() {
}
});
No need to specify dataType: "json", as you are not sending json. Data is passed using 'data'. Refere jQuery.ajax() for more details.
You can also use shorthand method jQuery.post(), to post instead of jQuery.ajax()
You may also like to read on what-is-the-difference-between-post-and-get.
Related
I am new to Laravel.
Trying to Pass ID from View to Controller but getting Error
POST http://127.0.0.1:8000/getbuffaloidformonitor 404 (Not Found)
This is my View BuffaloMonitor :
$(document).on('click', '.viewmonitormodal', function() {
var modal_data = $(this).data('info').split(',');
$('#viewbuffaloID').val(modal_data[1]);
var buffaloid = document.getElementById('viewbuffaloID').value// get buffalo id from textbox to get data for that ID
alert(buffaloid);
//alert(data);
$(function() {
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor",
data: {
'_token': $('input[name=_token]').val(),
'id': buffaloid,
},
success : function(response) {
alert(response);
}
});
});
}
This is BuffalomonitorCOntroller :
public function getbuffaloidformonitor(Request $req) {
$data = buffalodata::find($req->id);
alert(data);
$id = $req('data');
return $id;
}
This Is Route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
Your post route has {id} but it's not necessary. This is what you need Route::post('/getbuffaloidformonitor','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
pass id to the link http://127.0.0.1:8000/getbuffaloidformonitor
as you write the route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
You are just pass id by routes Params, so the URL must like this
http://127.0.0.1:8000/getbuffaloidformonitor/yourbuffaloid
You need to change URL.
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor/" + buffaloid,
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If you use this script in you blade template just use
const url = '{{ route("getbuffaloidformonitor",":id") }}'
$.ajax({
method : "POST",
url: url.replace(':id',buffaloid),
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If your routes {id} is optional just
Route::post('/getbuffaloidformonitor/{id?}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
with question on your id route you can use both by pass id by route params or you can pass id by data post.
In controller
public function getbuffaloidformonitor(Request $req, $id = null)
{
// id is get from route params
$getId = $req->get('id') // this one get from data post.
}
How I can use count variable out of ajax? In ajax function "count" shows count, but dessous nothing.
var count;
$.ajax({
cache : false,
dataType: 'json',
type : "POST",
url : "count.php",
success : function(tdata){
count = tdata;
console.log(count); //this works
}
});
console.log(count); //this doesn't work
$.ajax() is async, you need to wait for it to finish.
var count;
$.ajax({
cache : false,
dataType: 'json',
type : "POST",
url : "count.php",
success : function(tdata){
count = tdata;
console.log(count); //this works
}
})
.done(() => {
// this code runs after ajax is resolved
console.log(count);
});
Refer to http://api.jquery.com/jQuery.ajax/ for other chaining methods
Hey I don't know why $(this) not working in my ajax code.I want to append response in #feedback element.
here is my html structure image
AJAX
$("form#userComment").on("submit",function(e){
e.preventDefault();
$.ajax({
url : "request/postComment.php",
type : "POST",
data : new FormData(this),
dataType : "text",
contentType : false,
processData : false,
beforeSend : function(http){
$("#upload").val("Posting..");
$("#comment").val("");
},
success : function(response,status,http){
var text = response.split(" ");
$("#upload").val("Post");
if(text[3] === "'error'"){
$(".response").html(response);
$(".response").slideDown();
}else{
$(this).prev().append(response);
}
},
error : function(http,status,error){
$("#comment").val("Post");
$('.response').html("<span class='error'>Something went wrong</span>");
$(".response").slideDown();
}
})
})
I am passing an object to my controller like so:
var form = JSON.stringify({
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val()
});
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
contentType: "application/json; charset=utf-8",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
my controller sees this as the object it is looking for:
public ActionResult CreateSubcontracts(RoutingSubcontracts s)
My problem is that I'd like to pass along just one more string. I know I can make a view specific model but I was wondering if I could do something like this for example:
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu)
I have tried the the following with no luck:
data: JSON.stringify({ "s": form, "bu": "251" }),
but the complex object just comes through as null. Is there a way I can pass the object and a string through as well?
Try adding the string item in the JSON you already have. Dont stringify it or it will just send a big string that youll have to parse again on the server.
var form = {
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val(),
"bu": "251" // add it here
};
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
In your view jquery create a second var for bu. Assign the data in you ajax call like this;
data: { "s" : form, "bu" : "251" }
In your controller method change the signature to include a default value for bu like this;
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu = "NoValue")
With the default value set bu will act like an optional parameter
Sample rest Service is below:
#RequestMapping(value = "/image/upload", method = RequestMethod.POST)
public void uploadImage(#RequestParam("image") MultipartFile fileObj)
throws Exception
{
System.out.print("File Name:"+fileObj.getOriginalFileName());
}
and i wrote ajax code like this :
and my accept application format is Json when i call this i get 400 error
$('#user_click').click(function(){
var data = {
image:$("#file_1").val
};
$.ajax({
url : "http://localhost:8080/MyProject/image/upload",
type : "POST",
contentType : false,
crossDomain : true,
data : JSON.stringify(data),
dataType : 'json',
async : true,
success : function(result) {
alert('The Selected Items uploaded');
},
error: function(message){
alert("Error:"+JSON.stringify(message));
}
});
is this ajax code is correct or not?
No, it will not work since ajax request will not transfer file data.
The solutions are
Use a file upload plugin like jquery-form
Ex:
$('#myForm').ajaxSubmit({
url : 'http://localhost:8080/MyProject/image/upload',
type : "POST",
dataType : "json",
success : function(response) {
},
error : function(response) {
}
});
Use html5 FormData (Sadly no IE support)