Modify xml using AJAX - ajax

I have the following xml file:
<User>
<Address>123</Address>
<FirstName>John</FirstName>
<SecondName>Smith</FirstName>
</User>
I am trying to get it changed with an AJAX call:
var addressid= = 123;
$.ajax({
type: "GET",
url: url,
headers: {
"Authorization": "Basic " + btoa("username:password"),
},
contentType: "application/xml",
dataType: "xml",
async: true,
crossDomain: true,
success: function(xmlResponse) {
alert("Your user has been edited");
$(xmlResponse).find('User').each(function(){
if($(this).find('Address').text() == addressid) {
$(this).find('FirstName').text("Jenifer");
$(this).find('SecondName').text(secondName);
}
});
}
});
An alert comes, this does not display any errors, but it doesn't get passed on to the system. Which means, if I fetch the data from the server, the old name gets displayed. What am I doing wrong?

Related

Not able Invoke controller action method from Ajax Jquery

I was trying to call mvc core action method from ajax but getting error in console:
Following are the code:
`
$.ajax({
url: LogOutUrl,
type: "POST",
dataType: "html",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
if (window.location.href.indexOf(EserviceLogOutUrl) === -1) {
window.location.href = EserviceLogOutUrl;
}
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
MVC:
MVC: Controller:
public ActionResult Signout()
{
foreach (var cookie in Request.Cookies.Keys)
{
Response.Cookies.Delete(cookie);
}
_httpContextAccessor.HttpContext.Session.Clear();
return new RedirectResult("http://Google.com");//Redirecting to different website in antoher domain.
}
Error in console: I am able to invoke the action methods. but not able redirect the URL.
SEC7123: Request header x-requested-with was not present in the Access-Control-Allow-Headers list.
Add a header to options to satisfy your server:
$.ajax({
url: LogOutUrl,
type: "POST",
dataType: "html",
contentType: "application/json; charset=utf-8",
headers: {'X-Requested-With': 'XMLHttpRequest'},
...

How to get values from data: part in ajax call

$.ajax({
type: "POST",
url: baseUrl + "query?v=21266702",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({ query: text, lang: "en", sessionId: reqIdToken }),
success: function(data) {
xyz
}else{
setResponseForIT(data,"");
}
},
error: function() {
setResponse("Internal Server Error");
}
});
You would assign this stuff to variables before sending the raw data.
You have the data right here :
query: text, lang: "en", sessionId: reqIdToken
you are basically building the JSON on the fly, just process these before by setting them as variables.
Update (for clarification) :
This is creating json for you based on the variables already set etc.
JSON.stringify({ query: text, lang: "en", sessionId: reqIdToken })
This means you have access to 'text' and 'reqIdToken' and hence don't need to look at the 'data' variable that contains the json. Just use reqIdToken if you want to know the sessionId. (e.g. if (reqIdToken == "999") alert();)

django ajax MultiValueDictKeyError

I am receiving this error:
MultiValueDictKeyError at /orders/ajax/add_order_line
"'cart'"
Here is my script
var cart = {
0: {
id: "1",
quantity: 50
}
}
$.ajax({
url: myURL,
type: "post",
data: {cart: cart},
success: function() {},
error: function(){}
});
Meanwhile in my django views, the error was found in this line:
def something(request):
cart = request.POST['cart']
Use get method of multivaluedict
request.POST.get('cart')
Your data is a nested array, so you can't send it using the default default application/x-www-form-urlencoded content type.
You can send the data as json:
$.ajax({
url: myURL,
type: "post",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({cart: cart}),
success: function() {},
error: function(){}
});
Then in your view, you have to load the json string from request.body instead of using request.POST (which is for form-encoded data only).
import json
def my_view(reqest):
data = json.loads(request.body.decode('utf-8'))
cart = data.get('cart')

Youtrack - Apply Command to an Issue requires log in

To apply a command to an issue i'm using this code:
$.ajax({
async: false,
type: 'post',
url: "https://golaservices.myjetbrains.com/youtrack/rest/issue/"+e.target.id+"/execute"+"?command="+target.val(),
cache: "true",
dataType: "html"
});
but that brings up this error
You have no access to this resource. Try to log in.
that's why i tried putting that first bit of code like this:
$.ajax({
async: false,
type: 'post',
url: "https://golaservices.myjetbrains.com/youtrack/rest/user/login?login=xxx&password=123",
cache: "true",
dataType: "html",
success: function(output, status, xhr) {
alert(xhr.getResponseHeader('Set-Cookie'));
}
}).done(function (data) {
console.log("in done");
$.ajax({
async: false,
type: 'post',
url: "https://golaservices.myjetbrains.com/youtrack/rest/issue/"+e.target.id+"/execute"+"?command="+target.val(),
cache: "true",
dataType: "html"
});
console.log("after done");
});
but i still get the same error, any idea how to do this ?
/rest/user/login endpoint has been deprecated for a while already and is not recommended for further use. Try permanent tokens instead, they don't require any preflight login requests to be executed.
$.ajax({
type: "post",
url: "https://golaservices.myjetbrains.com/youtrack/rest/issue/" + e.target.id + "/execute" + "?command=" + target.val(),
dataType: "json"
beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Bearer " + permanentToken); },
});

Ajax post parameters ASP.NET MVC 3

Hello guys i have the next ajax call for login. I serialize the form and send the data to server and return redirect url link. My problem is that my url after post is like
http://localhost:50802/?username=&password= and not http://localhost:50802/Home
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
alert(result.link);
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
It looks like you wrote this $.ajax call in the .click event of a submit button or in the .submit event of a form without canceling the default action by returning false from the callback or by calling preventDefault on the argument. Here's how your code should look like:
$('#id_of_your_form').submit(function(e) {
e.preventdefault(); // <-- That's what I am talking about and what you forgot
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
});
Also async: false,????? You know what this does, do you? That's not AJAX. That's a blocking synchronous call to your webserver during which the client browser would be frozen like during the Ice Age 2 ruining all user experience.
Try returning false at the end of your submit function
$('#id_of_your_form').submit(function(e) {
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
return false; });
Another option would of course be to return the correct redirectlink from the controller instead of overriding it in the java script.

Resources