I'm trying to get a value from ajax request into my controller. My js function shows desired value in alert but when I try to pass this value as data into the controller, the controller received null.
I'm not sure if this is an error with my app logic or a different problem. I would appreciate any feedback.
The form
<form>
<input type="color" id="bgcolor" name="bgcolor">
<button onclick="hex2rgb()">CLick</button>
</form>
The Javascript
<script>
function hex2rgb(hex) {
var hex = document.getElementById("bgcolor").value;
r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (r) {
return alert(r.slice(1, 4).map(function (x) {
return parseInt(x, 16);
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url:"{{ route('niceActionController.multiStepStore') }}",
method:"POST",
data:{hex:hex,_token:_token},
success: function(response){ // What to do if we succeed
if(data == "success")
alert(response);
},
error: function(response){
alert('Error'+response);
}
})
}));
}
return null;
}
</script>
The Controller
public function multiStepStore(Request $request)
{
$input = $request->get('hex');
dd($input);
}
I think that you probles is in your token, the correct form to get a token for send in ajax is:
Blade
<form>
<input type="color" id="bgcolor" name="bgcolor">
<button onclick="hex2rgb()">CLick</button>
</form>
Javascript
<script>
function hex2rgb() { //remove the data you are receiving
var hex = document.getElementById("bgcolor").value;
r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (r) {
return alert(r.slice(1, 4).map(function (x) {
return parseInt(x, 16);
$.ajax({
url:"{{ route('niceActionController.multiStepStore') }}",
method:"POST",
data:{
_token: "{{ csrf_token() }}",
hex:hex,
},
success: function(response){ // What to do if we succeed
console.log(response);
},
error: function(response){
console.log('Error'+response);
}
})
}));
}
return null;
}
</script>
Controller
public function multiStepStore(Request $request)
{
dd($request->all());
}
Route
Route::post('/hex', 'Hexcontroller#multiStepStore')->name('niceActionController.multiStepStore');
to see the console.log you need to open your browser's inspector
Related
I need to wrote a code on an older version of the .net Framework, namely 4.5.2.
I ran into a problem, the ajax code sends an empty request to the controller.
Here is the form and I need to check user Full Name on unique:
<div class="register-card">
<h1>Register the new user</h1>
#using (Html.BeginForm("CreateUserAsync", "Home", FormMethod.Post))
{
<div>
#Html.Label("FullName", "Enter your full name")
<input type="text" id="FullName" name="FullName" pattern="^(\w\w+)\s(\w+)\s(\w+)$" onblur="CheckAvailability()" required />
<span id="message" onclick="ClearMessage()"></span>
</div>
<p><input type="submit" value="Send" id="submit" /></p>
}
</div>
Here is my js function to checking Full Name:
function CheckAvailability() {
var data = $("#FullName").val();
var param = data;
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "String",
data: JSON.stringify(param),
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
};
function ClearMessage() {
$("#message").html("");
};
Js function pass the FullName to next controller:
[HttpPost]
public async Task<JsonResult> CheckFullNameAsync([FromBody]string fullName)
{
var isValid = await _service.IsUserExistAsync(fullName);
return Json(isValid);
}
But the controller receives null.
I think the problem is in the Js function, but I can figure out what I'm doing wrong.
Dont need to create two variable
var data = $("#FullName").val();
var param = data;
Just create
var param = $("#FullName").val();
try this
Check this link. it explains your problem well
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: 'json',
data:{"":param},
//data: { fullName: param },
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
or this one also
$.post('/Home/CheckFullNameAsync', { fullname: param},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
What is dataType: "String"? That's not a listed option. And more specifically, all you're sending is a value but with no key. So the server isn't able to deserialize the data and determine where the fullName value comes from.
Change the type to 'json' and send the object with the named key for the value:
dataType: "json",
data: { fullName: param },
I am trying to submit a form using ajax in Laravel 5.5
The problem is the page is refreshing and not submitting data in the database. I need to store data in the database without refreshing the page.
Here is my code:
Controller
public function new_timing_table(Request $request)
{
if (Request::ajax()) {
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "yes";
} else {
$msg = "yes";
}
return ['msg'=> $msg];
}
View
<form id="timeForm" class="form-horizontal form-material" >
<div class="form-group">
{{ csrf_field() }}
<div class="col-md-12 m-b-20">
<label> Table Name</label>
<input type="text" id="timing_tables_name" class="form-control"
name="timing_tables_name" />
</div>
<div class="modal-footer">
<input type="button" value="Replace Message" id='btnSelector'>
</div>
</div>
</form>
Ajax script
const xCsrfToken = "{{ csrf_token() }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': xCsrfToken
}
});
jQuery(document).ready(function() {
jQuery('#btnSelector').click(function(e) {
event.preventDefault();
getMessage();
});
});
var getMessage = function() {
var timing_tables_name = $("input[name=timing_tables_name]").val();
$.ajax({
type: 'post',
url: '/new_timing_table',
dataType: 'json', //Make sure your returning data type dffine as json
data: timing_tables_name,
//data:'_token = <php echo csrf_token() ?>',
success: function(data) {
console.log(data); //Please share cosnole data
if (data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg);
}
}
});
}
Router
Route::post('/new_timing_table','Timing_TableControoler#new_timing_table');
You got a typo or a mistake in your script.
jQuery('#btnSelector').click(function(e){
// An error here - it should be e.preventDefault();
event.preventDefault();
getMessage();
});
My code is working now after adding beforeSend: function (request) in Ajax script
var getMessage = function(){
var timing_tables_name = $("#timing_tables_name").val();
console.log(timing_tables_name);
$.ajax({
type:'GET',
url:'/new_timing_table', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:
{
timing_tables_name
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-
token']").attr('content'));
},
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
and editing the controller to be simple as this one
public function new_timing_table(Request $request){
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "This is a simple message.";
return ['msg'=> $msg];
}
Thank you all for your help
I'm trying to remove records from my DB......
this is how my form looks like.........
#using (Html.BeginForm("RemoveDoctor", "Doctor", FormMethod.Post, new { #id = "form" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Id)
#Html.HiddenFor(model => model.Name)
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" id="submit" /> |
</div>
}
I'm trying to get these records from the view and pass to my controller Action method............................. i'm trying to serialize this form and send it to that action method as following...................
var jsonObj = $('#form').serialize();
it serialize the form put my Ajax POST function wont run with that result......
it just gives me an error!!!!................. I just need to pass that serialize value to my Action method............... This is how my Script looks like.....................
$('#submit').click(function () {
var jsonObj = $('#form').serialize();
alert(jsonObj);
$.ajax({
type: "POST",
url: '../Doctor/RemoveDoctor',
data: JSON.stringify({ "doctor": jsonObj }),
success: function (data) {
alert(data.Message);
},
error: function () {
alert("Error!!!");
}
});
return false;
});
This is how my action method looks like....................
public ActionResult RemoveDoctor(DoctorModel doctor)
{
bool confirmationResult = doctorManager.RemoveDoctor(doctor.Id);
string displayMessage = string.Empty;
if (confirmationResult == true)
displayMessage = "You have successfully removed your record!!";
else
displayMessage = "Error!! Some Thing Went Wrong, Please Try Again!!";
return Json(new { Message = displayMessage });
}
I'm trying to send this 'displayMessage' to my jQuery code........ please some give me an idea how to solve this....... thanks!!!!!
Try this
$.ajax({
type: "POST",
url: '../Doctor/RemoveDoctor',
data: $('#form').serialize(),
success: function (data) {
alert(data.Message);
},
error: function () {
alert("Error!!!");
}
});
It will serialize your form.
Use only $('#form').serialize() for serialization.
Edit
If you don't want to refresh page then you should use type="button" instead type="submit"
And
You should do this also
[HttpPost]
public ActionResult RemoveDoctor(DoctorModel doctor)
{
//...................
return Json(new { Message = displayMessage } , JsonRequestBehavior.AllowGet);
}
And change ajax error function to this (For getting error )
error: function(jqXHR, textStatus, errorThrown)
{
alert("Error: "+errorThrown+" , Please try again");
}
I am trying to create a live search using jquery, ajax and laravel. I also use pjax on the same page, this might be an issue?. Quite simply it should query the database and filter through results as they type.
When using Ajax type:POST I am getting 500 errors in my console. I get zero errors using GET but instead of returning in #foreach it will a full page view (this might be because of pjax).
Where am I going wrong?
Route:
Route::post('retailers/{search}', array(
'as' => 'search-retailers', 'uses' => 'RetailersController#search'));
Controller:
public function search($keyword) {
if(isset($keyword)) {
$data = array('store_listings' => RetailersListings::search($keyword));
return $data;
} else {
return "no results";
}
}
Model:
public static function search($keyword)
{
$finder = DB::table('retailers_listings')
->Where('city', 'LIKE', "%{$keyword}%")
->orWhere('country', 'LIKE', "{$keyword}")
->orderBy('country', 'asc')
->get();
return $finder;
}
View (store.blade.php):
<div id="flash"></div> //loading
<div id="live"> // hide content
<div id="searchword"><span class="searchword"></span></div> //search word
<table class="table">
<tbody>
#foreach($store_listings as $store)
<tr>
<td></td> //echo out all fields eg: {{ $store->name }}
</tr>
#endforeach
</tbody>
</table>
</div>
Form:
<form method="get" action="">
<input type="text" class="search-retailers" id="search" name="search">
</form>
Ajax and JS:
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
var dataString = 'keyword='+ keyword;
if(keyword=='') {
} else {
$.ajax({
type: "GET",
url: "{{ URL::route('search-retailers') }}",
data: dataString,
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
Additional, Here is my controller for pjax, It is important to note I am using the view store.blade.php foreach in for the search and for this store listing.
public function stores($city)
{
$this->layout->header = $city;
$content = View::make('retailers.stores', with(new RetailersService())->RetailersData())
->with('header', $this->layout->header)
->with('store_listings', RetailersListings::stores($city));
if (Request::header('X-PJAX')) {
return $content;
} else {
$this->layout->content = $content;
}
}
Your route is Route::post('retailers/{search}', [...]) and there you go. You pass data to your ajax-call. In GET you get something like url?key=value but using POST the data are added to the request body not to the url.
Knowing this your route is no longer valid since it only looks up for retailers/{search} and not for retailers only (which is the url POST is using).
Well maybe it could help somebody.
As a first problem you are defining the route as POST and then in the ajax request the type GET so it would not work
Also when making POST request Laravel has the csrf check so in order to work, provide it. The js function will be like
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
if(keyword=='') {
} else {
$.ajax({
type: "post",
url: "{{ URL::route('search-retailers') }}",
data: {
'keyword': keywork,
'_token': '{{ csrf_token() }}';
},
dataType: 'html',
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
And you can test your PHP search method doing separate tests for it.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
GOTO = function () {
alert("yes");
$.ajax({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
My Controller ActionResult is something like this
JsonResult
[HttpPost]
public System.Web.Mvc.JsonResult Index(FormCollection collection)
{
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}
I am not able to return the JsonResult here allways I am getting popupmessage saying u have choosen to open this dialogue? is there something I am doing wrong?
thanks
Try this instead -- and make sure jQuery is loaded first. Note the changes to apply the handler via jQuery instead of inline, serializing the data, generating the URL in code dynamically rather than hard-coded, and returning false from the click handler to prevent normal form submission.
<script type="text/javascript">
$(function() {
$('input[type=button]').click( function() {
var data = $('form').serialize(); // or however you get your data
$.ajax({
cache: false,
type: "POST",
url: "<%= Html.Action( "index", "home" ) %>",
data: data,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
return false; // don't do the normal submit
});
});
</script>
<input type="button" value="submit" />
you need to put the button in a form tag and call the GOTO function in onsubmit event
It looks like your data: datastring might be the problem. Check to make sure that the name of your data parameter is the same as your method parameter.
I would try to approach it more like this ...
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$(form).submit(function() {
alert("yes");
$.post({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
});
}
</script>
<form>
// your form fields
<input type="button" value="submit" />
</form>
</asp:Content>
And then your controller should look more like this.
Notice how we changed the parameter to a string that matches your jQuery data field.
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
// you can deserialize your Json here.
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}