302 error when post alot of data using Ajax - javascript

$('#update_reading').click(function(e) {
e.preventDefault();
var values = [];
$("table tr").each((_, row) => {
var value = {};
$(row).find(":input[name='mono_cmr[]']").each((__, e) =>
value['mono_cmr'] = $(e).val()
);
$(row).find(":input[name='mono_pmr[]']").each((__, e) =>
value['mono_pmr'] = $(e).val()
);
$(row).find(":input[name='color_cmr[]']").each((__, e) =>
value['color_cmr'] = $(e).val()
);
$(row).find(":input[name='color_pmr[]']").each((__, e) =>
value['color_pmr'] = $(e).val()
);
$(row).find(":input[name='scn_cmr[]']").each((__, e) =>
value['scn_cmr'] = $(e).val()
);
$(row).find(":input[name='scn_pmr[]']").each((__, e) =>
value['scn_pmr'] = $(e).val()
);
$(row).find(":input[name='asset_id[]']").each((__, e) =>
value['asset_id'] = $(e).val()
);
values.push(value);
});
// console.log(values)
values.shift();
values.shift();
values.shift();
values.shift();
var billing_date = $('#billing_date').val();
$("#overlay").fadeIn(300);
$.ajax({
type: "POST",
dataType: "json",
url: 'billing/post_reading',
data: {'values': values,'billing_date': billing_date,"_token":"{{ csrf_token() }}"},
success: function(data){
// var msg =JSON.parse(data);
}
}).done(function() {
setTimeout(function(){
$("#overlay").fadeOut(300);
alert("Reading Updated Successfully");
},
500);
});
});
</script>
i am using above to execute an Ajax call to post Data the script works well when i have like 10 input but when having like 400 rows to post i get 302 not found error am unable to find why am getting this redirect and data is not posted. The below is what is seen in inspect
how can i handle this issue?
the request also shows blocked

Related

Convert jquery ajax to fetch

Does someone knows jquery and can help me convert this ajax to js fetch ?
Unfortunately, I don't know jquery and I need to convert this into js fetch.
function ajaxLogoutDetailsApi() {
$.ajax({
type: "GET",
url: "OIDCGetLogoutDetails",
async: false,
cache: false,
data: "json",
success: function (data, status, xhr) {
data = data.replace('\/\*', '');
data = data.replace('\*\/', '');
var dataJson = JSON.parse(data);
if (dataJson.logoutUrl != null) {
document.location.href = dataJson.logoutUrl;
}
},
error: function (xhr, status, err) {
console.log("error in ajaxLogoutDetailsApi");
}
});
}
Appreciate every hint.
I was going to use async/await but since there's that odd replacing before the JSON gets parsed I've reverted to old-school fetch with "thenables".
function ajaxLogoutDetailsApi() {
const endpoint = 'OIDCGetLogoutDetails';
// Fetch the JSON
fetch(endpoint)
// This is returned as the first argument
// of "then"
.then(json => {
// Weird replacement stuff
const updated = json
.replace('\/\*', '')
.replace('\*\/', '');
// Parse the JSON
const data = JSON.parse(updated);
// Set the new page if the condition is met
if (data.logoutUrl) {
window.location.href = data.logoutUrl;
}
})
// Catch any errors
.catch(error => {
console.error('Error:', error);
});
}

JavaScript - Wait until multiple ajax requests are done then do something

I have two ajax calls in JavaScript that add content to the page asynchronously. I need to create a "timeout" function (or something similar) that waits until they're both done loading to then execute more code. Here is what I have so far
https://jsfiddle.net/qcu5asnj/
<div class='resultsSection'>
Example
</div>
<script>
var loading_first = "loading";
var first_ajax = {
url: 'https://example.com/load.php?q=fast',
type: "GET",
success: function( data ) {
console.log("success");
$(".resultsSection").append(data);
loading_first = "done";
}
};
$.ajax( first_ajax );
var loading_second = "loading";
var second_ajax = {
url: 'https://example.com/load.php?q=slow',
type: "GET",
success: function( data ) {
console.log("success");
$(".resultsSection").append(data);
loading_second = "done";
}
};
$.ajax( second_ajax );
// Need to create a function that waits until both are done. I know this is wrong
if((loading_first == "done") && (loading_second == "done")){
console.log("Both done loading, execute more code here");
}
</script>
Store the promises returned by $.ajax in variables and use Promise.all()
const req1 = $.ajax('https://jsonplaceholder.typicode.com/todos/1').then(data => {
console.log('First request done')
return data
})
const req2 = $.ajax('https://jsonplaceholder.typicode.com/todos/2').then(data => {
console.log('Second request done')
return data
})
Promise.all([req1, req2]).then(results=>{
console.log('All done')
console.log('Combined results',results)
}).catch(err=> console.log('Ooops one of the requests failed'))
.as-console-wrapper {max-height: 100%!important;top:0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

how to fix 'fetch' is undefined in ie11?

I am coming to an issue where my code below, says that 'fetch' is undefined in internet explorer 11. I am using the latest jquery which is jquery-3.3.1.min.js and I even tried $.ajax instead of fetch but that did not work. Can anyone help me solve this issue, with my code below. That it can even work in ie11. thank you very much!
when I do $_ajax instead fetch I get an console error saying res.text is not a function TypeError: res.text is not a function
Here is my code:
"use strict";
$(function () {
var myData = [];
$.get("#{request.contextPath}/JobSearchItem.xhtml", function (data) {
$("#searchTextField").autocomplete({
minLength: 2,
source: myData,
select: function select(event, ui) {
event.preventDefault();
var url = '#{request.contextPath}/index.xhtml';
var searchValue = ui.item.value;
var data = new FormData();
data.append('searchValue', searchValue);
fetch(url, {
body: data,
method: "post"
}).then(function (res) {
return res.text();
}).then(function (text) {
$('#results').append($(text).find('#textTable'));
$('#results').append($(text).find('table'));
$('#results').append($(text).find('#bestTable'));
$("#clearone").show();
});
},
response: function response(event, ui) {
if (!ui.content.length) {
var message = { value: "", label: "NO SEARCH RESULT FOUND" };
ui.content.push(message);
}
}
});
$.each(data, function (k, v) {
myData.push({
id: v.id,
label: v.label,
value: v.id
});
});
});
$("#sJobClass").change(function () {
var jobClassCd = $(this).val();
if (jobClassCd !== 0) {
var url = '#{request.contextPath}/index.xhtml';
var searchValue = $('#sJobClass').val();
var data = new FormData();
data.append('searchValue', searchValue);
fetch(url, {
body: data,
method: "post"
}).then(function (res) {
return res.text();
}).then(function (text) {
$('#results').append($(text).find('#textTable'));
$('#results').append($(text).find('table'));
$('#results').append($(text).find('#bestTable'));
$("#clearone").show();
});
};
});
});
Do this-
npm install --save isomorphic-fetch es6-promise
import it in your code and use it.

How to assign an Ajax response to a variable in another function in React?

I have an ajax call that responds with a list of movies, and then I have an other function with an other ajax call that returns the genre names, since the first call only has the id of the genre, then I relate the genreId with its name and I assign it to the JSON on the first ajax call, kind of like assigning it to a variable. The problem that I have is that since ajax is asynchronous, it always ends up undefined. I don't want to make it synchronous since it will end up in a bad user experience.
First ajax call
$.ajax({
url: urlString,
success: (searchResults) => {
const results = searchResults.results
var movieRows = [];
results.forEach(movie => {
movie.genres = this.getMovieGenres(movie.media_type, movie.genre_ids);
const movieRow = <MovieRow key={movie.id} movie={movie}/>;
movieRows.push(movieRow)
});
this.setState({rows: movieRows})
},
error: (xhr, status, err) => {
console.log("Failed to fetch data...")
}
})
Function that I call with the second ajax call
getMovieGenres (mediaType ,movieGenreIds) {
urlString = `https://api.themoviedb.org/3/genre/movie/list?api_key=${config.movieDBbApiKey}&language=en-US`ApiKey}&language=en-US`
var genres = []
$.ajax({
url: urlString,
async: true,
crossDomain: true,
method: "GET",
success: searchResults => {
for (let i = 0; i < movieGenreIds.length; i++) {
for (let j = 0; j < searchResults.genres.length; i++){
console.log(searchResults.genres[j].id)
if (movieGenreIds[i] === searchResults.genres[j].id) {
genres.push(searchResults.genres[j].name)
}
}
}
},
error: (xhr, status, err) => {
console.log("Failed to fetch data...")
}
})
return genres
}
There are variouse solutions to your problem.
The simplest is to make the second ajax call in the callback of the first ajax call. In the second call you'll have both results from first ajax call and the second. Then make transforms and set state in the second call.
Other options (the reccomended one) is to work with Axios or Fetch that rely on Promises.
Promises can be evaded with Promise.all:
var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "foo");
});
Promise.all([p1, p2, p3]).then(values => {
console.log(values); // [3, 1337, "foo"]
});
you can try this:
var promise = new Promise((resolve,reject)=> {
return $.ajax({
url: urlString,
success: (searchResults) => {
return resolve(searchResults.results)
},
error: (xhr, status, err) => {
return reject("Failed to fetch data...")
}
})
})
function that return a promise
getMovieGenres (mediaType ,movieGenreIds) {
urlString = `https://api.themoviedb.org/3/genre/movie/list?api_key=${config.movieDBbApiKey}&language=en-US`ApiKey}&language=en-US`
var genres = []
return new Promise((resolve,reject)=> {
$.ajax({
url: urlString,
async: true,
crossDomain: true,
method: "GET",
success: searchResults => {
for (let i = 0; i < movieGenreIds.length; i++) {
for (let j = 0; j < searchResults.genres.length; i++){
console.log(searchResults.genres[j].id)
if (movieGenreIds[i] === searchResults.genres[j].id) {
genres.push(searchResults.genres[j].name)
}
}
}
return resolve(genres)
},
error: (xhr, status, err) => {
return reject("Failed to fetch data...")
}
})
})
}
finally:
promise().then(results => {
var movieRows = [];
var tasks = []
results.forEach(movie => {
tasks.push(getMovieGenres(movie.media_type, movie.genre_ids))
});
Promise.all(tasks).then(output => {
output.forEach(movie => {
const movieRow = <MovieRow key={movie.id} movie={movie}/>;
movieRows.push(movieRow)
})
this.setState({rows: movieRows})
})
})
Hope to help you!

ajax validation login doesn't shows

I am using laravel 4 and I am trying to display login validation by using ajax. I have the following javascript validation:
jQuery('#form-signin').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('#form-signin').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".validation-error-inline").hide();
}
})
.done(function(data)
{
$('#validation-login').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
alert(arr);
}
else {
window.location = data.redirect_to;
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
and in my userController:
public function doLogin() {
Input::flash();
$data = [
"errors" => null
];
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => 'Invalid username or password',
);
return Response::json($response_values);
}else
{
echo 'error';
}
}
}
The problem is that it always displays "error" message, which means that jaax request isn't performed. What is wrong?
In your doLogin() function try
return Response::json(array(
'validation_failed' => 1,
'errors' => 'Unknow error'
))
instead of
echo "error"

Categories

Resources