I want to append one more param at the end of the current url if the ajax call returns successfully. In this context, we can get back the identifier of the object has been persisted into the database, then append this identifier to the url.
The problem is curationNotes of data was lost if the line window.history.pushState({}, null, newHref); is uncommented. It means we cannot get 'params.curationNotes' in controller. The params.curationNotes, which is a map of user provided values on the form, is null when we try to parse it inside the controller.
Below is the snippet I am working on.
$('#btnSave').on("click", function(event) {
if ($('#curationNotesForm')[0].checkValidity()) {
var curationNotes = buildCurationNotesTC();
"use strict";
event.preventDefault();
$.ajax({
dataType: "text",
type: "POST",
url: $.jummp.createLink("curationNotes", "doAddOrUpdate"),
cache: true,
data: {
curationNotes: curationNotes,
model: "${id}"
},
processData: true,
async: true,
beforeSend: function() {
$('#txtStatus').text("The curation notes are being saved. Please wait...");
},
success: function(response) {
var response = JSON.parse(response);
var href = window.location.href;
if (href.indexOf("&cnId=") < 0) {
var newHref = href + "&cnId=" + response['cnId'];
//window.history.pushState({}, null, newHref);
}
$('#txtStatus').text(response['message']);
},
error: function(jqXHR, textStatus, errorThrown) {
// TODO: the error message doesn't show properly
$('#txtStatus').text("Error: ", jqXHR.responseText + textStatus + errorThrown + JSON.stringify(jqXHR));
}
});
} else {
$('#txtStatus').text("Please check required fields and click Save button again...");
}
});
If I comment this line window.history.pushState({}, null, newHref);, the code is working properly.
Notes: this snippet works fine in any web browsers on Linux but cannot work in any web browser of Windows 10. That's actually ridiculous to me.
Have you ever had any experience with this problem?
Related
I have been struggling with a problem for some time. I cannot understand the reason as it happens in a specific case, not with the others.
I have a javascript function that calls a PHP script to upload a file to the server (standard code, have been using it and works perfectly normally).
function upload_picture(fieldID, success, error) {
var folderName;
switch (fieldID) {
case "pop_drawing":
folderName = "pop_dwg";
break;
case "pop_installation":
folderName = "pop_inst";
break;
case "pop_picture":
folderName = "pop_pict";
break;
}
var file_data = $('#' + fieldID).prop('files')[0];
var form_data = new FormData();
form_data.append('folder', folderName);
form_data.append('file', file_data);
$.ajax({
url: 'dbh/upload.php',
dataType: 'text',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
if (response.indexOf("yüklendi") > 0) {
success();
}
},
error: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
error(response);
}
});
}
The function is called from several points in the code and it works OK except one point. At this particular point when it returns it changes the page URL from
http://localhost/pop/#
to
http://localhost/pop/?pop_drawing=&pop_installation=&pop_picture=Compelis-Logo.jpg&pop_need_special_prod=Hay%C4%B1r&pop_need_application=Hay%C4%B1r&pop_order_made=Evet&pop_approval=4&pop_cost_visible=Hay%C4%B1r#
due to a reason I could not understand. This string in the URL line are some parameters on the web page where I press the button to call the function.
The code which call the function is:
function uploadPopPicture () {
if ($('#pop_picture_label').html() !== 'Seçili dosya yok...') {
upload_picture('pop_picture',
function(){
console.log('Görsel yüklendi...');
},
function(error){
console.log('Error:', error);
});
}
}
Same code (obviously with different parameters) is used elsewhere in the program and works OK.
Any ideas what I might be missing.
Many thanks in advance
A button's default behaviour is "submit". If you don't specify any particular behaviour then that's what it will do. So when clicked it will submit your form, regardless of any JavaScript.
Add the attribute type="button" to your button HTML and that will stop it from automatically submitting the form.
This question is a followup of this one. I have created a simple example to check how code is executed within the handler. For the form
<form id="calendar_id" method="post">
Insert date: <input id="date_id" type="text" name="l_date" required>
</form>
I'm trying to retrieve the fields using the following javascript:
function get_form_data_uid($form) {
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function (n, i) {
indexed_array[n['name']] = n['value'];
});
indexed_array['uid'] = 'badbfadbbfi';
return indexed_array;
}
$("#calendar_id").submit(function (e) {
var uri, method, formId, $form, form_data;
// Prevent default submit
e.preventDefault();
e.stopImmediatePropagation();
uri = "/";
method = "POST";
formId = "#calendar_id";
$form = $(formId);
form_data = get_form_data_uid($form);
alert("form_data " + form_data);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
// Setting async to false to give enough time to initialize the local storage with the "token" key
async: false,
dataType: "json",
data: form_data
};
// Make the request
$.ajax(request).done(function (data) { // Handle the response
// Attributes are retrieved as object.attribute_name
console.log("Data from change password from server: " + data);
alert(data.message);
}).fail(function (jqXHR, textStatus, errorThrown) { // Handle failure
console.log(JSON.stringify(jqXHR));
console.log("AJAX error on changing password: " + textStatus + ' : ' + errorThrown);
});
});
However, the code within the handler is not executed (the alert is not shown). Why?
Edit:
The code works jsfiddle but not in firefox.
At least, you are calling a function get_form_data_with_token() which is not defined anywhere in your posted code. Perhaps you meant to call your get_form_data_uid().
Would have just made this a comment, but apparently cannot.
Perhaps I'm not understanding this concept (I'm an AJAX/javascript/Web newbie). I'm using the JQuery autocomplete feature and if I specify a small, limited items flat file (suggestions.xml) the function works fine, but when I use an actual production data file (3 MB) of suggestions the script doesn't work at all.
So I created a web service that generates XML based on the characters in the textbox but it appears this JQuery doesn't run on each keypress, rather only when the page first loads. Obviously, for this function to be of any use it needs to fetch results dynamically as the user types into the input field.
$(document).ready(function () {
var myArr = [];
$.ajax({
type: "GET",
// this line always sends the default text; not what the user is typing
url: "Suggestions.aspx?searchString=" + $("input#txtSearch").val(),
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function (data) {
alert("XML File could not be found");
}
});
function parseXml(xml) {
//find every query value
$(xml).find("result").each(function () {
myArr.push({ url: $(this).attr("url"), label: $(this).attr("name") + ' (' + $(this).attr("type").toLowerCase() + ')' });
});
}
function setupAC() {
$("input#txtSearch").autocomplete({
source: myArr,
minLength: 3,
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.url;
//alert(ui.item.url + " - " + ui.item.label);
}
});
}
});
On the server I expected to see a few requests corresponding to the characters the user is typing into the search box but instead I get a single message:
2013-10-18 22:02:04,588 [11] DEBUG baileysoft.mp3cms.Site - QueryString params: [searchString]:'Search'
My flat file of suggestions appears to be way to large for JQuery to handle and my web service script is never called, except when the page is first loaded.
How do I generate suggestions dynamically as the user is typing in the search box if I can't run back to the database (via my web service) to fetch suggestions as the user is typing?
Ok, I got it all worked out.
On the ASPNET side; I created a form to receive and respond to the AJAX:
Response.ContentType = "application/json";
var term = Request.Form["term"];
var suggestions = GetSuggestions(term); // Database results
if (suggestions.Count < 1)
return;
var serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(suggestions);
On the AJAX side I modified the js function:
$("input#txtSearch").autocomplete({
minLength: 3,
source: function (request, response) {
$.ajax({
url: "Suggestions.aspx",
data: { term: $("input#txtSearch").val() },
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function (obj) {
return {
label: obj.Name,
value: obj.Url
};
}));
}
});
},
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.value;
}
});
Everything is working as expected now.
Hope this helps someone else who might get stuck trying to figure out JQuery stuff for ASPNET.
I want to see if it is possible to log into a third site that uses HTTP authentication. Ideally, the browser will store the credentials. Unfortunately this fails every time. Any help would be much appreciated, I'm using the base64 Jquery plugin, which I've tested to work.
So, two questions:
How can I view the HTTP status code?
Will this ultimately work, in principle?
<script>
$("#login_button").click(function() {
var username = 'myFunUsername';
var password = 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + $.base64.encode(username + ":" + password));
},
success: function(data) { $("#label").text("Logged in, yay!"); }
}).fail(function(){ $("#label").text("It didn't work"); });
});
Thanks!!
var user= 'myFunUsername';
var pwd= 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
crossDomain:true,
username :user,// Keep the variable name different from parameter name to avoid confusion
password:pwd,
xhrFields: { /* YOUR XHR PARAMETERS HERE */}
beforeSend: function(xhr) {
// Set your headers
},
success: function(data, textStatus, xhr) {
alert(xhr.status);// The status code
//Code for success
}
}).fail(function(){
//Fail code here
});
For more details on parameters refer to http://api.jquery.com/jQuery.ajax/
So I have this JavaScript which works fine up to the $.ajax({. Then it just hangs on the loader and nothing happens.
$(function() {
$('.com_submit').click(function() {
var comment = $("#comment").val();
var user_id = $("#user_id").val();
var perma_id = $("#perma_id").val();
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
if(comment=='') {
alert('Please Give Valid Details');
}
else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
alert('This works');
$("ol#update").append(html);
$("ol#update li:first").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
Try replacing:
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
with:
var dataString = { comment: comment, user_id: user_id, perma_id: perma_id };
in order to ensure that the parameters that you are sending to the server are properly encoded. Also make sure that the commentajax.php script that you are calling works fine and it doesn't throw some error in which case the success handler won't be executed and the loader indicator won't be hidden. Actually the best way to hide the loading indicator is to use the complete event, not the success. The complete event is triggered even in the case of an exception.
Also use a javascript debugging tool such as FireBug to see what exactly happens under the covers. It will allow you to see the actual AJAX request and what does the the server respond. It will also tell you if you have javascript errors and so on: you know, the kinda useful stuff when you are doing javascript enabled web development.