Ajax Post Data Form without refreshing - javascript

Firstly, I've been stuck between method and type as if I've defined method in form so I don't have to define it in ajax, and if so? ajax gives undefined in console.
Secondly, The following code gives 405 POST method not allowed.
Also, When I do succeed trying bunch of things ajax refreshes the whole page, I want to post data to server without refreshing the page.
Any help would do!!
Controller Function
public function storeDevSkill(Request $request, $user_id)
{
$this->validate($request,
[
'dev_skill_name' => 'required',
'dev_skill_exp' => 'required',
]);
try {
$data = array(
'dev_id' => $user_id,
'dev_skill_name' => $request->dev_skill_name,
'dev_skill_exp' => $request->dev_skill_exp,
);
DevSkill::create($data);
return back();
} catch (\Exception $exception) {
return back()->withError($exception->getMessage())->withInput();
}
}
Route:
Route::post('/developer/create/skill/{user_id}', 'SuperAdminControllers\DeveloperController#storeDevSkill')->name('store.developer.skill');
Form:
<form id="form_skill" method="POST" enctype="multipart/form-data" action= "{{route('store.developer.skill',$user->user_id)}}">
Button:
<button type="submit" id="addskillSubmit" value="{{$user->user_id}}" style="display: none;" class="btn btn-primary">Save</button>
Script:
<script>
$(document).ready(function () {
$('#form_skill').on('submit', function (event) {
console.log("Ajax Call")
event.preventDefault();
var action_url = '';
var user_id = $(this).attr('value');
console.log(action_url)
$.ajax({
url: action_url,
type: "post",
data: $(this).serialize(),
// dataType: 'json',
success: function (response) {
if (response.error) {
console.log('Ajax Success')
} else {
// var table = $('#addskilltable').DataTable();
// table.ajax.reload();
console.log(response.success)
}
}
});
});
});
</script>

You need to pass action attribute from the form to your ajax call like so
<script>
$(document).ready(function () {
$('#form_skill').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "post",
data: $(this).serialize(),
dataType: 'json',
success: function (response) {
if (response.error) {
console.log('Ajax Success')
} else {
console.log(response.success)
}
}
});
});
});
</script>
Give it a try and see if that changes anything.

$(document).on('submit', '#form_skill', function(e){
e.preventDefault();
var nFormId = '#'+ $(this).attr('id');
var formData = $(this).serialize();
var url = $(this).attr('action');
$.ajax({
type: "POST",
url: url,
data: formData,
success: function (response) {
console.log(response);
$(nFormId)[0].reset();
},
error: function (jqXHR, exception) {
},
beforeSend: function () {
},
complete: function () {
}
});
});
Hope this answer help you.

Related

Display error on ajax response from php function

I have some ajax call like this
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
alert(data);
},
});
}
And php function like this
function export_database(){
return $response;
}
The problem is in that response I have something like this
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3fa58ee1-48bf0cb9f60bfa25."
}
I want to alert only title, but when i try data.title , i got undefine
Do I must encode or decode something, thanks?
This is what you need. Just access the object by data.title and it will show in the alert()
You need to define dataType as json in your request.
If its does not work then use JSON.parse(data) like this:
var response = JSON.parse(data)
alert(response.title)
Try below:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: 'json'
data: data,
beforeSend: function () {},
success: function (data) {
alert(data.title);
},
error: function(error){
//Error
alert(error.title)
}
});
}
Hope this helps.
Try Below:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
var parsedData = jQuery.parseJSON(data)
alert(parsedData.title);
},
});
}
You have to use JSON.parse() for accessing data objects Like this:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
var res = JSON.parse(data)
alert(res.title);
},
});
}

Can't call the webmethod using user control

I'm creating a modal when I click I will pass the id and action to the serverside to save a logs.
Here is my sample code but can't get it to work. I'm using a usercontrol.
$("a.modal_show2").click(function () {
$(this).each(function () {
if ($(this)) {
var storecheckid = $(this).attr("id");
$.ajax({
type: "POST",
url: "TalkTalk.aspx/saveLogs",
data: {
action: 'video_tag',
clickedlinktag: storecheckid
},
dataType: "text",
success: function (response) {
console.log(response);
}
});
}
});
});
[System.Web.Services.WebMethod]
public static string saveLogs(string action, string clickedlinktag)
{
DataHelper.InsertLogs("TalkTalk", Convert.ToInt16(clickedlinktag), Convert.ToInt16(TwwId));
return clickedlinktag;
}
Thanks
data: JSON.stringify({ action: 'video_tag', clickedlinktag: storecheckid })
// response is a wrapper for your data. your data is in `d`.
success: function (response) {
console.log(response.d);
}

Getting response from action method into jquery

My jquery for onclick,
$(document).ready(function () {
$("#submitSave").on("click", function () {
var confirmPassword = $("#txtLgnPasswordConfirmReset").val();
var passwordReset = {
UserName: $("#txtLgnUsername").val(),
Password: $("#hdnOldPassword").val(),
NewPassword: $("#txtLgnPasswordReset").val()
}
$.ajax({
type: "POST",
url: "/Account/PasswordReset",
data: passwordReset
});
});
});
Below is my Controller action method which is called on 'ON CLICK' by above jquery,
[HttpPost]
public ActionResult PasswordReset(User user)
{
if (_lfAPI.PasswordReset(user))
{
return RedirectToRoute(Constants.Login);
}
return View();
}
If my, if(condition) in the above method returns true, I want to show a notify message...
My notify message,
notifyMessage.showNotifyMessage('info', 'Your password has been reset.Please login with your new password.', false)
Thanks in advance...
you can handle this in ajax success callback as
$.ajax({
type: "POST",
url: "/Account/PasswordReset",
data: passwordReset,
success: function(data) {
if (data == true) {
//show success msg
}
}
});
Use success callback in your ajax call.
$.ajax({
type: "POST",
url: "/Account/PasswordReset",
data: passwordReset ,
success: function (resp) {
if (resp == "true") {
// do your stuff here
notifyMessage.showNotifyMessage('info', 'Your password has been reset.Please login with your new password.', false)
}
},
});
});

MVC dropdownlist onchange event not calling properly the action in controller

Hi all I need to do here is that when the selection is changed of a dropdown list, with the use of AJAX I want to call an action and pass some data. Here below you can find The code that I am using. I have searched a lot and dont get why it is not entering in the action. The data and url are correct. The Controller name is HomeController and the action name is getData.
<script type="text/javascript">
function submitform() {
var a = document.getElementById("tournaments");
var datad = a.options[a.selectedIndex].value;
var url = '/Home/getData';
var completeurl = window.location.host + url;
alert(completeurl);
$.ajax({
type: "GET",
url: completeurl,
data: {tournamentid : datad},
datatype: 'JSON',
success: function (data) { alert('got here with data'); },
error: function () { alert('something bad happened'); }
});
};
</script>
Dropdownlist:
<%: #Html.DropDownList("tournaments", null, new { name = "tournaments", title = "Please Select Tournament.", onchange = "submitform();",id = "tournaments"}) %>
Action:
[HttpGet]
public ActionResult getData(int? tournamentid)
{
//perform your action here
UserBl us = new UserBl();
int num = Convert.ToInt32(tournamentid);
Tournament tour = us.GetTournamentById(num);
return Json(tour, JsonRequestBehavior.AllowGet);
}
you would do it like this:
$(function(){ // document and jquery ready
$("#tournaments").on("change", function(e){
var dropValue = $(this).val();
$.ajax({
type: "GET",
url: '/Home/getData/' + dropValue,
datatype: 'JSON',
success: function (data) { alert('got here with data'); },
error: function () { alert('something bad happened'); }
});
});
});
There are two ways
one is (use selectedItem as tournamentId)
<script type="text/javascript">
$(function () {
$("#tournaments").change(function () {
var selectedItem = $(this).val();
submitform(selectedItem);
});
});</script>
Or
put javascript: for onchange attribute
onchange = "javascript:submitform();"
EDITED :
for that I would suggest
$.ajax({
cache: false,
type: "GET",
url: url,
data: { "tournamentid ": datad},
success: function (data) {
alert("succeded")
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed ');
}});

Controller can give either json or html

The question is that the controller can give json or html piece. How to know what is it?
$(document).on("submit", "form.client-form", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (result) {
if (result is json) {
...
} else if (result is html) {
$("#result").html(result);
}
}
});
});
Another solution...found here: jquery how to check response type for ajax call
$(document).on("form.client-form", "submit", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(result, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
//html here
$("#result").html(result);
}
if (ct.indexOf('json') > -1) {
//json here
}
}
});
});
How about using converters? Take a look at Using Converters on jquery ajax api: http://api.jquery.com/jQuery.ajax/
$(document).on("form.client-form", "submit", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (result) {
try {
var response = $.parseJSON(result);
}
catch (ex){
//something else
$("#result").html(result);
}
}
});
});

Categories

Resources