jQuery Ajax placing random "jQuery111201xxx" into string - javascript

I have made a booking system that utilizes FullCalendar; though that part should be irrelevant. My problem is that upon saving an appointment, a 'notes' field I have created very occasionally has this strange string inserted into it, generally at a random point in the string. Here is the latest example:
Has this been changedjQuery1112010047650896012783_1444929292744 with Rich- finishing sleeve off.bringing deposit in on saturday. told him space isnt secure.
As you can see, there is a totally out of place "jQuery1112010047650896012783_1444929292744" placed in the middle of the note. I can't find anything about this online (mainly because I have no idea what terms I'd use to find it). It must be related to jQuery, considering the string.
I am using jQuery v1.11.2 - obviously the string looks like a long version number.
Why is my ajax request seemingly succeeding, but placing this message in the middle of the sent string? I cannot replicate this issue at all, especially this time since it was another user who managed to cause it.
The function that fetches/prepares/sends data looks like this:
function postForm(content, action, update) {
loader('show');
var popup = content.parent();
var children = content.find(".input");
var data = {}
var elements = [];
data['elements'];
$( children ).each(function() {
var child = {};
child['name'] = $(this).attr('data-name');
if ($(this).is(':checkbox')) {
child['value'] = $(this).is(":checked");
} else {
child['value'] = $(this).val();
}
elements.push(child);
});
data.elements = elements;
data.request = action;
dataPost = JSON.stringify(data);
console.log(dataPost);
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
return false;
}
The note section is just a textarea with the class 'input' (which is looped through and fetched).
I don't think there will be a solution for the exact problem, however, I'm looking for an explanation for the modification of the string. The application works perfectly, except for this very rare case.

Question marks (??) are replaced with a jQuery time stamp. To fix, I had to add jsonp: false to the parameters. Final ajax:
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
jsonp: false,
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});

Related

How to create a secure token for an app?

Im working on a simple app, that allow the user to login. Im using an ajax function pass the values to a PHP file(on a different domain). If the user and the password are correct the page display echo"success" and im using that word to validate and create a random key to allow the user access to a private page.
I was reading that you can also add a header token, it is possible to add that to my current code..
Iam new in developing "app", hope some one can point in the right direction on what is the best way to do this.
var username = $("#username").val();
var password = $("#pass").val();
var dataString = "username="+username+"&pass="+password+"&insert=";
$.ajax({
type: "POST",
url: "url",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {$('#loginButton').val('Connecting...');},
success: function(data)
{
if(data == " success")
{
alert("Success");
returnHash();
}
if(data == " Login failed")
{
alert("There's a problem with username/password!");
$('#loginButton').val('Submit');
}
}
});
function returnHash()
{
letters = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
window.token="";
for(i=0;i<64;i++){
window.token += letters[Math.floor(Math.random()*letters.length)];
}
success();
}
To create a real unique hash, use the current time with an random generated number like in the code below:
var dateForHash = (new Date()).valueOf().toString();
var createRandomNum = Math.random().toString();
crypto.createHash('sha1').update(dateForHash + createRandomNum).digest('hex');
You can also use crypto.randomBytes()- this hash is practical unique but not theoretical.
var hash = crypto.randomBytes(20).toString('hex');
I would recommend the second way for this type of use.

Get select box value to use as a variable

I'm hoping someone can help, I'm a relative newbie to javascript and have the following issue. I have a select box with id "mySelect"
that is populated with the following code -
$(document).ready(function(artists){
$.ajax({
type: "GET",
url: "bookinglist.xml",
dataType: "xml",
success: function(artists_list) {
var select = $('#mySelect');
var artistsArr = [];
$(artists_list).find('vw_ADM_BookingListNull[strArtistName]').each(function(){
var artists = $(this).attr('strArtistName');
if ($.inArray(artists, artistsArr) == -1) {
select.append('<option value="'+artists+'">'+artists+'</option>');
artistsArr.push(artists);
}
});
select.children(":first").text("please make a selection").attr("selected",true);
}
});
});
I need to use the selected value as a variable to insert into another piece of code. How do I make a variable from this?
The variable will be used in place of
'vw_ADM_BookingListNull[strArtistName="James Zabiela"]'
in the following code which populates a table from an xml list.
$(document).ready(function(unavailable){
$.ajax({
type: "GET",
url: "bookinglist.xml",
dataType: "xml",
success:(function(unavail){
$(unavail).find('vw_ADM_BookingListNull[strArtistName="James Zabiela"]').each(function() {
var venue = $(this).attr('strVenueName');
var artist = $(this).attr('strArtistName');
var booking_date = $(this).attr('dteEventDate').substr(0,10); //subtr strips date down
if(!(booking_date >= $nowformat && booking_date <= $advformat)){
$('<tr style="display:none;"></tr>')
}
else {
$('<tr></tr>').html('<th>'+booking_date+'</th><td>'+artist+'</td>').appendTo('#unavail');
}
});
})
});
});
I need to handle the possible event that a value has not been selected and so the value of the select box will be "please make a selection", which is set as the default value.
So I guess I need to wrap some kind of if statement around the code that creates the table, so as to not display anything if nothing has yet been selected.
Any help would be massively appreciated as deadlines are looming.
Thanks again.
You appear to be using jQuery, so from the jQuery Documentation
var dropdownValue = $('#mySelect').val();

ajax success callback not working

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.

How to bring ajax search onkeyup with jquery

My Script to call ajax
<script language="javascript">
function search_func(value)
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
</script>
HTML
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.
For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.
When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.
Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.
I believe I had explained up to reader knowledge.
You should check if the value has changed over time:
var searchRequest = null;
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "sample.php",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
EDIT:
The searchRequest variable was added to prevent multiple unnecessary requests to the server.
Keep hold of the XMLHttpRequest object that $.ajax() returns and then on the next keyup, call .abort(). That should kill the previous ajax request and let you do the new one.
var req = null;
function search_func(value)
{
if (req != null) req.abort();
req = $.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
Try using the jQuery UI autocomplete. Saves you from many low-level coding.
First i will suggest that making a ajax call on every keyup is not good (and this why u run in this problem) .
Second if you want to use keyup then show a loading image after input box to show user its still loading (use loading image like you get on adding comment)
Couple of pointers. Firstly, language is a deprecated attribute of javascript. In HTML(5) you can leave the attribute off, or use type="text/javascript". Secondly, you are using jQuery so why do you have an inline function call when you can do that with jQuery too?
$(function(){
// Document is ready
$("#sample_search").keyup(function()
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg)
{
//Receiving the result of search here
}
});
});
});
I would suggest leaving a little delay between the keyup event and calling an ajax function. What you could do is use setTimeout to check that the user has finished typing before then calling your ajax function.

Preloading the XML via jQuery or Javascript

Hey guys, how can I preload an external XML file in Javascript/jQuery?
This is my XML loader:
jQuery.ajax({
type: "GET",
url: dictionaryList,
dataType: ($.browser.msie) ? "text/xml" : "xml",
success: function(xml) {
var xml2 = load_xml(xml);
var i=0;
$(xml2).find('wordle').each(function(){
$(xml2).find('w').each(function(){
var tmpHold = $(this).text();
if (tmpHold.substring(0, 1) == letter) {
if ($(this).attr('p') == 1) {
wordColor = 'color: #693030';
} else {
wordColor = 'color: #5a5a5a';
}
$('#wordList').append('<li class="w" style="'+wordColor+';">'+$(this).text()+'</li>');
}
});
});
}
});
one possibility, and it sounds like this is what you want, would be to send the response document, (xml) above, to a variable that could be processed on-demand at a later time based on some event.
the stored xml document, and the xml processing function, would live in an object, and the xml processing function would be called based on an event trigger rather than the ajax success event. if this doesn't make sense let me know and i can provide some sample code ...
also, i'd recommend adding an error: function to the ajax call if you don't already have one in place.
I think it's good to keep backend xml generator/retriever script in case if you want to get xml from a different domain.
jQuery.ajax({
type: "GET",
url: XML_GENERATE_BACKEND_URL, // data.xml, /generate/xml etc.
..
..
..
Sultan

Categories