I want to send JSON data in XDR using the POST method. I'm able to send JSON data, however the problem is . (DOT) symbols are converted into _ (underscores). Here is the code:
if ($.browser.msie && window.XDomainRequest) {
var xdr = new XDomainRequest();
xdr.open("POST",Path);
xdr.send(JSON.stringify(data) + '&ie=1');
xdr.onerror = function() {
alert('in error');
};
xdr.onload = function() {
alert(xdr.responseText);
}
} else {
jQuery.ajax({
type: "POST",
url: Path,
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
success: function(msg) {
alert(msg);
}
});
}
May be your server side scripting is wrong..
this code seems to be correct....
Related
I'm new to JavaScript and jQuery. I'm currenly having the following code in my javascript file, however it doesn't seem to be working. I'm using this from prototype.js :
var url = '/sip/TnsViewScreenResponse';
var myAjax = new Ajax.Request(url, {
method: "post",
headers:{
'X-Requested-By': 'XMLHttpRequest'
},
parameters: "tin=" + tin,
success: function transResult(response) {
document.getElementById('tinVersionsOf_' + tin).innerHTML
= response.responseText;
document.getElementById('ajax_loading_img').style.display
= 'none';
document.getElementById('tinVersionsOf_' + tin).style.display =
'block';
},
error: function transResult(response) {
document.getElementById('ajax_loading_img').style.display = 'none';
alert('Failure: Problem in fetching the Data');
},
}
);
return false;
This seems to be conflicting with the other jQuery files being used in the file, so I want to convert this to plain JavaScript or jQuery. I have tried the below but it doesn't seem to be working. How can I make this right ?
var url = '/sip/TnsViewScreenResponse';
var myAjax = $.ajax({
type: "POST",
url: url,
data: tin,
success: function transResult(response) {
$('#tinVersionsOf_' + tin).html(response.responseText);
$('ajax_loading_img').css("display","none") ;
$('#tinVersionsOf_' + tin).css("display","block");
},
error: function transResult(response) {
$('#ajax_loading_img').hide();
alert('Failure: Problem in fetching the Data');
},
}
});
The above code is getting skipped while being parsed in the browser, which I had checked with inspect element option in Google chrome.
Try This
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/sip/TnsViewScreenResponse",
data: JSON.stringify({ mydata: tin }),//where tin is ur data
success: function (result) {
//include your stuff
},
error:function(error)
{
// include your stuff
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Below is the relevant code (JS+jQuery on the client side):
function getuser(username, password) {
var user = new Object();
user.constructor();
user.username = username;
user.password = password;
//....
$("#a1").click(function () {
var u = getuser($("#username").val(), $("#password").val());
if (u == false) {
alert("error");
} else {
//....
}
});
}
The question is how to send var u to a session on the server side?
You can use ajax to accomplish this. Something like:
$.ajax({
url: "/Controller/Action/",
data: {
u: u
},
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
//handle response from server
}
});
Then have a controller action to receive the data:
[HttpPost]
public ActionResult Action(string u)
{
try
{
//do work
}
catch (Exception ex)
{
//handle exceptions
}
}
Note that /controller/action will be specific to where youre posting the data to in your project
See the documentation
For example:
If you just want to do a simple post the following may suit your needs:
var user = getUser(username, password);
$.post(yourserverurl, user, function(response){console.log("iam a response from the server")});
As the documentation says:
This is a shorthand to the equivalent Ajax function:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So In your example:
$.ajax({
type: "POST",
url: "/mycontroller/myaction",
data: {user: getUser(username, password)},
success: function(responseFromServer){//handleResponseHere},
error: function(xhr){//handleyourerrorsHere}
dataType: yourdatatype
});
I've tried almost all suggestions but it doesn't work. My ids are working properly in the JavaScript function when I alert my array using arr['id']. However, when I try $_POST['id'] on a different PHP file (I've used AJAX and specified the URL) is gives me an error.
scriptfile.php:
<script>
function detailsmodal(cid, pid) {
var arr = { "cid": cid, "pid": pid };
jQuery.ajax({
url: '/frontend/include/detailsmodal.php',
method: "post",
data: arr,
success: function(data) {
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function() {
alert("something went wrong");
}
});
}
detailsmodal.php
<?php
echo $_POST['cid'];
?>
You could try sending your data as json like this:
$.ajax({
type: "POST",
url: "/frontend/include/detailsmodal.php",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ cid: cid, pid: pid }),
success: function(data) {
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function() {
alert("something went wrong");
}
});
For the decoding you could use javascript JSON.parse
var myObj = JSON.parse(this.responseText);
or
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["cid"];
I want to use jQuery POST method to call an xsjs service that does some modifications in Database.My xsaccess file prevents xsrf, so I need to handle it in my controller method.
Below is my controller code-
var obj= {};
obj.name= "John";
obj.age= "abc#xyz.com";
obj.loc= "Minnesota";
jQuery.ajax({
url: "serviceTest.xsjs",
type: "GET",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(responseToken, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
console.log("token = " +token);
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
},
success : function(response) {
// will be called once the xsjs file sends a
response
console.log(response);
},
error : function(e) {
// will be called in case of any errors:
var errMsg = e.responseText
console.log(e);
}
});
},
And here is my xsjs code-
var csrf_token = $.request.headers.get("X-CSRF-Token");
if(csrf_token === "Fetch") {
var content = $.request.body.asString();
var args = $.parseJSON(content);
var xsName= args.name;
var xsemail= args.email;
var xsLoc= args.loc;
//then execute DML statement by passing these 3 parameters as arguments.
catch (error) {
$.response.setBody(content);
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
I am not able to do the update and getting error Err 500 - Internal server Error.
Any suggestions would be extremely helpful
Edit:
If I forgot the token then I got a 403 Access denied error ("CSRF token validation failed") and not a 500 internal. So I think something is wrong with your services
You can add your X-CSRF-Token as header of your POST request with setup your ajax requests before your fire your POST.
$.ajaxSetup({
headers: {
'X-CSRF-Token': token
}
});
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
Otherwise add it to each POST request.
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
headers: {
'X-CSRF-Token': token
},
beforeSend: function(xhr) {
Your way with using beforeSend event should work too.
Im making a simple AJAX request for an XML file, but instead of text/xml
it returns it as application/xml, which apperently gives me some issues.
Code:
method.getXmlData = function () {
return jQuery.ajax({
type: "GET",
url: "testxml.xml?id=" + theQuizId,
async: false,
dataType: "xml"
});
};
theQuizData = method.getXmlData();
Anyone had a similar problem?
Note: can't include js-fiddle because of CORS.
I got it working by changing the code to the following:
method.getXmlData = function () {
var outerData;
jQuery.ajax({
type: "GET",
url: "testxml.xml?id=" + theQuizId,
async: false,
cache: false,
dataType: "xml",
success : function(data) {
outerData = data;
}
});
return outerData;
};
theQuizData = method.getXmlData();
On Which Browser you are trying the above code?
Try using dataType : "text/xml" instead of xml . IE handles XML data type differntly (As ActiveXObject other browsers like chrome handle them as Simple XML).
For Example.
$.ajax({
url : "myUrl",
type : 'post',
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
var xml;
if (typeof data == 'string') {
/*This is for IE*/
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
}
}