one event triggers multiple AJAX request - javascript

<script>
$(document).ready(function(){
var finishedCount = 0; //Count the amount of completed Ajax requests
var data; //Keep track of the first request's data
var data1; //Keep track of the second request's data
function finished(){
finishedCount++;
if (finishedCount >= 2){ //2 is the amount of requests
//Do what you need done using data and data1
$(document).on('mouseenter','.grid-item',function(){
var container = $(this);
container.find('.title-wrap').html('<p class="job-name">'+ data +'</p>');
container.find('.title-wrap').html('<p class="client-name">'+ data1 +'</p>');
console.log(data);
});
};
};
$(document).on('mouseenter','.grid-item',function(){
var container = $(this);
var jobId = container.children().find('.title-wrap-hidden').text();
$.ajax({
url: 'db_job_name_lookup.php',
type: 'POST',
data: {jobId: jobId},
success: function(data) {
// success
data = data;
finished();
// console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
// error
alert(errorThrown);
}
});
$.ajax({
url: 'db_client_name_lookup.php',
type: 'POST',
data: {jobId: jobId},
success: function(data1) {
// success
data1 = data1;
finished();
// console.log(data1);
},
error: function(jqXHR, textStatus, errorThrown){
// error
alert(errorThrown);
}
});
});
$(document).on('mouseleave', '.grid-item', function(){
var container = $(this);
container.find('.title-wrap').html('<p class="job-name"></p>');
container.find('.title-wrap').html('<p class="client-name"></p>');
});
});
</script>
Hi everyone, I want to use one event to make multiple AJAX request and I want to have both response result available to use at the same time. I tried using the above code, but it only gives back one response at a time and it even looks confused as to which result it should give, I tried using $.when and $.then but I pretty sure I'm not using it right. How would I accomplish this task?
PAGE 1
<?php
require_once("../includes/site_init.php");
if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
$job_id = $_POST['jobId'];
$portfolio_item_client = JobClient::find_by_sql('SELECT client_id FROM '.'job_client'." WHERE job_id = '" . $job_id . "' ");
$client_name = Client::find_by_sql('SELECT name FROM '.'client'." WHERE id = '" .$portfolio_item_client[0]->client_id."'");
echo $client_name[0]->name;
}else {
echo 'result failed';
}
?>
PAGE 2
<?php
require_once("../includes/site_init.php");
if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
$job_id = $_POST['jobId'];
$portfolio_item_name = Job::find_by_sql('SELECT name FROM '.'job'." WHERE id = '" . $job_id . "' LIMIT 1");
echo $portfolio_item_name[0]->name;
}else {
echo 'result failed';
}
?>

Try using $.when to resolve the promises
$(document).on('mouseenter', '.grid-item', function() {
var container = $(this);
var jobId = container.children().find('.title-wrap-hidden').text();
var ajax = $.ajax({
url: 'db_job_name_lookup.php',
type: 'POST',
data: {
jobId: jobId
},
success: function(data) {
// success
data = data;
},
error: function(jqXHR, textStatus, errorThrown) {
// error
alert(errorThrown);
}
});
var ajax1 = $.ajax({
url: 'db_client_name_lookup.php',
type: 'POST',
data: {
jobId: jobId
},
success: function(data1) {
// success
data1 = data1;
},
error: function(jqXHR, textStatus, errorThrown) {
// error
alert(errorThrown);
}
});
var container = $(this);
$.when(ajax, ajax1).done(function(data, data1) {
container.find('.title-wrap').html('<p class="job-name">'+ data +'</p>');
container.find('.title-wrap').html('<p class="client-name">'+ data1 +'</p>');
});
});
});
if you want to do a single ajax call you do the following: single_page.php
<?php
require_once("../includes/site_init.php");
header('Content-Type: application/json');
if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
$job_id = $_POST['jobId'];
$portfolio_item_client = JobClient::find_by_sql('SELECT client_id FROM '.'job_client'." WHERE job_id = '" . $job_id . "' ");
$client_name = Client::find_by_sql('SELECT name FROM '.'client'." WHERE id = '" .$portfolio_item_client[0]->client_id."'");
$data['client_name']=$client_name[0]->name;
$portfolio_item_name = Job::find_by_sql('SELECT name FROM '.'job'." WHERE id = '" . $job_id . "' LIMIT 1");
$data['portfolio_item_name']=$portfolio_item_name[0]->name;
echo json_encode(array('result'=>$data))
}else {
echo json_encode(array('result'=>'result failed'))
}
?>
js:
$(document).on('mouseenter', '.grid-item', function() {
var container = $(this);
$.ajax({
url: 'single_page.php',
type: 'POST',
data: {
jobId: jobId
},
success: function(data) {
container.find('.title-wrap').html('<p class="job-name">'+ data.result.portfolio_item_name +'</p>');
container.find('.title-wrap').html('<p class="client-name">'+ data.result.client_name +'</p>');
},
error: function(jqXHR, textStatus, errorThrown) {
// error
alert(errorThrown);
}
});
});

Lets make an analogy. An Ajax request is like sending somebody to the store, and when they get back, they will do what you tell them. What you are trying to do is send two people to the store separately, and force them both to return at the same time. That won't work.
What you can do is keep track of which has returned, and whenever one comes back, check if they are both back. If they are, then you can tell them what to do at once (call a function). Or, you can have one go to the store, and when they return, they can tell the other one to go to the store, and when the second one returns, then tell them what to do (call a function).
Bottom line: you can't force them to finish at the same time, but you can wait until they are both done to run container.find('....
EDIT: Assuming all you need is to execute code once both requests are done, I would do this:
var finishedCount = 0; //Count the amount of completed Ajax requests
var data; //Keep track of the first request's data
var data1; //Keep track of the second request's data
function finished(){
finishedCount++;
if (finishedCount >= 2){ //2 is the amount of requests
//Do what you need done using data and data1
}
}
$.ajax({
url: 'db_job_name_lookup.php',
type: 'POST',
data: {jobId: jobId},
success: function(data) {
data = data;
finished();
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
$.ajax({
url: 'db_client_name_lookup.php',
type: 'POST',
data: {jobId: jobId},
success: function(data1) {
data1 = data1;
finished();
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});

Related

pagination automatically sending multiple requests with laravel

hello guys recently I am developing a new website which have multiple filters so I use the session-based filter with laravel
it is working fine if I use only the Show filter one time but when I switch to another filter, it is sending multiple requests(as much time I repeat the filter)
when someone clicks the filter this code will run
<------- Laravel route where I am sending a request it returns me a HTML file and I am rendering in my div tag where I have all lists ------->
public function filter(Request $request){
$course = Course::query();
if (isset($request->show)) {
Session::put('show',$request->show);
$show = $request->show;
}
if(isset($request->type)){
$course->where('type',$request->type);
}
if (isset($request->ratting)) {
$course->where('ratting','>=',$request->ratting);
Session::put('ratting',$request->ratting);
}
if(isset($request->short_type))
{
$type = $request->short_type;
$course = $this->checkSort($course,$type);
Session::put('short',$type);
}
if (Session::has('search')) {
$search = Session::get('search');
$course->where(function($q) use ($search){
$q->where('title', 'LIKE', '%'.$search.'%')
->orWhere('slug', 'LIKE', '%'.$search.'%')
->orWhere('description', 'LIKE', '%'.$search.'%')
->orWhere('keyword', 'LIKE', '%'.$search.'%');
});
}
if(Session::has('show') && !isset($request->show)){
$show = Session::get('show');
}
if(Session::has('ratting') && !isset($request->ratting)){
$course->where('ratting','>=',Session::get('ratting'));
}
if(Session::has('short') && !isset($request->short)){
$type = Session::get('short');
$course = $this->checkSort($course,$type);
}
$course->select('id', 'title', 'slug', 'description', 'created_at', 'regular_price', 'sell_price', 'thumbnail','ratting','status');
return view('site.courses.ajax-listing',[
'active' => 'courses',
'type' => $request->type,
'courses' => $course->where('status',1)->paginate(isset($show) ? $show : 10),
]);
}
public function checkSort($courses,$type){
if($type == "alphabetically_a_z")
{
$courses->orderBy('title', 'ASC');
}
if($type == "alphabetically_z_a")
{
$courses->orderBy('title', 'DESC');
}
if($type == "date_new_to_old")
{
$courses->orderBy('created_at', 'ASC');
}
if($type == "date_old_to_new")
{
$courses->orderBy('created_at', 'DESC');
}
if($type == "popular")
{
$courses->where('is_popular', 1);
}
return $courses;
}
<------------------------------------------->
In the search input have route where i will send request
<input type="text" hidden id="search-url" value="{{route('ajax-search-course')}}">
<--------- Javascript Code ----->
$(document).ready(function(){
var url = "{{route('ajax-search-course')}}";
var Jobtype = "1";
var value;
$("input[name='RattingRadioDefault']:radio").change(function(){
value = $("[name=RattingRadioDefault]:checked").val();
ajaxFilter(url + "?ratting="+value+ "&type=" + Jobtype);
});
$("input[name='ShowingRadioDefault']:radio").change(function(){
value = $("[name=ShowingRadioDefault]:checked").val();
ajaxFilter(url + "?show=" + value + "&type=" + Jobtype);
});
$("input[name='ShortingRadioDefault']:radio").change(function(){
value = $("[name=ShortingRadioDefault]:checked").val();
console.log("this is value",value,$("[name=ShortingRadioDefault]:checked").val());
ajaxFilter(url + "?short_type=" + value + "&type=" + Jobtype);
});
});
function ajaxFilter(url, data = null) {
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log("this is return data",data);
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function(jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
console.log("this is error", errorMessage);
}
});
}
<------------- Javascript pagination page ----------->
//Ajax Paginatio
$(document).one('click', '#ajaxPagination ul li a', function (e) {
console.log("ajax pagination function is running",$(this).attr("href"),"and",$(e).attr("href"));
e.preventDefault();
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
var url = $(this).attr("href")+"&"+ "type=" + $('#data_sort_filter').attr('job-type'),
data = '';
e.preventDefault();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function (jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
}
});
});
i was trying to add a multiple filters system with the session. now i have this error pagination function running as much i am repeating filters i want to solve this please help me it is a very important to project for me

Getting data from database but not post and update

This is the error occurs in web console:
vendor.bundle.base.js:2 POST http://localhost/dashboard_new/public/addPackage 404 (Not Found)
send # vendor.bundle.base.js:2
ajax # vendor.bundle.base.js:2
addPackage # all_package_listing_view:522
onclick # all_package_listing_view:361
all_package_listing_view:546 Uncaught TypeError: Cannot read properties of undefined (reading 'errors')
at Object.error (all_package_listing_view:546)
at c (vendor.bundle.base.js:2)
at Object.fireWith [as rejectWith] (vendor.bundle.base.js:2)
at l (vendor.bundle.base.js:2)
at XMLHttpRequest.<anonymous> (vendor.bundle.base.js:2)
recently I have solved datatables error using "Yajra datatable", but
after that, I can retrieve data after updating it from PHPMyAdmin it
shows on the web for but I couldn't update or add. I have used PHP,
ajax, and js...
function addPackage()
{
console.log('here');
// e.preventDefault();
var formData = new FormData(jQuery('#addform')[0]);
$.ajax({
url:"http://localhost/dashboard_new/public/addPackage",
type:"POST",
data:formData,
contentType: false,
processData: false,
success:function(dataBack)
{
console.log(dataBack);
$('#form_submit_success').modal('show');
setTimeout(function() {$('#form_submit_success').modal('hide');}, 2000);
$("#addform").trigger("reset");
window.location.href = '<?php echo url('/');?>'+"/all_package_listing_view";
}, error: function (xhr, status, error)
{
// console.log(xhr.responseJSON.errors);
$.each(xhr.responseJSON.errors,function(key,item)
{
$('#form_submit_error').modal('show');
setTimeout(function() {$('#form_submit_error').modal('hide');}, 2000);
})
}
});
}
$(document).on("click",".edit",function()
{
var id = $(this).attr("id");
console.log(id);
$.ajax({
type:"get",
url:"http://localhost/dashboard_new/public/edit_pack/"+id,
// data:{id:id},
success:function(data)
{
console.log(data);
$("#id").val(data[0].id);
$("#aname").val(data[0].name);
$("#adetails").val(data[0].details);
$("status").val(data[0].status);
$("#aamount").val(data[0].amount);
}
})
})
function updatePackage()
{
var formData = new FormData(jQuery('#editform')[0]);
var idRow = $("id").val();
console.log(formData);
$.ajax({
url:"{{route('updatepackage')}}",
type:"POST",
data:formData,
contentType: false,
processData: false,
success:function(dataBack)
{
$("#signupForm").html("<li class='alert alert-success text-center p-1'> Edited Success </li>");
$("#"+idRow).html('')
$("#"+idRow).html(dataBack)
window.location.href = '<?php echo url('/');?>'+"/all_package_listing_view";
}, error: function (xhr, status, error)
{
// console.log(xhr.responseJSON.errors);
$.each(xhr.responseJSON.errors,function(key,item)
{
$("#errorUpdate").html("<li class='alert alert-danger text-center p-1'>"+ item +" </li>");
})
}
})
}
function deletePackage(id)
{
// var id = $(this).attr("id");
// console.log(id);
$.ajax({
type:"get",
url:"http://localhost/dashboard_new/public/deletepackage/"+id,
success:function(data)
{
console.log(data);
alert(data.success);
// $("#"+data.id).remove();
window.location = "http://localhost/dashboard_new/public/all_package_listing_view";
}
})
}
There is the screenshot of error:

Save multiple table rows with one save button in javascript

I am using the following code to save a row in a datatable using a save button
$(document).on('click','.updateOrder', function(){
var thisRow = $(this).closest('tr');
var rejectReasons = { PersistRejectReasons :[] }
var jsonReturnObj = new Object();
jsonReturnObj.OrderNumber = thisRow.find('.dt_orderNo').text();
jsonReturnObj.OrderLineNumber = thisRow.find('.dt_orderLineNo').text();
jsonReturnObj.RejectReasonCode = thisRow.find('.dt_researchOutcome').find("option:selected").prop("value");
jsonReturnObj.RejectReasonNotes = thisRow.find('.dt_researchNotes').find('input').val();
if(jsonReturnObj.RejectReasonCode != "" && jsonReturnObj.RejectReasonCode != null) {
if(jsonReturnObj.RejectReasonCode =="14. Other") {
if(jsonReturnObj.RejectReasonNotes == "" || jsonReturnObj.RejectReasonNotes == "null") {
alert(" Please add Research Notes");
jsonReturnObj.Processed = false;
$('#orderReportTable').append("call failed");
throw new Exception("Error message");
}
}
jsonReturnObj.Processed = true;
}else {
jsonReturnObj.Processed = false;
}
if($("#movedInput"+jsonReturnObj.OrderNumber+"-"+jsonReturnObj.OrderLineNumber).is(':checked')){
jsonReturnObj.IsAvailable = false;
}else{
jsonReturnObj.IsAvailable = true;
}
rejectReasons.PersistRejectReasons.push(jsonReturnObj);
var jsonReturnString = JSON.stringify(rejectReasons);
console.log("Rejecting Store Number is "+$("#storeNum").val())
var request2 = $.ajax({
headers: {
'RejectingStoreNum': $("#storeNum").val(), //thisRow.find('.dt_storeNo').text(), //thisRow.find("td").eq(16).text(),
'Content-Type': 'application/json'
},
type: "POST",
url: "persistStoreResearchOutcome", // REST endpoint. replace url1 with REST Endpoint
data : jsonReturnString,//json data. use data and contentType attributes for POST requests.
contentType: "application/json",
dataType: "text",
/*xhrFields: {
'withCredentials': true //Tell browser to provide credentials
},*/
crossDomain: true,// this is for cross domain requests*/
success: function (data, status, jqXHR){
console.log("status:"+status);
$('#orderReportTable').append("call successful");
if(jsonReturnObj.Processed){
thisRow.find('.dt_itemStatus').text("Researched");
table.draw();
}else{
thisRow.find('.dt_itemStatus').text("Active");
table.draw();
}
},
error: function (jqXHR, status, errorThrown){
//console.log("failed: status:"+status);
$('#orderReportTable').append("call failed, error"+errorThrown);
alert("There was an error while trying to save this item");
}
});
});
I want to do the same processing but for all the rows in the table with one single click.I used the each function to loop over the rows but keep getting an error
$("table tr").each(function (){
console.log(this);
var thisRow = $(this).closest('td');
var rejectReasons = { PersistRejectReasons :[] }
var jsonReturnObj = new Object();
jsonReturnObj.OrderNumber = thisRow.find('.dt_orderNo').text();
jsonReturnObj.OrderLineNumber = thisRow.find('.dt_orderLineNo').text();
jsonReturnObj.RejectReasonCode = thisRow.find('.dt_researchOutcome').find("option:selected").prop("value");
jsonReturnObj.RejectReasonNotes = $(this).find('.dt_researchNotes').find('input').val();
if(jsonReturnObj.RejectReasonCode != "" && jsonReturnObj.RejectReasonCode != null) {
if(jsonReturnObj.RejectReasonCode =="14. Other") {
if(jsonReturnObj.RejectReasonNotes == "" || jsonReturnObj.RejectReasonNotes == "null") {
alert(" Please add Research Notes");
jsonReturnObj.Processed = false;
$('#orderReportTable').append("call failed");
throw new Exception("Error message");
}
}
jsonReturnObj.Processed = true;
}else {
jsonReturnObj.Processed = false;
}
if($("#movedInput"+jsonReturnObj.OrderNumber+"-"+jsonReturnObj.OrderLineNumber).is(':checked')){
jsonReturnObj.IsAvailable = false;
}else{
jsonReturnObj.IsAvailable = true;
}
rejectReasons.PersistRejectReasons.push(jsonReturnObj);
var jsonReturnString = JSON.stringify(rejectReasons);
console.log("Rejecting Store Number is "+$("#storeNum").val())
var request2 = $.ajax({
headers: {
'RejectingStoreNum': $("#storeNum").val(), //thisRow.find('.dt_storeNo').text(), //thisRow.find("td").eq(16).text(),
'Content-Type': 'application/json'
},
type: "POST",
url: "persistStoreResearchOutcome", // REST endpoint. replace url1 with REST Endpoint
data : jsonReturnString,//json data. use data and contentType attributes for POST requests.
contentType: "application/json",
dataType: "text",
/*xhrFields: {
'withCredentials': true //Tell browser to provide credentials
},*/
crossDomain: true,// this is for cross domain requests*/
success: function (data, status, jqXHR){
console.log("status:"+status);
// $('#orderReportTable').append("call successful");
if(jsonReturnObj.Processed){
this.find('.dt_itemStatus').text("Researched");
table.draw();
}else{
this.find('.dt_itemStatus').text("Active");
table.draw();
}
},
error: function (jqXHR, status, errorThrown){
//console.log("failed: status:"+status);
$('#orderReportTable').append("call failed, error"+errorThrown);
alert("There was an error while trying to save this item");
}
});
});
});
How can I fix this?
The error message is
http://localhost:8080/persistStoreResearchOutcome 500 ()
send # jquery-3.2.1.min.js:4
ajax # jquery-3.2.1.min.js:4
(anonymous) # (index):544
each # jquery-3.2.1.min.js:2
each # jquery-3.2.1.min.js:2
(anonymous) # (index):509
dispatch # jquery-3.2.1.min.js:3
q.handle # jquery-3.2.1.min.js:3
I tried different ways to loop over the table including the every() function from datatables,but keep getting the same error

pass two variable inside ajax data call in jquery function

I get two variable in my jquery function and how i pass it in my data inside ajax call and get it in laravel controller
This is my function
$('#updateProduct').on('submit', function(e){
e.preventDefault(e);
var redirect_url = $(this).find("[name='redirect_url']").val();
var url = $(this).attr('action');
var method = $(this).attr('method');
var videos = document.getElementById('videoToUpload').files[0];
var myData ={
'name': $(this).find("[name='name']").val(),
'description': $(this).find("[name='description']").val(),
'brand': $(this).find("[name='brand']").val(),
'category': $(this).find("[name='category']").val(),
'condition': $(this).find("[name='condition']").val(),
'shipper': $(this).find("[name='shipper']").val(),
'shipping_from': $(this).find("[name='shipping_from']").val(),
'shipping_paid_by': $(this).find("[name='shipping_paid_by']").val(),
'shipping_within' :$(this).find("[name='shipping_within']").val(),
'shipping_weight': $(this).find("[name='shipping_weight']").val(),
'shipping_fee': $(this).find("[name='shipping_fee']").val(),
'seller_get' : $(this).find("[name='seller_get']").val(),
'price_per_unit': $(this).find("[name='price_per_unit']").val(),
'selling_fee' : $(this).find("[name='selling_fee']").val(),
'is_active':$(this).find("[name='is_active']:checked").val(),
//'videos' :$("#videoToUpload").files[0],
//'videos' : document.getElementById('videoToUpload').files[0],
}
console.log(data);
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: {'myData':myData
'videos':new FormData("videos", document.getElementById('videoToUpload').files[0])
},
success: function(data){
alert("Products updated successfullly");
console.log(data);
//window.location.href = redirect_url;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
Here i am having two variable one videos and other myData now my question is how to pass these two variable in data and request this variable in laravel controller
You have done everything well, but forget to write comma
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: {'myData': myData, 'videos': new FormData("videos", document.getElementById('videoToUpload').files[0]) },
success: function(data){
// .........
},
error: function(jqXHR, textStatus, errorThrown) {
// .........
}
});
By the way, don't spend time to define each input to variable, use jquery serialize and PHP unserialize, or you can use this code below to create Serialize Object
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

Accepted use methods of javascript callbacks

I am looking for advice to ensure that I am using callbacks and javascript coding using generally accepted js guidelines. What is listed below is two functions which are chained together. Basically its a list of checks which need to be completed prior to creating the entity. I don't expect the final version to use a ajax POST but it is a good way to test all of the error handling.
Advice or recommendations would be appreciated!! I will give credit to the best explained and critiqued answer.
function relationship_check(app_label, model, company_id, params, form, callback_function){
// This will check to see if a relationship exists. This works even on new objects.
kwargs = $.extend({}, params);
kwargs['app_label'] = app_label;
kwargs['model'] = model;
kwargs['relationship__company'] = company_id;
kwargs['error_on_objects_exists_and_no_relation'] = true;
ajax_req = $.ajax({
url: "{% url 'api_get_discover' api_name='v1' resource_name='relationship' %}",
type: "GET",
data: kwargs,
success: function(data, textStatus, jqXHR) {
callback_function(form, params)
},
error: function(data, textStatus, jqXHR) {
results = $.parseJSON(data.responseText)
if (results['object_exists'] && ! results['relationships_exists']){
django_message(results['create_string'], "info");
} else {
django_message(results['error'], "error");
}
return false
}
})
return false
};
function create_community(form, data){
var self = $(this),
ajax_req = $.ajax({
url: self.attr("action"),
type: "POST",
data: data,
success: function(data, textStatus, jqXHR) {
django_message("Saved successfully.", "success");
},
error: function(data, textStatus, jqXHR) {
var errors = $.parseJSON(data.responseText);
$.each(errors, function(index, value) {
if (index === "__all__") {
console.log(index + " : " + value )
django_message(value[0], "error");
} else {
console.log(index + " : " + value )
apply_form_field_error(index, value);
}
});
}
});
}
$(document).on("submit", "#community_form", function(e) {
e.preventDefault();
clear_form_field_errors("#community_form");
var data = {
name: $(this).find("#id_name").val(),
city: $(this).find("#id_city").val(),
cross_roads: $(this).find("#id_cross_roads").val(),
website: $(this).find("#id_website").val(),
latitude: $(this).find("#id_latitude").val(),
longitude: $(this).find("#id_longitude").val(),
confirmed_address: $(this).find("#id_confirmed_address").val()
};
console.log(data)
relationship_check(
'community', 'community', '{{ request.user.company.id }}',
data, "#community_form", create_community);
});

Categories