I have this ajax call
function addNewRemarksToDataBase(argRemark) {
if (argRemark != '') {
// if not blank
$.ajax({
url: '../AutoComplete.asmx/AddNewRemarks',
type: 'POST',
timeout: 2000,
datatype: 'xml',
cache: false,
data: 'argRemarks=' + argRemark,
success: function (response) {
// update the field that is source of remarks
updateRemarksSource();
},
error: function (response) {
}
});
}
};
The method is defined as
[WebMethod]
public void AddNewRemarks(string argRemarks)
{
BAL.BalFactory.Instance.BAL_Comments.SaveRemarks(argRemarks, Globals.BranchID);
}
The problem is if a user enters something like long & elegant or something like smart & beautiful, something that contains &, I only get the first part before &, long (in the first case), smart (in the second one) (also notice the whitespace!)
I read in jquery ajax documentation that one should set processData to false, because it is something used for querystring or something. I added the
processData: false
but I am still getting the term before the &. I don't want to use encodeURIComponent because it will turn the & to amp; (or something like that). What I need is the full value long & elegant, smart & beautiful that will be saved to the database. How can I do this?
EDIT Doing { argRemarks: argRemark } doesn't helps! The function doesn't event gets called. Running it with firebug, and setting breakpoint in error function, I got this
[Exception... "Component does not have requested interface" nsresult: "0x80004002 (NS_NOINTERFACE)" location: "JS frame :: http://localhost:49903/js/jquery-1.8.1.min.js :: .send :: line 2" data: no]"
UPDATE 2 :
Doing
data: 'argRemarks=' + encodeURIComponent(argRemark)
did the trick. But can anyone help me understand how does this works? I thought it would convert & to & but it didn't? The parameter I am receiving to the method now is just what I wanted, long & elegant, smart & beautiful, doesn't encodeURIComponent() converts special characters?
You do need to encode the argRemark. The easiest way to do this is to let jQuery do the job for you:
data: { argRemarks: argRemark }
This is different than data: 'argRemarks=' + argRemark in that by passing in an object, jQuery assumes that it needs to URL-encode the values of the properties on that object -- while if passing in a string, you are expected to have properly encoded it beforehand.
You have to URL-encode the string first:
data: 'argRemarks=' + encodeURIComponent(argRemark)
Related
I am writing a program with php laravel and react.js. But i am very new to these. Anyway in react, i am sending a API request with ajax.
like this:
const sendquery = {
"async": true,
"crossDomain": true,
"url": url,
"method": "POST",
"headers": {
"Authorization": "Bearer " + tkid,
"Accept": "application/json",
"Content-Type": "application/json",
},
"processData": false,
"data": query
};
$.ajax(sendquery).done(function (response) {
console.log('Survey Request :' + response);
});
There are another API requests that are printing nicely when i console.log() because they are in array type. But this must be json. I tested API with Postman everything is OK. But still i have output like this:
Survey Request :[object Object]
Can anyone please help ?
You can try with JSON.stringify(response) but note that it doesn't work with all the types, see JSON.stringify doesn't work with normal Javascript array, for example.
To get json
console.log(JSON.stringify(response));
To get structured JSON
console.log(JSON.stringify(response, undefined, 2));
Another option apart from what #Beris Demiray wrote is to write:
console.log('Survey Request :', response);
Meaning to put the object as a second parameter in the log.
This will give you an object that you'll can open in the debugger.
The reason why this option is better because JSON.stringify doesn't stringify all objects, and this lets you look into all objects.
Use the JSON.parse function like as below:
JSON.parse(response, null, 2)
The best way is pass the display string in the first argument and the object as second
console.log('Survey Request', response);
use console.dir(object:any) like this ->
$.ajax(sendquery).done(function (response) {
console.dir(response);
});
While i acknowledge all answers above, it's important to point out why you seem to be getting that result on the console.
When you do this:
console.log('Survey Request :' + response);
You are basically trying to concatenate a primitive value 'Survey Reguest :' with a complex value response, which is an object. Javascript cannot convert an object response to a primitive value. By simply replacing the + with a , signifies that you are sending the response object as a separate argument. Javascript then logs the arguments separately to the console.
I am trying to get a response from a web service, specifically to add two WFS layers from geoserver to a leaflet web map. The first layer gets added no problem every time, but most of the time, the second layer fails, complaining that the callback function is not defined:
ReferenceError: getJson is not defined
But what is very strange to me is that the second layer will be added, only sometimes. Refreshing the page and trying again will almost always fail.
This is the code making the ajax call:
$(document).ready(function() {
...
$("#add-network-button").on("click", function() {setLocation("Moscow")})
function setLocation(locationName) {
var networkParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'netex:' + locationData[locationName].networkWFSName,
maxFeatures: 99999,
outputFormat: 'text/javascript',
format_options: 'callback: getJson'
};
addWebService(map, WFSURL, networkParameters)
var buildingParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'netex:' + locationData[locationName].buildingWFSName,
maxFeatures: 99999,
outputFormat: 'text/javascript',
format_options: 'callback: getJson'
};
addWebService(map, WFSURL, buildingParameters)
}
And here is the addWebService function:
var addWebService = function(map, WFSURL, WFSParameters) {
var leafletWFSParameters = L.Util.extend(WFSParameters);
console.log(WFSURL + L.Util.getParamString(leafletWFSParameters));
$.ajax({
url: WFSURL + L.Util.getParamString(leafletWFSParameters),
dataType: 'jsonp',
jsonpCallback: 'getJson',
success: handleJson,
cache: false
});
// TODO: add style
function handleJson(data) {
L.geoJson(data, {}).addTo(map);
}
}
You're using jsonp, which means the data you're getting back is not JSON, but javascript code that makes a call to a globally-defined function (which name is defined by jsonpCallback).
jQuery automagically creates a function with that name, performs the network request, and when that function runs, it destroys its own reference from the global scope.
You're performing two calls to addWebService() in quick succession, which trigger two jQuery $.ajax({jsonpCallback: 'getJson'}) calls. The second call is overwriting the globally-defined getJson callback function. When the first jsonp payload is received by your browser, the globally-defined getJson callback is destroyed. When the second jsonp payload is received, it tries to call a globally-defined getJson function, and failing. A classic race condition.
Let me quote jQuery's documentation for the jsonpCallback parameter on $.ajax(), empasis mine:
jsonpCallback
Type: String or Function()
Specify the callback function name for a JSONP request.
This value will be used instead of the random name
automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests.
I suggest you either use other transport format than JSONP, or use different callback names for each request.
I got a very strange problem, I thought this worked before but it doesn't any more. I dont even remember changing anything. I tried with an older jQuery library.
I got an error that says: http://i.imgur.com/H51wG4G.png on row 68: (anonymous function). which refer to row 68:
var jsondata = $.parseJSON(data);
This is my ajax function
I can't get my alert to work either because of this error. this script by the way is for logging in, so if I refresh my website I will be logged in, so that work. I also return my json object good as you can see in the image. {"success":false,"msg":"Fel anv\u00e4ndarnamn eller l\u00f6senord.","redirect":""}
When I got this, I will check in login.success if I got success == true and get the login panel from logged-in.php.
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.success(function(data)
{
var jsondata = $.parseJSON(data);
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});
Thank you.
If the response you have showed in the attached screenshot is something to go by, you have a problem in your PHP script that's generating the JSON response. Make sure that thePHP script that's generating this response (or any other script included in that file) is not using a constant named SITE_TITLE. If any of those PHP files need to use that constant, make sure that that SITE_TILE is defined somewhere and included in those files.
What might have happened is that one of the PHP files involved in the JSON response generation might have changed somehow and started using the SITE_TITLE costant without defining it first, or without including the file that contains that constant.
Or, maybe none of the files involved in the JSON generation have changed, but rather, your error_reporting settings might have changed and now that PHP interpreter is outputting the notice level texts when it sees some undefined constant.
Solving the problem
If the SITE_TITLE constant is undefined, define it.
If the SITE_TITLE constant is defined in some other file, include that file in the PHP script that's generating the response.
Otherwise, and I am not recommending this, set up your error_reporting settings to ignore the Notice.
Your response is not a valid JSON. You see: "unexpected token <".
It means that your response contains an unexpected "<" and it cannot be converted into JSON format.
Put a console.log(data) before converting it into JSON.
You shoud use login.done() , not login.success() :)
Success is used inside the ajax() funciton only! The success object function is deprecated, you can set success only as Ajax() param!
And there is no need to Parse the data because its in Json format already!
jQuery Ajax
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.done(function(data)
{
var jsondata = data;
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});
I'm using Coldfusion8.
I'm receiving an Ajax request with an item number (random 35 charchater string), which I need to write/retrieve to the database.
Problem is, when I'm passing only digits like:
23456
Coldfusion outputs receiving:
23456.0
If the string contains any letters like A12345 it works correctly.
Some code (although this does not show what's not working:
Javascript:
var btn = $(this).find('input'),
putOnRack = btn.jqmData('index'),
form = "",
service = "../services/handler.cfc",
method = "process",
returnformat = "JSON",
targetUrl = "",
formdata = "form_submitted=store_selection&artikelnummer="+putOnRack+"&method="+method+"&returnformat="+returnformat;
// pass to AJAX
ajaxFormSubmit( form, service, formdata, targetUrl, successHandler, "no", "", returnformat, "" );
var ajaxFormSubmit =
function ( form, service, formdata, targetUrl, successHandler, dataHandler, errorHandler, returnformat, type ){
$.ajax({
async: false,
type: type == "" ? "get" : type,
url: service,
data: formdata,
dataType: returnformat,
success: function( objResponse ){},
error: function (jqXHR, XMLHttpRequest, textStatus, errorThrown) {}
In Coldfusion I'm passing this through process, which validates and builds the form server side, then I pass to my database handler which gets a
`LOCAL.form`
object containing all the passed info, so my item number will be in LOCAL.form.artikelnummer
If I output this:
cfdump output="e:\dump.txt" label="catch" var="#LOCAL.form.artikelnummer#">
digit only strings are treated to .0
Question
How can I make sure I end up with varchar and not numbers, when passing a parameter via AJAX to Coldfusion?
You could use NumberFormat(). Example:
NumberFormat('123.0', '99999')// returns '123'
The second parameter is a mask that determines how your number will be displayed.
Use <cfqueryparam ...> within your cfquery block and specify CFSQLType="CF_SQL_INTEGER". This will also prevent SQL injection attacks (p.s. you should never pass raw data from the end user into your database).
Recommended reading:
cfqueryparam (Coldfusion 8)
Secure your ColdFusion application against SQL injection attacks
You can also use the INT function in CF.
int(123.456) <!--- returns 123 --->
INT is like floor (round down) in other languages
See INT()
You'll need to check your result to make sure if it is a number before trying to use either int or numberFormat or you'll get a The value cannot be converted to a number error.
<cfif isNumeric(yourValue)>
<cfset yourValue = int(yourValue)>
</cfif>
Ok, I am semi-new to ExtJS, and I am building a program that has "inputs" that are listed in a grid, and in my DB these inputs can be linked to "symptoms".
I am trying to create a function that will take in the id of the input and grab all of the symptoms from the database that are linked to that symptom, and list them in a field set.
It works fine when I click on an input that is only linked to one symptom, but if the input is linked to more than one symptom, then the error says.. "invalid property id"
This is what I have for my function.
function listSymptoms(inputID){
Ext.Ajax.request({
url: "../../inc/project4.php?list=symptoms",
reader: new (Ext.data.JsonReader)({
root: "symptoms",
inputid: "id"
}),
params: {
inputid: inputID
},
method: "POST",
success: function (f, a){
var jsonData = Ext.util.JSON.decode(f.responseText);
symptomsFieldSet.body.update(jsonData.data.name);
},
failure: function (f,a){
Ext.Msg.alert('There was a problem opening your message.');
}
});
}
I have the inputID for the function being passed in when the user clicks on one of the inputs that are held inside the grid.
I believe that my problem has something to do with this line..
symptomsFieldSet.body.update(jsonData.data.name);
I am just stumped on how to handle this. Do I need to create a data store like I have for grids? Or is there an easier way to do this?
ANY help is appreciated! thanks in advance.
I think you need to rethink the structure of your JSON response object. You can send this in your JSON response to your request. If you are using Ext.util.Ajax calls instad of a form, you'll need to decode this JSON response string using the util method Ext.util.JSON.decode(). Check out the API Documentation
{
success: true,
msg: {text: 'this can be used for error message handling' },
data : [
{id:1,
chiefComplaint: 'head hurts',
symptoms: [
{symptomID: '740.1', text: 'Headache'},
{symptomID: '12352135'. text: 'and so on'}
}
]
]
}