Ajax request don't send data to controller metod - javascript

i am new to laravel 8 and ajax and also i am working in a group.
I have a blade view to view the data of a user and since from this view I would like to make it possible to modify some data without a form tag I have made a js script to send the new data to be modified to a method of a controller but this data does not never arrive at the controller as I notice that the mysql db and the profilo view is not updated, however some "debug" printouts report a success.
Where am I wrong? Thanks in advance.
This is the controller
class ProfiloUtente extends Controller{
public function visualizzaProfiloUtente(Request $request)
{
$id_utente = $request->session()->get('LoggedUser');
$flag_attore = $request->session()->get('Attore');
$utente = null;
if ($flag_attore === Attore::CITTADINO_PRIVATO) {
$utente = CittadinoPrivato::getById($id_utente);
}
if ($flag_attore === Attore::DATORE_LAVORO) {
$utente = DatoreLavoro::getById($id_utente);
}
if ($flag_attore === Attore::MEDICO_MEDICINA_GENERALE) {
$utente = MedicoMG::getById($id_utente);
}
return view('profilo', compact('utente'));
}
public function modificaProfiloUtente(Request $request)
{
$id_utente = $request->session()->get('LoggedUser');
$flag_attore = $request->session()->get('Attore');
$this->validation($request);
$input = $this->generalInput($request);
try {
User::updateInfo($id_utente, $input['nuovo_codice_fiscale'], $input['nome'], $input['cognome'], $input['citta_residenza'],
$input['provincia_residenza'], $input['email'], $input['password']);
if ($flag_attore === Attore::CITTADINO_PRIVATO) {
CittadinoPrivato::updateCittadino($input['codice_fiscale_attuale'], $input['nuovo_codice_fiscale']);
}
elseif ($flag_attore === Attore::DATORE_LAVORO) {
$input['partita_iva'] = $request->input('iva');
$input['nome_azienda'] = $request->input('nome_azienda');
$input['citta_azienda'] = $request->input('citta_sede_aziendale');
$input['provincia_azienda'] = $request->input('provincia_sede_aziendale');
DatoreLavoro::updateDatore($input['codice_fiscale_attuale'], $input['nuovo_codice_fiscale'], $input['partita_iva'], $input['nome_azienda'], $input['citta_azienda'], $input['provincia_azienda']);
}
elseif ($flag_attore === Attore::MEDICO_MEDICINA_GENERALE) {
$input['partita_iva'] = $request->input('iva');
MedicoMG::updateMedico($input['codice_fiscale_attuale'], $input['nuovo_codice_fiscale'], $input['partita_iva']);
}
}
catch(QueryException $ex){
return back()->with('update-error', 'Errore, modifica non avvenuta.');
}
return redirect('/profilo');
}
/**
* Raggruppa le validazioni dei dati comuni
* #param Request $request
*/
private function validation(Request $request) {
$validation = $request->validate([
'cf' => 'required|min:16|max:16',
'nome' => 'required|max:30',
'cognome' => 'required|max:30',
'citta_residenza' => 'required|max:50',
'provincia_residenza' => 'required|max:50',
'email' => 'required|email',
'psw' => 'required|min:8|max:40'
]);
}
private function generalInput(Request $request)
{
$input = [];
$input['nuovo_codice_fiscale'] = $request->input('cf');
$input['codice_fiscale_attuale'] = $request->input('cf_attuale');
$input['nome'] = $request->input('nome');
$input['cognome'] = $request->input('cognome');
$input['citta_residenza'] = $request->input('citta_residenza');
$input['provincia_residenza'] = $request->input('provincia_residenza');
$input['email'] = $request->input('email');
$input['password'] = $request->input('psw');
return $input;
}
}
This is the route
Route::post('/modificaProfilo', [ProfiloUtente::class, 'modificaProfiloUtente'])->name('modifica.profilo');
This the script for ajax request in blade view
var data = '<?php echo json_encode($utente) ?>';
data = JSON.parse(data);
getDataProfilePage(data); //get values ​​to update
sendDataProfilePage(data,"{{route('modifica.profilo') }}","{{csrf_token()}}");
sendDataProfilePage function in public/script/script.js
function sendDataProfilePage(data, url, csrfToken) {
var formData = new FormData();
formData.append("_token", csrfToken);
for (key in data) {
if (key == "codice_fiscale") {
formData.append("cf", data[key]);
formData.append("cf_attuale", data[key]);
} else if (key == "password") {
formData.append("psw", data[key]);
} else if (key == "partita_iva") {
formData.append("iva", data[key]);
} else {
formData.append(key, data[key])
}
}
for (var pair of formData.entries()) { //print for feedback
console.log(pair[0] + ', ' + pair[1]);
}
//send data
var request = new XMLHttpRequest();
request.open("POST", url);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("X-CSRF-TOKEN", csrfToken);
request.onreadystatechange = function() {
console.log("ready state " + request.readyState); //print for feedback
console.log("status " + request.status); //print for feedback
if (request.readyState === XMLHttpRequest.DONE) {
if (status === 0 || (status >= 200 && status < 400)) { //detect request succes
console.log("responseStatus " + request.status + " " + request.statusText); //print for feedback
} else {
console.log("responseStatus " + request.status + " " + request.statusText); //print for feedback
}
}
};
request.send(formData);
}

A FormData object is sent with content-type multipart/form-data not application/x-www-form-urlencoded. In your code remove the line where you set the content-type header, the correct content-type header will be set automatically.

Related

Form not sending message

I use heroku CORS anywhere proxy to solve CORS Access-Control-Allow-Origin in my form.
Now, my form showing message not send every time i tried to send a message. How can i solve this issue?
My form: Demo
Scripts:
const blogId="xxxxxxxxxxxxx";
var contactForm = document.querySelectorAll(".contact-form-blogger");
function an(req) {
try {
return JSON.parse(req)
} catch (req) {
return false
}
}
for (i = 0; i < contactForm.length; i++) {
var a = contactForm[i];
a.addEventListener("submit", function (submitUrl) {
submitUrl.preventDefault();
var form = submitUrl.target;
var req = new FormData(form),
cH = "blogID=" + typeof blogId !== "undefined" ? blogId : "";
req.forEach(function (cL, cK) {
cH += "&" + encodeURIComponent(cK) + "=" + encodeURIComponent(cL)
});
submitUrl = "https://cors-anywhere.herokuapp.com/https://www.blogger.com/contact-form.do";
req = new XMLHttpRequest;
req.open("post", submitUrl, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(cH);
req.onreadystatechange = function () {
var cK;
if (this.readyState === 4) {
if (this.status === 200) {
if (this.response != "") {
cK = an(this.responseText.trim());
if (cK.details.emailSentStatus == "true") {
form.reset();
var formSend = form.querySelector(".send-success");
if (formSend) {
formSend.style.display = "block";
}
} else {
var notSend = form.querySelector(".send-error");
if (notSend) {
notSend.style.display = "block";
}
}
}
}
}
}
})
}
You're using the demo server as your proxy, which is rate-limited and not open. See this announcement for details. You need to deploy it yourself and change the URL prefix to point to your version. The documentation, such as it is, can be found at the bottom of the README. Advanced options are here. You're also posting to Blogger, which doesn't accept a POST at that path (returns a 405, method not allowed).

using JSON object in different function in javascript

I have a javascript which parse the server data and stores it in a variable. I can use that variable only in one function but not in multiple functions, please find the javascript code below.
function serverData(command, param) {
console.log('command is ' + command + ' param is ' + param);
if (!command) {
console.log('Command not recieved, No call to Server');
return;
}
var url = 'ProgramSetting.cgi?command=' + command;
if (param) {
url += '&' + param;
}
var xhttp = new XMLHttpRequest();
xhttp.open('GET', url, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
responseHandler(command, data);
}
};
}
function responseHandler(command, jsonData) {
if (!jsonData) {
console.log('Json from server not defined!!!');
return;
}
switch (command) {
case 'set':
if (jsonData.result == 'success') {
document.getElementById('info').innerHTML = 'INFO: Committed successfully!';
} else {
if (jsonData.options && jsonData.options.length > 0) {
var failedOptions = '';
for (var i = 0; i < jsonData.options.length; i++) {
failedOptions += ' ' + jsonData.options[i];
}
document.getElementById('info').innerHTML =
'ERROR: Failed to commit following option(s)-' + failedOptions;
} else {
console.log('Failed to Commit');
document.getElementById('info').innerHTML = 'ERROR: Failed to Commit';
}
initialPageLoad();
document.getElementById('info').style.color = 'red';
}
break;
case 'get':
console.log('jsonData.POLICY is ' + jsonData.POLICY);
if (jsonData.POLICY == 'gehc') {
document.getElementById('list1').checked = true;
gehc();
} else if (jsonData.POLICY == 'strict') {
document.getElementById('list2').checked = true;
strictgehc();
} else if (jsonData.POLICY == 'custom') {
document.getElementById('list3').checked = true;
custom(jsonData);
}
break;
default:
console.log("we don't support this");
}
}
function custom(jsonData) {
console.log('Custom called');
console.log('jsonData.MINLEN_RANGE is ' + jsonData.MINLEN_RANGE);
document.getElementById('Minlen_text').value = jsonData.MINLEN_RANGE;
document.getElementById('Minlen_text').disabled = false;
console.log('jsonData.EXPIRY is ' + jsonData.EXPIRY);
document.getElementById('Expiry_text').value = jsonData.EXPIRY;
document.getElementById('Expiry_text').disabled = false;
document.getElementById('reset').disabled = false;
}
function initialPageLoad() {
console.log('Retrieving data from Server calling get');
serverData('get');
}
In the above script I am able to use jsonData in responseHandler() function but cannot use in``custom()` function.

How to Open a URL/link in between a running ajax call and destroy all running ajax call?

I am working on Web page having an ajax call to the server and from the server(Controller) again a WCF service is called(which takes time) for fetching some data.
Inside server(Controller) i called to service in Parallel by using Task and async-await.
My problem is:
after opening the page that has code for calling the controller and WCF service, I can't redirect my tab/page to another URL by clicking on anchor tab present in UI. until ajax call result is retrieved.
UI CODE:
$(function () {
if (AutomationType.toLowerCase() === "desktop") {
$.ajax({
async: true,
url: "/" + AutomationType + "/Home/GetAllController",
data: { "hostName": hostname},
type: 'POST',
dataType: 'json'
}).success(function (response) {
debugger;
})
}
});
i have tried to abort the ajax call also as below,
$(function() {
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(i, jqXHR) { // cycle through list of recorded connection
jqXHR.abort(); // aborts connection
$.xhrPool.splice(i, 1); // removes from list by index
});
}
$.ajaxSetup({
beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); }, // annd connection to list
complete: function(jqXHR) {
var i = $.xhrPool.indexOf(jqXHR); // get index for current connection completed
if (i > -1) $.xhrPool.splice(i, 1); // removes from list by index
}
});
})
// Everything below this is only for the jsFiddle demo
$('a').click(function () {
$.xhrPool.abortAll();
});
Server(Controller) Code
public async Task<JsonResult> GetAllController(string hostName)
{
string IsControllerRunning = string.Empty;
var currentHost = string.Empty;
var currentRunId = string.Empty;
var currentStatus = string.Empty;
var ipDns = string.Empty;
Stopwatch sw = new Stopwatch(); sw.Start();
List<List<ExecutionStepResult>> returnresultArray = new List<List<ExecutionStepResult>>();
List<Task<IEnumerable<ExecutionStepResult>>> taskList = new List<Task<IEnumerable<ExecutionStepResult>>>();
Debug.WriteLine("starting 1 " + sw.Elapsed);
var resultArray = hostName.TrimEnd('^').Split('^');
for (int i = 0; i < resultArray.Length; i++)
{
string host = resultArray[i];
Task<IEnumerable<ExecutionStepResult>> task = new Task<IEnumerable<ExecutionStepResult>>(() => getServiceResultByTask(host));
task.Start();
taskList.Add(task);
}
foreach (Task<IEnumerable<ExecutionStepResult>> taskitem in taskList)
{
try
{
Debug.WriteLine("calling task " + sw.Elapsed);
IEnumerable<ExecutionStepResult> val = await taskitem;
returnresultArray.Add(val.ToList());
}
catch (Exception ex)
{
returnresultArray.Add(new List<ExecutionStepResult>() { new ExecutionStepResult() { IsError = true, ErrorMessage="true" ,CustomMessage = ex.Message.ToString() } });
}
}
for (int i = 0; i < resultArray.Length; i++)
{
string host = resultArray[i];
currentHost = host.Split('|').GetValue(1).ToString();
currentStatus = host.Split('|').GetValue(2).ToString();
currentRunId = host.Split('|').GetValue(0).ToString();
ipDns = host.Split('|').GetValue(3).ToString();
List<ExecutionStepResult> exeResponse = returnresultArray[i].ToList();
if (exeResponse.Count() > 0 && (currentStatus != "3" || (currentStatus == "3" && exeResponse[i].ErrorMessage == "true")))
IsControllerRunning += host + "|" + exeResponse[0].CustomMessage + "^";
else if (exeResponse.Count() > 0 && currentStatus == "3" && exeResponse[0].ErrorMessage == "false")
IsControllerRunning += host;
}
Debug.WriteLine("end " + sw.Elapsed);
sw.Stop();
return Json(IsControllerRunning, JsonRequestBehavior.AllowGet);
}
calling WCF service:
private IEnumerable getServiceResultByTask(string hosts)
{
using (var service = new RemoteCommandClient())
{
try
{
System.Threading.Thread.Sleep(15000);
string currentHost = hosts.Split('|').GetValue(1).ToString();
string currentStatus = hosts.Split('|').GetValue(2).ToString();
string currentRunId = hosts.Split('|').GetValue(0).ToString();
string ipDns = hosts.Split('|').GetValue(3).ToString();
IEnumerable<ExecutionStepResult> result = service.ExecuteRemoteWithRunId("CHECK_CURRENT_EXECUTION", Convert.ToInt32(currentRunId));
return result;
} catch (Exception ex)
{ throw ex; }
}
}
Still, I don't know how to open /redirect a page URL if an ajax call is running on the server. I am using signalR in the same page also. Please help.

send multiple ajax call to a same file

I have a big table and my idea to optimize my program is to get the information one by one and update the table as the information arrives.
To do that I am using an ajax call to a php file which collect the data from the database. I am trying to send and receive the data one by one:
for (var i = depF; i <= depT; i++) {
xmlhttp.open("GET", "../../php_includes/reports/InventoryReportPage.php?date=" + arguments[0] + "&depF=" + i + "&depT=" + i + "&subT=" + subT + "&subF=" + subF + "&catT=" + catT
+ "&catF=" + catF + "&Tar=" + Tar, true);
xmlhttp.send();
console.log("sent ajax");
}
this code will correctly send 2 ajax calls (in the browser I can see two "sent ajax"). However in the receiver:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
console.log("recieved");
if (xmlhttp.responseText) {
var table = document.getElementById("inventoryReport");
table.innerHTML += xmlhttp.responseText;
}
}
}
I only see one return value. Any idea if I am even allowed to use ajax calls like this?
The whole function:
var isClicked = false;
function onClick(date, depF, depT, subF, subT, catT, catF, Tar) {
//alert(date+ depF+ depT+ subF+ subT+ catT+ catF+ Tar)
// return null;
if (!isClicked) {
console.log("in the function");
var clicked = arguments[0];
isClicked = true;
var div = clicked + "apDiv";
var browserSupport = (navigator.userAgent.indexOf('Firefox') != -1) || ((navigator.userAgent.indexOf('Chrome') != -1) || (navigator.userAgent.indexOf('Safari') != -1));
if (browserSupport) {
var xmlhttp = new XMLHttpRequest();
}
else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (!xmlhttp) {
alert("your browser doens't supposrt XMLHTTP " + navigator.userAgent);
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
console.log("recieved: "+xmlhttp.responseText);
if (xmlhttp.responseText) {
var table = document.getElementById("inventoryReport");
table.innerHTML += xmlhttp.responseText;
}
}
}
for (var i = depF; i <= depT; i++) {
xmlhttp.open("GET", "../../php_includes/reports/InventoryReportPage.php?date=" + arguments[0] + "&depF=" + arguments[1] + "&depT=" + arguments[2] + "&subT=" + subT + "&subF=" + subF + "&catT=" + catT
+ "&catF=" + catF + "&Tar=" + Tar, true);
xmlhttp.send();
console.log("sent the ajax");
}
}
}
The reason your code don't work as you expect is that you basically overwrite the requests you are doing. You can try something like this:
var reqs = [];
for (var i = depF; i <= depT; i++) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/", true);
xmlhttp.send();
reqs.push(xmlhttp);
}
reqs.forEach(function(req) {
req.onreadystatechange = function()
{
if (req.readyState === 4 && req.status === 200)
{
console.log("recieved");
if (req.responseText) {
var table = document.getElementById("inventoryReport");
table.innerHTML += req.responseText;
}
}
}
})

why my textbox doesnot return any proper value in jquery?

I have created this controller for for getting existing value by searching id. this is my controller for searching data by id. this code is running well but result is not acceptable. i am new in jquery that's why i am explaining this very helpfully..
public string Search(string id=null)
{
string[] ci = new string[9];
//return "Artistry";
string cn = null;
cn = Request.QueryString["id"];
if (cn != null)
{
ClientInfo c = db.SingleOrDefault<ClientInfo>("where CId='" + cn + "'");
if (c != null)
{
// ci[0] = c.CId.ToString();
ci[1] = c.CName;
ci[2] = c.CCName;
ci[3] = c.PhoneNo.ToString();
ci[4] = c.Fax;
ci[5] = c.Email;
ci[6] = c.Address;
ci[7] = c.PostalCode.ToString();
ci[8] = c.Country;
return ci[5];
}
else
return null;
}
else
return null;
//*/
}
My view page script for showing my data..
<script type="text/javascript">
$(document).ready(function () {
$('#CId').blur(function () {
var v = $('#CId').val();
var url = "/Clients/Search/" + v;
// alert("Test : " + url);
$.get(url, function (data, status) {
$("#CName").val(1);
$("#CCName").val(2);
$("#PhoneNo").val(3);
$("#Fax").val(4);
$("#Email").val(5);
$("#Address").val(6);
$("#PostalCode").val(7);
$("#Country").val(8);
alert("Test : " + data + " Status :" + status);
});
});
});
</script>
And finally my sql server database for showing data in views are..
SELECT TOP 1000 [CId]
,[CName]
,[CCName]
,[PhoneNo]
,[Fax]
,[Email]
,[Address]
,[PostalCode]
,[Country]
FROM [test].[dbo].[ClientInfo]
I think you should return json type data like so:
public JsonResult Search(string id=null)
{
// view code
return Json(new {info=ci[5]});
}
And client code:
$.get(url, function (data, status) {
alert("Test : " + data.info + " Status :" + status);
});

Categories