I keep getting a 422(Unprocessable Entity) error, how do I fix this?
The below is my code on ajax call, can someone help me on to fix this problem?
$(document).on('click', '.edit-post', function() {
$('.edit-modal').css('display','block');
$('.posts-table').css('display','none');
var id = $(this).attr('data-id');
var title = $(this).attr('data-title');
var slug = $(this).attr('data-slug');
var category = $(this).attr('data-category');
var featured_image = $(this).attr('data-image');
var body = $(this).attr('data-body');
$('#edit-post-form #edit-title').val(title);
$('#edit-post-form #edit-slug').val(slug);
$('#edit-post-form #edit-category').val(category);
//$('#edit-post-form #edit-image').val(featured_image);
$('#edit-post-form #edit-body').val(body);
$('#edit-id').val($(this).data('id'));
});
//Update New Post
$("#update-post").click(function(e) {
e.preventDefault();
id = $('#edit-id').val();
var title = $('#edit-post-form #edit-title').val();
var slug = $('#edit-post-form #edit-slug').val();
var category_id = $('#edit-post-form #edit-category').val();
var featured_image = $('#edit-post-form #edit-image').val();
var body = $('#edit-post-form #edit-body').val();
var form = new FormData();
form.append('title', title);
form.append('slug', slug);
form.append('category_id', category_id);
form.append('featured_image', featured_image);
form.append('body', body);
$.ajax({
type:'PUT',
url: "/updatepost/" + id,
headers: {
'X-CSRF-TOKEN' : $('input[name="_token"]').val()
},
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form,
success: function(data) {
toastr.success('Successfully Updated Post!', 'Success Alert', {timeOut: 5000});
$('#'+ id).html("<tr id='" + data.id + "' class='item'><th>" + data.id + "</th><td>" + data.title + "</td><td>" + data.body + "</td><td>" + data.created_at + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-edit'></span> Edit</button></td></tr>");
$('.edit-modal').css('display','none');
$('.posts-table').css('display','block');
}
});
});
The data of the post will show in the edit form, but when I try to submit it after editing some fields, 422 Unprocessable entity keeps showing.
Related
I'm creating a list of clients by ajax(jquery) including 'add client', 'edit client', 'remove client'.
With ajax, I wrote the code to append a new client with $("#list").append(...) to my list as following:
$.ajax({
type: "POST",
url: "traitement.php",
data: {nom, prenom, email},
dataType: "json",
success: function () {
$("#reponse")
.hide()
.html("<span class='sucess'> Client ajouté avec succès. </span>")
.fadeIn(1000);
$("input").val('');
$("#list").append("<tr id='New'><td>" + id + "</td><td>" + nom + "</td><td>" + prenom + "</td><td>" + email + "</td>"+"<td id = 'editNew'><button><i class='fa fa-edit'></i></button></td>"+"<td id = 'deleteNew'><button><i class='fa fa-trash-o'></i></button></td>"+"</tr>");
},
error: function() {
$("#reponse")
.html("<span class='error'> Une erreur s'est produite. </span>");
}
});
Now, i would like to select #editNew or #deleteNew to modify my list of clients without refresh the page.
The problem is that after append "#new" to my HTML by ajax. This element ** is displayed but not yet in the Page Source**. So that, i can not choose it.
Could you please to give me some ideas about how can I append an element and choose this element without refresh the page with ajax, please!
Thanks you so much.
Let try with this code, i hope can help you.
$.ajax({
type : "POST",
url : "traitement.php",
data : {nom, prenom, email},
beforeSend: function() {},
success: function(response) {
$("input").val('');
$("#list").html('');
if (response.notification) {
var list_tr = '';
response.data.forEach(d => {
list_tr += "<tr id='New'><td>" + d.id + "</td><td>" + d.nom + "</td><td>" + d.prenom + "</td><td>" + d.email + "</td>"+"<td id = 'editNew'><button><i class='fa fa-edit'></i></button></td>"+"<td id = 'deleteNew'><button><i class='fa fa-trash-o'></i></button></td>"+"</tr>";
});
} else {
$("#list").html("<tr><td colspan='5'><p></p></td></tr>");
}
$("#list").html(list_tr);
},
complete: function(response) {
if (response.notification) {
$("#reponse")
.html("<span class='sucess'> Client ajouté avec succès. </span>")
.fadeIn(1000);
} else {
$("#reponse")
.html("<span class='danger'> Client ajouté avec fail. </span>")
.fadeIn(1000);
}
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log( 'The following error occured: ' + textStatus, errorThrown );
}
});
I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")
$("#btntest").click(function () {
alert('Called btn test');
var FromDate = $("#FromDate").val();
var ToDate = $("#ToDate").val();
var UserId = $("#ddlUserName")[0].value;
debugger;
$.ajax({
url: '<%:Url.Action("Grid1","GridView") %>',
data: '{"uid":"' + UserId + '","fdate": "' + FromDate + '","tdate":"' + ToDate + '"}',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('Success');
alert(data);
window.open("../GridView/Grid1");
}
});
});
on button click GridView action have to call with its respective view(Grid1)
public ActionResult Grid1(string uid, string fdate, string tdate)
{
List<modeldata> list = new List<modeldata>();
DataTable ds1 = new DataTable();
SqlCommand cmd = new SqlCommand("spGettLeadReport", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserID", uid);
cmd.Parameters.Add("#FromDate", fdate);
cmd.Parameters.Add("#ToDate", tdate);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds1);
foreach (DataRow dr in ds1.Rows)
{
list.Add(new modeldata
{
LeadName = dr["LeadName"].ToString(),
CompanyName = dr["CompanyName"].ToString(),
CreatedOn = Convert.ToDateTime(dr["CreatedOn"]),
CreatedBy = dr["CreatedBy"].ToString(),
// ZoneName = dr["ZONE_NAME"].ToString()
});
}
return View(list);
}
View Is not affecting.on new window it throws an error..
how can i change to the corresponding action view?
please help..
Change your ajax code as below.
$.ajax({
url: '<%:Url.Action("Click Here","Grid1","Controller Name") %>',
data: '{"uid":"' + UserId + '","fdate": "' + FromDate + '","tdate":"' + ToDate + '"}',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('Success');
alert(data);
window.open("../GridView/Grid1");
}
});
I am new to JqGrid. I have a problem with reload JqGrid. Not getting any errors also.
jQuery("#gridData").jqGrid("setGridParam",
{ type: "POST",
url: "TablesCoolView.aspx/GetTableData",
data: "{TableName :'" + "Test" + "'}",
contentType: "application/json",
dataType: "json"
}).trigger("reloadGrid", [{ current: true }]);
The Code will go here,
onPaging: function (pgButton) {
//debugger;
var pagerId = this.p.pager.substr(1); // get paper id like "pager"
var currentPage = jQuery("#gridData").jqGrid("getGridParam", 'page'); //get current page
var lastPage = jQuery("#gridData").jqGrid("getGridParam", 'lastpage'); //get last page
if (currentPage - 1 == lastPage - 1)
jQuery("#gridData").jqGrid("setGridParam", { page: lastPage }).trigger("reloadGrid"); // set the requested page to the last page value – then reload
var currentRecordCount = jQuery("#gridData").jqGrid("getGridParam", 'reccount'); //get the record count
var recordsPerPage = jQuery("#gridData").jqGrid("getGridParam", 'rowNum'); // get the records per page
var newValue = 0; // new value
if (pgButton === "user") {
newValue = $(".ui-pg-input").val();
}
else {
if (pgButton.indexOf("next") >= 0)
newValue = ++currentPage;
else if (pgButton.indexOf("prev") >= 0)
newValue = --currentPage;
else if (pgButton.indexOf("last") >= 0)
newValue = jQuery("#gridId").jqGrid("getGridParam", 'lastpage');
else if (pgButton.indexOf("first") >= 0)
newValue = 1;
}
alert(pgButton);
//alert(newValue);
jQuery("#gridData").jqGrid("setGridParam", { page: newValue }).trigger("reloadGrid"); // set the requested page to the last page value – then reload
currentRecordCount = jQuery("#gridData").jqGrid("getGridParam", 'reccount'); // read the current page records
//alert('RecordCount: ' + currentRecordCount + ' RecordsPerPage: ' + recordsPerPage);
if (currentRecordCount < recordsPerPage) {
startRange = 1;
endRange += endRange;
alert("Grid Reload test Start");
//jQuery("#gridData").jqGrid("setGridParam", { type: "POST", url: "TablesCoolView.aspx/GetTableData", page: 1, async: true, loadOnce: true, data: "{TableName :'" + "Test" + "'}", contentType: "application/json", dataType: "json" }).trigger("reloadGrid");
jQuery("#gridData").jqGrid("setGridParam", { type: "POST", url: "TablesCoolView.aspx/GetTableData", data: "{TableName :'" + "Test" + "'}", contentType: "application/json", dataType: "json" }).trigger("reloadGrid", [{ current: true }]);
alert("Grid Reload test End");
//jQuery("#gridData").jqGrid("setGridParam", { datatype: "json", data: "{TableName :'" + tableName + "', \"PageSize\" :\"" + recordsPerPage + "\", \"PageNumber\" :\"" + newValue + "\"}", url: "TablesCoolView.aspx/GetNextSetOfRecords" }).trigger("reloadGrid");
//data: "{TableName :'" + tableName + "', \"PageSize\" :\"" + recordsPerPage + "\", \"PageNumber\" :\"" + newValue + "\"}",
}
}
Dont know where am doing wrong.
Please help me out of this.
Try changing data: "{TableName :'" + "Test" + "'}", to postData: "{TableName :'" + "Test" + "'}",
I researched about this a lot, but couldn't find the magic.
Actually I want to populate a list of city pin code no. using JQuery autocomplete UI. It's a https page. It's working in Firefox but not in Google Chrome. Can anyone help me to resolve this issue. Thanks in Advance.
In the following is my code:
function zipAutoCompletet(prefix) {
jQuery("#" + prefix + "_zip").autocomplete({
source: function(request, response) {
jQuery.ajax({
url: "http://ws.geonames.org/postalCodeSearchJSON",
dataType: "jsonp",
data: {
style: "full",
maxRows: 12,
postalcode_startsWith: request.term
},
success: function(data) {
response(
jQuery.map(data.postalCodes, function(item) {
return {
label:
item.placeName +
(item.adminCode1
? ", " + item.adminCode1
: "") +
", " +
item.postalCode +
", " +
item.countryCode,
value: item.postalCode
};
})
);
jQuery(".ui-autocomplete").css("width", "188px");
}
});
},
minLength: 2,
select: function(event, ui) {
var myString = new String(ui.item.label);
var address = myString.split(",");
jQuery("#" + prefix + "_city").val(address[0]);
jQuery("#" + prefix + "_city").addClass("activated");
jQuery("#" + prefix + "_city").trigger("change");
jQuery("#" + prefix + "_city")
.parents(".row")
.removeClass("error-row");
jQuery("#" + prefix + "_city")
.parents(".row")
.addClass("ok-row");
var countryCode = address[3] ? address[3] : address[2];
countryCode = jQuery.trim(countryCode);
var countryName = jQuery(
"#" +
prefix +
'_country option[value="' +
jQuery.trim(countryCode) +
'"]'
).text();
jQuery("#countryContainer .jqTransformSelectWrapper span").html(
countryName
);
jQuery("#countryContainer .jqTransformSelectWrapper").addClass(
"selected-jqtranform"
);
jQuery("#" + prefix + "_country")
.parents(".row")
.addClass("ok-row");
jQuery("#" + prefix + "_country")
.parents(".row")
.removeClass("error-row");
jQuery("#" + prefix + "_country").val(jQuery.trim(countryCode));
var stateCode = address[2] ? address[1] : "";
stateCode = jQuery.trim(stateCode);
if (countryCode == "US") {
var base = base_url;
base = base.replace("https", "http");
jQuery.ajax({
url: base + "/getStateName",
dataType: "jsonp",
data: { stateCode: stateCode },
success: function(data) {
stateName = data;
jQuery("#jc_state").val(stateName);
jQuery("#jc_state").addClass("activated");
jQuery("#jc_state")
.parents(".row")
.removeClass("error-row");
jQuery("#jc_state")
.parents(".row")
.addClass("ok-row");
jQuery("#jc_state").trigger("change");
formValidate();
}
});
} else {
stateName = stateCode;
jQuery("#jc_state").val(stateName);
jQuery("#jc_state").addClass("activated");
jQuery("#jc_state")
.parents(".row")
.removeClass("error-row");
jQuery("#jc_state")
.parents(".row")
.addClass("ok-row");
jQuery("#jc_state").trigger("change");
formValidate();
}
jQuery("#" + prefix + "_zip")
.parents(".row")
.addClass("ok-row");
jQuery("#" + prefix + "_zip")
.parents(".row")
.removeClass("error-row");
},
open: function() {
jQuery(this)
.removeClass("ui-corner-all")
.addClass("ui-corner-top");
},
close: function() {
jQuery(this)
.removeClass("ui-corner-top")
.addClass("ui-corner-all");
},
change: function(event, ui) {
if (ui.item === null) {
jQuery("#" + prefix + "_zip")
.parents(".row")
.removeClass("ok-row");
jQuery("#" + prefix + "_zip")
.parents(".row")
.addClass("error-row");
$("#" + prefix + "_zip").val("");
}
}
});
}
If you are on https page, browser will block requests to non-secure resources (http).
Regularly you should see some notification about that. Looks like other browsers does not block non secure AJAX requests on secured pages by default, but google chrome does.
In your code, you have hardcoded URL:
url: "http://ws.geonames.org/postalCodeSearchJSON",
If that is cross domain request and it supports HTTPS, you can change it like this:
url: "//ws.geonames.org/postalCodeSearchJSON",
As you can see, protocol is not specified there. Browser will take page default protocol (http or https) and use it to request data.