AJAX call to server side function in javascript? - javascript

I'm new to AJAX and I'm not too clear about how to use the format of the AJAX call
ex
$.ajax({
type: "POST",
url: "Default.aspx/function",
data: '{ searchBy: id }',
contentType: "application/json; charset=utf-8"
}).success(function (result) {
alert(result);
})
I have a function in the .cs file that should take in a string ID and return a list of all the objects that contain that ID.
I want to call this function in the javascript to check that the returned list is null (therefore the ID does not already exist) before inserting new objects into the database.
How could I go about doing this?
All the examples I see return a string from the server side function.

If you have control of the server-side endpoint, then return whatever you want to indicate no matches - an empty list, null, empty string, etc. Then in the success function check for that.
Note the dataType ajax parameter. That tells the ajax function how to format the response for you to consume. If you are expecting JSON to be returned, use dataType: json and in the success function check for an empty json array result.length === 0. In the case of null or empty string, use a dataType: text and check for result == "null" or result == "". Etc.
If you don't have control of server side then you will need to conform to whatever data it sends back to you. The dataType is still the key though.

[WebMethod]
public static int function(int Id)
{
return Id;
}

If you need use only ajax, the best option is XMLHttpRequest, is Vanilla JS and more fast.
If you decide use ajax with jquery the function is:
$.ajax({
type: "POST",
url: "Default.aspx/function",
data: { searchBy: id },
dataType: 'json',
success: function(result) {
// Do something
}
});

I've never done C#, but your url parameter must be a path to a file (e.g. url: Default.aspx). In your file, you should have the logic to handle the request and call the right function. This function will check the DB, and will print the result.
// inside Default.aspx
// 1- is there a POST parameter? If so, call foo()
public static string foo(string postParam) {
// check DB, process
Print(result)
}
Inside your success callback, check if null:
.then(function(result) {
if (result === null) // do stuff
})

Related

Javascript Convert JSONP data from string to Json object

So i am not sure if i am doing this right.
I want to send markup over HTML (i am trying to create a widget)
Here is the mocky response that i am expecting
so I create a simple jquery get like this
var jsonp_url = "http://www.mocky.io/v2/5c9e901a3000004a00ee98a1?callback=myfunction";
$.ajax({
url: jsonp_url,
type: 'GET',
jsonp: "callback",
contentType: "application/json",
success: function (data) {
$('#example-widget-container').html(data.html)
},
error: function (data) {
alert('woops!'); //or whatever
}
});
then created myFunction
function myfunction(data) {
console.log(data);
}
The problem being that while, i get the response it comes as a string instead of a json or function. i am not sure how to extract the json from this (unless i do string manupulation).
Any pointers would be helpful.
JSFiddle here
P.S. Per https://www.mocky.io/ ,
Jsonp Support - Add
?callback=myfunction to your mocky URL to enable jsonp.
Delete function myfunction.
In the URL, replace callback=myfunction with callback=?.
jQuery will generate a function (your success function) and a function name for you.

Ajax Call in PHP and jQuery

This is my functions.php script containing the following code. The array is encoded into JSON.
functions.php
$final['custom']['main'] = queryCustom($conn, $id);
echo json_encode($final);
My global.js has the following code which makes an AJAX request in jQuery:
$.ajax({
type: "POST",
url: "functions.php", // file to reach Ajax call
dataType: "json",
data: {
action: 'custom',
id: id,
},
success:
function(data) {
setCustom(data.custom);
I want to know what the data contains in function(data)? The setCustom(data.custom), what does this mean here? Can someone provide me an explanation of this please?
data contains an object literal provided by the server side json_encode(). It's been automatically parsed because the data type is set to json.
example:
PHP:
$final['custom']['main'] = queryCustom($conn, $id);
echo json_encode($final);
Will give the following json string (formatted for better understanding):
{
"custom": {
"main":[
{
"symbol":"MAP4",
"official_ID":"112315"
}
]
}
}
The ajax call above is set to datatype json. jQuery knows if this datatype is set, it will automatically parse the string to an object literal.
Javascript:
$.ajax({
type: "POST",
url: "url.php", // file to reach Ajax call
dataType: "json",
success: function(data) {
var main = data.custom;
console.log(main); // returns the child object with "main"
}
});
data contains the initial object, custom is a child object of data and main is a child object of custom.
Success: A function to be called if the request succeeds. The function gets passed three arguments:
Data Returned From The Server
Status
jqXHR (XMLHttpRequest Object)
In your PHP code you've added echo json_encode($final); which will be returned if the request is completed successfully. The response will be passed to data which you can later use in your front-end code.
You can read more about $.ajax() at http://api.jquery.com/jQuery.ajax/

Does $.ajax automatically execute script, if the data returned is javascript?

I use a single JS file to post all my data back to my server, using:
$.ajax({
url: "/backend/post.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(response, status, xhr) // A function to be called if request succeeds
{
var ct = xhr.getResponseHeader("content-type") || "";
if(ct.indexOf("text/plain") > -1){
alert(response);
console.log('text - response');
}
if(ct.indexOf("text/javascript") > -1){
//eval(response);
console.log('javascript - response');
}
}
});
It goes through a whole load of functions on the server side but eventually gets to this one: output_javascript("alert('item added');");
function output_javascript($script)
{
header("content-type:text/javascript");
echo $script;
}
The idea was to have the $.ajax function display text or execute script from the server.
When $.ajax gets the response from output_javascript("alert('item added');"); then it executes the code twice. When I comment out the code to execute in the success function:
$.ajax({
url: "/backend/post.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(response, status, xhr) // A function to be called if request succeeds
{
}
});
Then it only executes the response once. Making me believe that $.ajax executes the code before returning the script in the response variable.
Is this true, or am I not understanding $.ajax correctly ? If I am misunderstanding the $.ajax function, could someone please tell me how to resolve this problem?
Yes, ajax will execute returned JavaScript code. We can see this in the documentation:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
So if you don't specify dataType, jQuery will figure it out from the response. Okay, but what does it do with a "script" value? Further down:
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
And later in the discussion:
If script is specified, $.ajax() will execute the JavaScript that is received from the server before passing it on to the success handler as a string.
All of this is easily found in the documentation by simply searching for the word "JavaScript" on the page.

Ajax do not pass data to method using GET

I have a method which Is accesed using Get
[HttpGet]
[AdminAuthorization]
public ActionResult MakeReservation(ReservationModel m)
{
return PartialView(m);
}
here Ajax Code:
$.ajax({
url: "/DeviceUsage/MakeReservation",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({ data: Ids }),
error: function (data) {
alert("Dodanie nie powiodło się Jeden lub wiecej numerów seryjnych nie są unikalne " + data);
},
success: function (data) {
$('#ProperModal.modal-body').html(data);
$("#Modal").modal('show');
//if (data === "sukces") {
}
});
If I change method description and ajax type to POST function works. How should I modify this code to make it work wiht GET calls?
You need to use JsonRequestBehavior.AllowGet in your controller. For more information you could read this answer on SO
And I think it is good practise to return Json (not PartialView) in your action (for ajax). If you want to return PartialView, you could use this technique
You don't need to explictly tell the HttpGet, By Default, it takes it as HttpGet, but if you put HttpPost attribute, then it does not work on Get Requests.
Same is the case for Jquery ajax, if you don't tell it, its get or post request, it by default makes a get request to server
Remove contentType and dataType: 'json' (this indicates you are returning json, but your code returns a partial view). And Remove JSON.stringify as jQuery accept your JS object directly. Haven't tested it, but it should work.

Jquery ajax success response is string not javascript object

I'm making a jQuery AJAX call to my Rails app (all run on localhost) which is responding with Javascript. The javascript is running because I'm getting the alert. But, I would like to read the my_var variable in the js.erb file. However, when I try to look at the data parameter of the success function it sees the data as a string. So doing data.my_var is undefined.
js.erb file
var my_var = "hi";
alert('this ran');
javascript
$.ajax({
url: "/a/validate?a_id=" + "<%= params[:id] %>",
context: this,
dataType: "script",
data:
{
json_a: JSON.stringify(this.a),
model_to_validate: model,
target_class: target_class,
current_class: current_class
},
success: function (data, textStatus, jqXHR) {
if(!this.orderFormViewed) {
this.orderFormViewed = data.order_block_opened;
}
},
error: function (data) {
console.log("error in ajax validate call");
debugger;
}
})
That's because that's exactly what you told it to do with dataType: "script" - look at the dataType options below. The script is run in it's own context and so you won't see that variable (I believe). You're going to need to communicate differently if you want that set. Or if you just need data send json.
https://api.jquery.com/jQuery.ajax/
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
try to change your dataType to json if you only need to get an object and be sure your server return a json.

Categories