using JSON object in different function in javascript - 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.

Related

Ajax request don't send data to controller metod

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.

js for newest chat message order

in my chat extension for phpBB, i use ajax for the js with a little jquery mixed in. i'm setting it up for users to select if they want the newest messages at the top or the bottom in accordance to their setting in their user control panel. the php side of it is done and works well but the js is still adding the new message at the top, ignoring the sort order in the php.
in the php. note that the sort order is set with this line
ORDER BY c.message_id ' . ($this->user->data['user_ajax_chat_messages_down'] ? 'DESC' : 'ASC');
i can't post the php in this post as the body is limited to 30000 characters. so i will post it if needed.
here is the js that does all the work
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
//******************************************************************************************
// This functions reads & returns the cookie value of the specified cookie (by cookie name)
//******************************************************************************************
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name !== document.cookie.substring(0, name.length))) {
return null;
}
if (start === -1)
return null;
var end = document.cookie.indexOf(';', len);
if (end === -1)
end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function deletecookie(name)
{
var cookie_date = new Date( ); // current date & time
cookie_date.setTime(cookie_date.getTime() - 1);
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
location.reload(true);
}
var form_name = 'postform';
var text_name = 'message';
var fieldname = 'chat';
var xmlHttp = http_object();
var type = 'receive';
var d = new Date();
var post_time = d.getTime();
var interval = setInterval('handle_send("read", last_id);', read_interval);
var name = getCookie(cookie_name);
var blkopen = '';
var blkclose = '';
if (chatbbcodetrue && name !== null && name !== 'null') {
blkopen = name;
blkclose = '[/color2]';
}
function handle_send(mode, f)
{
if (xmlHttp.readyState === 4 || xmlHttp.readyState === 0)
{
indicator_switch('on');
type = 'receive';
param = 'mode=' + mode;
param += '&last_id=' + last_id;
param += '&last_time=' + last_time;
param += '&last_post=' + post_time;
param += '&read_interval=' + read_interval;
if (mode === 'add' && document.postform.message.value !== '')
{
type = 'send';
for (var i = 0; i < f.elements.length; i++)
{
elem = f.elements[i];
param += '&' + elem.name + '=' + blkopen + "" + encodeURIComponent(elem.value) + blkclose;
}
document.postform.message.value = '';
} else if (mode === 'add' && document.postform.message.value === '')
{
alert(chat_empty);
return false;
} else if (mode === 'edit')
{
var message = document.getElementById('message').value;
type = 'edit';
mode += '/' + f;
param = '&submit=1&message=' + message;
} else if (mode === 'delete')
{
var parent = document.getElementById('chat');
var child = document.getElementById('p' + f);
parent.removeChild(child);
type = 'delete';
param += '&chat_id=' + f;
} else if (mode === 'quotemessage')
{
type = 'quotemessage';
param += '&chat_id=' + f;
}
xmlHttp.open('POST', query_url + '/' + mode, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = handle_return;
xmlHttp.send(param);
}
}
function handle_return()
{
if (xmlHttp.readyState === 4)
{
if (xmlHttp.status == 200)
{
results = xmlHttp.responseText.split('--!--');
if (type === 'quotemessage') {
if (results[0]) {
$text = document.getElementById('message').value;
document.getElementById('message').value = $text + results[0];
document.getElementById("message").focus();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type === 'edit') {
jQuery(function($) {
'use strict';
var opener = window.opener;
if (opener) {
$(opener.document).find('#p' + last_id).replaceWith(results[0]);
}
var popup = window.self;
popup.opener = window.self;
popup.close();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
});
} else if (type !== 'delete') {
if (results[1])
{
if (last_id === 0)
{
document.getElementById(fieldname).innerHTML = results[0];
} else
{
document.getElementById(fieldname).innerHTML = results[0] + document.getElementById(fieldname).innerHTML;
}
last_id = results[1];
if (results[2])
{
document.getElementById('whois_online').innerHTML = results[2];
last_time = results[3];
if (results[4] !== read_interval)
{
read_interval = results[4];
window.clearInterval(interval);
interval = setInterval('handle_send("read", last_id);', read_interval * 1000);
document.getElementById('update_seconds').innerHTML = read_interval;
}
}
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type == 'delete') {
var parent = document.getElementById('chat');
var child = document.getElementById('p' + results[0]);
if (child) parent.removeChild(child);
}
indicator_switch('off');
} else {
if (type == 'receive') {
window.clearInterval(interval);
}
handle_error(xmlHttp.status, xmlHttp.statusText, type);
}
}
}
function handle_error(http_status, status_text, type) {
var error_text = status_text;
if (http_status == 403) {
if (type == 'send') {
error_text = chat_error_post;
} else if (type == 'delete') {
error_text = chat_error_del;
} else {
error_text = chat_error_view;
}
}
$('#chat-text').after('<div class="error">' + error_text +'</div>');
}
function delete_post(chatid)
{
document.getElementById('p' + chatid).style.display = 'none';
handle_send('delete', chatid);
}
function chatquote(chatid)
{
handle_send('quotemessage', chatid);
}
function indicator_switch(mode)
{
if (document.getElementById("act_indicator"))
{
var img = document.getElementById("act_indicator");
if (img.style.visibility === "hidden" && mode === 'on')
{
img.style.visibility = "visible";
} else if (mode === 'off')
{
img.style.visibility = "hidden";
}
}
if (document.getElementById("check_indicator"))
{
var img = document.getElementById("check_indicator");
if (img.style.visibility === "hidden" && mode === 'off')
{
img.style.visibility = "visible";
} else if (mode === 'on')
{
img.style.visibility = "hidden";
}
}
}
function http_object()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
} else if (window.ActiveXObject)
{
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{
document.getElementById('p_status').innerHTML = (ie_no_ajax);
}
}
} else
{
document.getElementById('p_status').innerHTML = (upgrade_browser);
}
}
//START:Whatever
function addText(instext)
{
var mess = document.getElementById('message');
//IE support
if (document.selection)
{
mess.focus();
sel = document.selection.createRange();
sel.text = instext;
document.message.focus();
}
//MOZILLA/NETSCAPE support
else if (mess.selectionStart || mess.selectionStart === "0")
{
var startPos = mess.selectionStart;
var endPos = mess.selectionEnd;
var chaine = mess.value;
mess.value = chaine.substring(0, startPos) + instext + chaine.substring(endPos, chaine.length);
mess.selectionStart = startPos + instext.length;
mess.selectionEnd = endPos + instext.length;
mess.focus();
} else
{
mess.value += instext;
mess.focus();
}
}
//END;Whatever
function parseColor(color) {
var arr=[]; color.replace(/[\d+\.]+/g, function(v) { arr.push(parseFloat(v)); });
return {
hex: "#" + arr.slice(0, 3).map(toHex).join(""),
opacity: arr.length == 4 ? arr[3] : 1
};
}
function toHex(int) {
var hex = int.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
jQuery(function($) {
'use strict';
$(window).on('load', function () {
$("#smilies").click(function () {
$("#chat_smilies").toggle(600);
});
$("#bbcodes").click(function () {
$("#chat_bbcodes").toggle(600);
});
$("#chat_bbpalette").click(function () {
$("#chat_colour_palette").toggle(600);
});
});
var $chat_edit = $('#chat_edit');
$chat_edit.find('#submit').on('click', function(e) {
e.preventDefault();
handle_send('edit', $chat_edit.find('input[name=chat_id]').val());
});
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
$('#chat').on('click', '.username, .username-coloured', function(e) {
e.preventDefault();
var username = $(this).text(),
user_colour = ($(this).hasClass('username-coloured')) ? parseColor($(this).css('color')).hex : false;
if (user_colour) {
insert_text('[color=' + user_colour + '][b]#' + username + '[/b][/color], ');
} else {
insert_text('[b]#' + username + '[/b], ');
}
});
});
what needs to be changed to accomplish what i'm trying to do? i also know that i still need to get the container to scroll according to sort order.
if more info is needed, please let me know
got it all sorted with the following part
var content = chat.innerHTML;
chat.innerHTML = isDown ? (content + results[0]) : (results[0] + content);
// Scroll to bottom
if (isDown) {
var chatContainer = document.querySelector('.shout-body');
chatContainer.scrollTop = chatContainer.scrollHeight;
}```

record wav file in cordova and upload to api

I have created an app where I am recording an audio in wav format and then replaying that audio and then posting it to api for further processing.
But after posting data to api it says "not a wave file -- no riff header".
I tried this link also as reference.
Here is my javascript code of app:
var mediaVar = null;
var recordFileName = "recording.wav";
var mediaVarSrc = "cdvfile://localhost/sdcard/recording.wav";
var status = null;
var target = "";
document.getElementById("start-btn").addEventListener("click", function () {
createMedia(function () {
status = "recording";
mediaVar.startRecord();
}, onStatusChange);
$("#recordingText").show();
});
document.getElementById("stop-btn").addEventListener("click", function () {
stop();
});
function createMedia(onMediaCreated, mediaStatusCallback) {
if (mediaVar != null) {
onMediaCreated();
return;
}
if (typeof mediaStatusCallback == 'undefined') {
mediaStatusCallback = null;
}
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function (fileSystem) {
fileSystem.getFile(recordFileName, {
create: true,
exclusive: false
}, function (fileEntry) {
fileUrl = fileEntry.toURL();
mediaVar = new Media(fileUrl,
function () {}, onError, mediaStatusCallback);
onMediaCreated();
}, onError);
}, onError);
}
function stop() {
alert("Stop");
$("#recordingText").hide();
if (mediaVar == null) {
return;
}
if (status == 'recording') {
mediaVar.stopRecord();
mediaVar.release();
status = 'stopped';
play();
} else {
alert("Nothing stopped");
}
}
function play() {
if (mediaVar) {
status = "playing";
//playAudioFile(recordFileName);
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory + recordFileName, function (tempFile) {
alert(JSON.stringify(tempFile));
tempFile.file(function (tempWav) {
alert(JSON.stringify(tempWav));
var options = new FileUploadOptions();
options.chunkedMode = false;
options.fileKey = "file";
options.fileName = recordFileName;
options.mimeType = "audio/wav";
var ft = new FileTransfer();
ft.upload(tempFile.nativeURL, encodeURI(target), function () {
alert("Win");
}, function () {
alert("false");
}, options, true);
});
}, function (e) {
console.log("Could not resolveLocalFileSystemURL: " + e.message);
});
}
}
var myMedia = null;
function playAudioFile(src) {
myMedia = new Media(src,
function () { },
function (error) { },
function (status) { }
);
myMedia.play();
}
function stopplay(calledfrom) {
mediaVar.stop();
}
function recordAudio() {
if (myMedia == null) {
myMedia = new Media(srcurl,
function () {
console.log("recordAudio():Audio Success");
},
function (err) {
console.log("recordAudio():Audio Error: " + err.code);
});
}
myMedia.startRecord();
}
For recording I have used Media plugin. I am not able to figure out why this is happening.
Here is my api code
[HttpPost]
[Route("UploadFile")]
public string UploadFile()
{
string Result = String.Empty;
string path = HttpContext.Current.Server.MapPath("~\\App_Data");
string convertedFileName = "convert.wav";
try
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
else
{
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(path);
Task.Run(async () =>
{
await Request.Content.ReadAsMultipartAsync(streamProvider);
}).Wait();
var file = streamProvider.FileData[0];
FileInfo fileInfo = new FileInfo(file.LocalFileName);
string fileName = fileInfo.Name;
if (System.IO.File.Exists(path + "\\" + fileName))
{
using (WaveFileReader reader = new WaveFileReader(path + "\\" + fileName))
{
WaveFormat format = new WaveFormat(16000, 16, 1);
using (WaveFormatConversionStream convert = new WaveFormatConversionStream(format, reader))
{
WaveFileWriter.CreateWaveFile(path + "\\" + convertedFileName, convert);
convert.Close();
}
reader.Close();
}
System.IO.File.Delete(path + "\\" + fileName);
BingSpeechToText obj = new BingSpeechToText();
STTResponse _STTResponse = obj.ConvertAudio(path + "\\" + convertedFileName);
if (_STTResponse.Status && !String.IsNullOrEmpty(_STTResponse.Response))
{
Result = _STTResponse.Response;
}
else
{
Result = "No Result";
}
}
}
}
catch (Exception ex)
{
Result = ex.Message;
}
finally
{
if (System.IO.File.Exists(path + "\\" + convertedFileName))
System.IO.File.Delete(path + "\\" + convertedFileName);
}
return Result;
}
Try like below one,
static String API_KEY = "YOUR-KEY";
static String PROFILE_ID = "YOUR-PROFILE-ID";
static String LOCATION = "westus";
HttpClient httpclient = HttpClients.createDefault();
try {
URIBuilder builder = new URIBuilder(
String.format("https://%s.api.cognitive.microsoft.com/spid/v1.0/identificationProfiles/%s/enroll", LOCATION, PROFILE_ID));
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Ocp-Apim-Subscription-Key", API_KEY);
request.setEntity(new FileEntity(new File("test.wav"), ContentType.APPLICATION_OCTET_STREAM));
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
// Response is empty on success; the following will contain the URI where you can check the status
System.out.println(response.getHeaders("Operation-Location")[0].getValue());
} catch (Exception e) {
System.out.println(e.getMessage());
}

Sharepoint javascript list form validation on presaveaction

I have a Function named "ViewItem" that calls 2 more functions: "success" and "failed". When "success" is called it goes and check if a value exists and return true if the value exists or false if the value doesnt exist. Lastly I have a 4th function called "PresaveAction" what this function does is check if a value is "yes" or "no", if "no" it returns true and allows me to save and what I want to achieve is if the value is "yes" call the "success" function from before and depending if "success" returns true or false allow me to save. So how do I pass to the PreSaveAction function what "success" return?
function ViewItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('demoTrainingRoom2');
var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, 'Include(Title, EventDate, time2)');
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var currentTitle = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
for(var i = 0; i < this.allItems.get_count(); i++){
var item = this.allItems.get_item(i);
console.log(item.get_item('time2') + ' - ' + currentTitle );
if (currentTitle == item.get_item('time2')){
alert('There is an event with the same Start Date on DemoTrainingRoom2' + ' ' + item.get_item('time2') + ' - ' + currentTitle );
return true; // or item
}
}
return false;
}
function failed(sender, args) {
alert("failed. Message:" + args.get_message());
}
function PreSaveAction() {
var time = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
alert(time + " Current Start Time");
if(SPUtility.GetSPField('demoField').GetValue() == "no")
{
alert('No need for validation');
return true; // save file
}
else
{
alert('Need to validate date');
//here is where i need to call the result from success
return false; // don't save file
}
}
#Thriggle are you suggestion something like this
var result; //global variable
function ViewItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('demoTrainingRoom2');
var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, 'Include(Title, EventDate, time2)');
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var currentTitle = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
for(var i = 0; i < this.allItems.get_count(); i++){
var item = this.allItems.get_item(i);
console.log(item.get_item('time2') + ' - ' + currentTitle );
if (currentTitle == item.get_item('tiempo2')){
alert('There is an event with the same Start Date on DemoTrainingRoom2' + ' ' + item.get_item('time2') + ' - ' + currentTitle );
var result = "Yes";
return true; // or item
}
}
var result = "No";
return false;
}
function failed(sender, args) {
alert("failed. Message:" + args.get_message());
}
function PreSaveAction() {
var time = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
alert(time + " Current Start Time");
if(SPUtility.GetSPField('demoField').GetValue() == "no")
{
alert('No need for validation');
return true;
}
else if(SPUtility.GetSPField('demoField').GetValue() == "yes" && result == "Yes")
{
alert(result);
//return false;
}
else if(SPUtility.GetSPField('demoField').GetValue() == "yes" && result == "No")
{
alert(result);
//return false;
}
}
This is how i did it
var originalSaveButtonClickHandler = function(){};
$(document).ready(function () {
var saveButton = $("[name$='diidIOSaveItem']") //gets form save button and ribbon save button
if (saveButton.length > 0) {
originalSaveButtonClickHandler = saveButton[0].onclick; //save original function
}
$(saveButton).attr("onclick", "PreSaveAction2()"); //change });
});
//override the default PreSaveAction
//custom PreSaveAction
function PreSaveAction2(callback) {
alert("iniciando validacion");
var time = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
if(SPUtility.GetSPField('demoField').GetValue() == "no") {
alert('No need for validation');
originalSaveButtonClickHandler();
//return true;
}
else if(SPUtility.GetSPField('demoField').GetValue() == "yes") {
var resultado1 = ViewItem('demoTrainingRoom2').then(
function(allItems) {
var currentTitle = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
var res = "No";
for (var i = 0; i < allItems.get_count(); i++) {
var item = allItems.get_item(i);
console.log(item.get_item('tiempo2') + ' - ' + currentTitle );
if (currentTitle == item.get_item('tiempo2')){
res = "Si";
console.log('There is an event with the same Start Date on DemoTrainingRoom2'
+ ' ' + item.get_item('tiempo2') + ' - ' + currentTitle);
}
}
if (res == "Si") {
alert(res + " there's an event on room 2");
//return false;
} else {
alert(res + " no event on 2");
originalSaveButtonClickHandler();
//return true;
}
},
function (sender, args) {
alert("failed. Message:" + args.get_message());
}
);
}
}
function ViewItem(listTitle) {
var deferred = $.Deferred();
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var query = SP.CamlQuery.createAllItemsQuery();
var allItems = list.getItems(query);
context.load(allItems, 'Include(Title, EventDate, tiempo2)');
context.executeQueryAsync(
Function.createDelegate(this,
function () { deferred.resolve(allItems); } ),
Function.createDelegate(this,
function (sender, args) { deferred.reject(sender, args); }));
return deferred.promise();
}

NETWORK_ERR: XMLHttpRequest Exception 101 in Android sync mode

I need to send request to server in sync mode, so i set async=false, but i receive always NETWORK_ERR: XMLHttpRequest Exception 101. Here is my code, there i someone that know how can i improve it to fix this issue?
var request = new XMLHttpRequest();
request.open("GET", 'ip-address ', false);
request.onreadystatechange = function () {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
var data = JSON.parse(request.responseText);
var object = "";
var string = "";
var find = false;
window.localStorage.setItem(data.id, JSON.stringify(data));
$.each(data.img, function (i, item) {
if (data.img[i].principal) {
string = data.img[i].path;
}
});
if (string == "") string = data.img[0].path;
var splitt = string.substring(2);
window.localStorage.setItem("img" + data.id, splitt);
if ($("#img" + (l + 1)).attr("src") === 'ip-address' + splitt) {
find = true;
} else {
object='<img id="img'+(l+1)+'" src="ip-address'+splitt+'" name="'+data.id+'"></img>'; if (!trovata) {
if (flag) {
$("#" + (l + 1)).empty();
$("#" + (l + 1)).html(object);
if (l == 0) {
$("#" + (l + 1)).flip({
direction: 'tb'
});
} else {
switch (l % 2) {
case (1):
$("#" + (l + 1)).flip({
direction: 'lr'
});
break;
case (0):
$("# " + (l + 1)).flip({
direction: 'rl'
});
break;
}
}
}
}
}
}
}
request.send();

Categories