Getting data from database but not post and update - javascript

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:

Related

Access object properties - Ajax Call

I have simple AJAX call.
It looks like this:
myApp.onPageInit('about', function (page) {
search_term = $$("#search_term").val();
const key = "xxxx-xxxx";
const nick = "https://api.xxx.xxx/" + search_term + "?api_key=" + key;
$$.ajax({
url:nick,
type:'GET',
dataType: JSON,
beforeSend: function(){
//myApp.showPreloader('Please wait...');
},
success: function(data) {
//myApp.hidePreloader();
console.log(data);
console.log(data['summonerLevel']);
},
statusCode: {
404: function() {
// myApp.alert('Account does not exist.', 'ERROR');
}
},
error: function(data) {
myApp.alert('Account does not exist.', 'ERROR');
// ak je ovaj error, netko je dirao putanju - fajl
},
});
})
When I'm trying to get properties from data object, every time it says undefined.
Console log: {"id":"xxxx","accountId":"xxxx","puuid":"xxxx","name":"Data","profileIconId":3015,"revisionDate":1546082318000,"summonerLevel":37}
Second console log: undefined
I tried dot notation and bracket notation, but everytime same status(undefined).
Like this:
console.log(data['summonerLevel']);
console.log(data.summonerLevel);
Any suggestion for this problem?
use JSON.Parse() method and try taking the value with object.attributename
$.ajax({
url:nick,
type:'GET',
dataType: JSON,
beforeSend: function(){
},
success: function(data) {
var data=JSON.Parse(data);
console.log(data.summonerLevel);
console.log(data.accountId);
},
statusCode: {
404: function() {
}
},
error: function(data) {
},
});

How do I send files via jQuery AJAX with multiple parameter to an MVC controller?

enter code hereI have read several answers about this question, but no one works.
I have the following code but my HttpPostedFileBase[] array is always null.
The Other parameters has the right value, but the HttpPostedFileBase[] is always null.
What am i missing??
$('#myFile').on('change', function (e) {
var fileName = e.target.files[0].name;
archivosProcesar = new FormData();
for (var i = 0; i <= e.target.files.length -1; i++) {
archivosProcesar.append(i, e.target.files[i]);
}
});
function aplicarFragmentacion() {
var ids = obtenerAfiliadosSeleccionados();
var data = {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
archivos: archivosProcesar
}
if (!validarProcentajes() & !validarSeleccionados(ids)) {
$.ajax({
data: data,
url: urlAplicarFrag,
type: 'POST',
processData: false,
beforeSend: function () {
//$("#resultado").html("Procesando, espere por favor...");
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
}
}
Controller.cs
public async Task<ActionResult> AplicarFragmentacion(decimal fragmento1, decimal fragmento2, string[] segment\
os, HttpPostedFileBase[] archivos)
{
List<Credito> lstSegmentos = new List<Credito>();
try
{
ProgressHub.SendMessage("Iniciando proceso de fragmentación...", 10);
lstSegmentos = await FragmentacionNegocio.AplicarFragmentacion(fragmento1, fragmento2, segmentos)\
;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return Json(lstSegmentos, JsonRequestBehavior.AllowGet);
}
Try submitting a FormData object, not an anonymous object with a FormData field. Also it is my understanding that the contentType should be set to false.
var formData = new FormData();
formData.append('fragmento1', parseInt($('#fragmento1').val());
formData.append('fragmento2', parseInt($('#fragmento2').val());
formData.append('segmentos', obtenerAfiliadosSeleccionados());
formData.append('archivos', $('#fileupload')[0].files[0]);
$.ajax({
type: 'POST',
data: formData,
url: urlAplicarFrag,
type: 'POST',
processData: false,
contentType: false,
[...]
});
The fix was to use this plug in
https://jquery-form.github.io/form/
In this way
$(this).ajaxSubmit({
url: urlAplicarFrag,
data: {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
fechaReenvio: $('#fecha-reenvio').val()
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
check the plugin website

one event triggers multiple AJAX request

<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);
}
});

JavaScript runtime error: Unable to get property 'domain_name' of undefined or null reference

I'm getting the popup as Undefined and showing the error as below:
Unable to get property 'domain_name' of undefined or null reference.
Can Any body help on this
From View:
#Html.ActionLink("Details", "",
new { id = item.id },
new { onclick = "someFunction(" + item.id + ")",
href = "javascript:void(0)" })
Javascript
function someFunction(id) {
$.ajax({
type: 'POST',
url: '#Url.Content("~/")Contracts/Test/',
data: { 'id': id },
dataType: 'json',
success: function (data) {
alert(data.domain_name);
},
error: function (xhr, status, exception) {
alert("Error: " + exception + ", Status: " + status);
}
});
}
Controller action
enter code here
public JsonResult Test(int id)
{
var result = (from cntrct in db.contracts where cntrct.id == id
select new { cntrct.domain_name, cntrct.id}).ToArray();
return Json(result);
}
Below is the data which I"m getting from db but can't pass to JavaScript back.
Error
SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3.
Contracts
Can you try this in the Json Action method
Action
public JsonResult Test(int id)
{
var result = (from cntrct in db.Contracts where cntrct.ID == id
select new { cntrct.domain_name, cntrct.id, cntrct......}).ToArray();
return Json(result);
}
Script
function someFunction(id) {
$.ajax({
type: 'POST',
url: '#Url.Content("~/")Contracts/Test/',
data: { 'id': id },
dataType: 'json',
success: function (data) {
alert(data.domain_name);
}
});
}
Oohoo!! Finally I got this... Only thing we need to do is alert(data[0].domain_name); :)

handle jquery ajax error

in my MVC layout page I have the following:
$("body").ajaxError(
function (e, request) {
if (request.status == 403 || request.status == 500) {
window.location = '#Url.Action("LogOn", "Account", new {area = "", msg = "forbidden", returnUrl = HttpContext.Current.Request.RawUrl})' + window.location.hash;
return;
}
window.location = '#Url.Action("Index", "Error")';
}
);
on another page I'm performing an ajax call like so:
...
$.when(refreshActionLinks(row, machineId, packageId)).done(function(a1) {
row.find("span").text(opStatus).removeClass("pending");
progressbar.progressbar("destroy");
$(row).flash(bg[1], 1000);
});
...
javascript function:
function refreshActionLinks($row, machineId, packageId) {
try {
var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
console.log("refreshActionLinks => " + json);
$row.find("td.options div.actionLinks").html("<img src='#Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
return $.ajax({
url: "#Url.Action("GetActionLinks", "Packages")",
data: json,
timeout: 50000,
contentType: 'application/json',
type: 'POST',
success: function (data) {
if ($row.length) {
$row.find("td.options div.actionLinks").html(data);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
} catch(e) {
// hide icons
$row.find("a.action").remove();
}
}
The issue is that while refreshAction function is executing, clicking a menu link causes the ajax call to error out - which in this case is correct. BUT it does take me to /Index/Error page which is NOT correct. I would like "$("body").ajaxError" to handle all ajax errors on the site EXCEPT on the page I'm calling refreshActionLinks. Notice, I already have try/catch surrounding my ajax call. why doesn't that work?
thanks
figured it out:
ajax has a settings:
global: false
now my function looks like this:
function refreshActionLinks($row, machineId, packageId) {
try {
var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
console.log("refreshActionLinks => " + json);
$row.find("td.options div.actionLinks").html("<img src='#Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
return $.ajax({
url: "#Url.Action("GetActionLinks", "Packages")",
global: false, // disable error pages on failed ajax calls
data: json,
timeout: 50000,
contentType: 'application/json',
type: 'POST',
success: function (data) {
if ($row.length) {
$row.find("td.options div.actionLinks").html(data);
}
}
});
} catch(e) {
// hide icons
$row.find("a.action").remove();
}
}

Categories