When I put ":))" in my textarea and send via ajax, it inputs into the database a value like
"jQuery172039628539560362697_1345324072488", how can I stop this? Should I parse my text in some way in javascript first to make it recognize it's text, and not part of the javascript coding?
This is how i get my text
var message = $("textarea.message_thread").val();
var dataString = 'id=' + id + '&message=' + message;
// make ajax call
sending with
$.ajax(
{
type: "POST",
url: "/inbox/instsend",
data: dataString,
dataType: 'json',
success: function(results) {}
}
See the comments under the question; the problem is that what has been submitted in dataString is actually a url-encoded string, and not a JSON-izable or JSON literal variable.
Hence:
dataString = {id: id, message: message};
Will fix this problem, here. jQuery will take that object-initialized variable and encode it for you to JSON.
This is done automatically by jQuery when you're using JSONP for cross-domain AJAX calls. It should be sending this string as the value of the callback parameter.
You need to sanitise the input and escape any control codes - e.g. : and )
Since you are doing POST here. This would work
var dataString = '{'+'id:' + id + 'message:' + message +'}'
Related
I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});
I'm currently using the following ajax function to send ajax queries.
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function (htmltwo) {},
error: function (htmltwo) {}
});
The problem is when i send the text which include the operator "&", the items on the right of the operator is deleted. The following is my dataString.
var dataString = 'id=' + id + '&dateoccur=' + dateoccur + '&timeoc=' +
timeoc + '&hitype=' + hitype + '&hid=' + hid;
So e.g if hid is text containing "EEEE&LLLLL", the items on the right of & will be removed when receiving it on the server side. So on the server end, will receive "EEEE". I assume ajax recognizes this because it's part of the dataString variable. How would I be able to solve this issue ?
You could use encodeURIComponent in Javascript to encode characters such as & and then decode them back at the server.
var hidValue = "EEEE&LLLLL";
var hidValueEncoded = encodeURIComponent(hidValue);
console.log(hidValueEncoded);
I always recommend using an object rather than a string. jQuery will then automatically encode everything properly.
var dataString = {
id: id,
dateoccur: dateoccur,
timeoc: timeoc,
hitype: hitype,
hid: hid
};
It's also much more readable, IMHO.
But if you really want to build the string yourself, use encodeURIComponent as in Nisarg Shah's answer. You should do this for all parameters, unless you're sure they don't contain any special characters.
I have a web application with an HTML form. When I press submit I want to submit the values from this form to a perl script, parseDatabaseData_v2.pl, which get's data from a database and creates a JSON string of that data.
Then, I'd like to visualize this JSON data using a D3 graph.
The following code using jquery ajax works, and returns JSON from the perl script as expected.
var runFromDate = $('#runDateSelectBox1').val();
var runToDate = $('#runDateSelectBox2').val();
var barcode = $('#barcodesSelectBox').val();
var dataString = 'runFromDate='+ runFromDate + '&runToDate=' + runToDate + '&barcode=' + barcode;
// ajax command
$.ajax({
type: 'POST',
url: './cgi-bin/parseDatabaseData_v2.pl',
async: true,
data: dataString,
dataType: "json",
success: function(data) {
console.log("succesfully called script");
}
}); // end of ajax command
In the perl script I use cgi->param('runFromDate'); to get the posted parameters.
However, since I'm visualizing the data using NVD3's lineWithFocusChart I want to call the script using d3.xhr.
When I create the following d3.xhr request the script doesn't work (it get's called, but is unable to get the parameters).
var runFromDate = document.getElementById("runDateSelectBox1").value;
var runToDate = document.getElementById("runDateSelectBox2").value;
var barcode = document.getElementById("barcodesSelectBox").value;
var dataString = 'runFromDate='+ runFromDate + '&runToDate=' + runToDate + '&barcode=' + barcode;
d3.xhr("./cgi-bin/parseDatabaseData_v2.pl")
.header("Content-Type", "application/x-www-form-url-encoded")
.post(dataString,function(error, data){
console.log("succesfully called script");
console.log(data);
});
I've tried various ways of formatting the datastring including formatting it as JSON as explained at the D3 API Reference.
I'd be most grateful if someone was willing to help me with this.
Thanks,
Koen
You have a spurious hyphen between url and encoded!
Change
.header("Content-Type", "application/x-www-form-url-encoded")
to
.header("Content-Type", "application/x-www-form-urlencoded")
Looks like you are not the only one as this other recent answer shows. Seems the offending code has been in the d3.js wiki so I have updated it too.
I have a function which currently passes an account code (derived from a combo box) to the server. Currently it does this by sending the request in the body - I need it to send as a URL parameter. So for example the URL should be:
localhost:1234/myProject/WebApp/Data?accountCode=Full
Assuming full is selected.
My code below works as a request body but my attempts to amend it to submit as a URL request have failed.
accountSelected: function () {
var saccountCode = $("select#accountcombo").val();
var stringAccountCode = saccountCode.toString()
console.log("Account is: " + stringAccountCode);
var myURL = "WebApp/Data";
$.ajax({
url: myURL,
type: "POST",
data: {
"accountCode": stringAccountCode
},
dataType: "text",
})
I have been looking at using $.param but couldn't get anything to work and also read on other questions about using $.get but when I change my code above to a "GET" i get an error
"Request method 'GET' not supported" - the server is expecting a POST request. Any way i could achieve this?
Thanks
Try,
URL: "localhost:1234/myProject/WebApp/Data?accountCode="+stringAccountCode
Appending number of parameters you want example
?accountCode="+stringAccountCode+"&aa="+someAccount
i am trying to make a call to a rest server using jquery/ajax
The rest Server is built in Codeigniter
The ajax function is as follows:
var req = $.ajax({
type: 'GET',
url: "http://localhost/projects/comp6300Server/index.php/resources/token//username/" + email + "/password/" + pword + "/institution/" + inst,
contentType: "application/json; charset=utf-8",
dataType: "json"
})
The request that is generated is as follows:
http://localhost/projects/comp6300Server/index.php/resources/token//username/etambie#yahoo.com/password/qwerty/institution/BCC
The status returned is '400 Bad Request'
I think the problem may be with the email that is passed in "etambie#yahoo.com". Is there a way for the ajax automatically convert the '#' to '%40', or would i have to convert all special characters in my strings manually?
Two things to check out:
The "_" parameter is probably added to that each request is unique. If this isn't done, then the browser may attempt to get the result of calling the URL from it's cache, which is probably not what you want.
On the bad request ... are you sure you want two slashes after the word 'token' in your url?