When i open using the Google chrome browser this url http://www.site.nl/a/b/c/d/e?niss=f, it first ask for username password:
Manually when i put the username password i get some data.
Now, using jQuery how can i submit that username password? following is not working, always after submit its failing with "401 unauthorized"
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic Username1:password1234"
},
data: '{ "test" }',
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
Please try following code
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
data: '{ "test" }',
beforeSend: function(xhr)
{
xhr.setRequestHeader('Authorization', make_base_auth("Username1", "password1234"));
},
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
function make_base_auth(user,password)
{
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
} // ends
Related
When I want to send data as datatype json it response this error:
SyntaxError: Unexpected token < in JSON at position 0
When I tried to send the data as datatype text, it sends the data to php successfully but my php wont respond.
ajax/js as datatype json:
let form = $("#form");
$("#form").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "POST",
dataType: "json",
data: {
test: 1
},
success: function (r) {
console.log("!!!");
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
});
ajax/js as datatype normal:
let form = $("#form");
$("#form").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "POST",
data: form.serialize(),
success: function (r) {
console.log("!!!");
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
});
php code:
if(isset($_POST["test"])){
echo "<script>console.log('works');</script>";
}
Try this
var ob = {
test: 1
};
$.ajax({
url: "test.php",
method: "POST",
dataType: "json",
contentType: 'application/json',
data:JSON.stringify(ob),
success: function (r) {
console.log("!!!");
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
I am new to web development(Front end) and I have created a form and when I hit submit I want to post the values into the controller "/data" in the backend as a JSON.
So this my code to post the data
$(document).on("click", ".btn btn-warning", function(e) {
var params = {
username: $(".input-group[name=names]").val(),
email: $(".input-group[name=email]").val(),
nicknames: $(".input-group[name=names]").val()
};
$.ajax({
url: back + "/data",
type: "POST",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Please enter the correct credentials: " + errorThrown);
}
});
});
My working
pen
$.ajax({
type: "POST",
url: "http://api.xyz.com/go/login",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
data:{id:'547',password:'password'},
success: function (data, status, jqXHR) {
alert("success");// write success in " "
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
alert('fail' + status.code);
}
});
This is the sample of code I used to get response.
what's wrong here?
The code isn't responding json file.
In javascript how can I write a function that if string is 'Select client' then address and contact number fields should be null or blank. I have already this function that if client name is selected then address and contact number fields are entered automatically using the populator gem of rails.
$('#client_id').change(function(){
$.ajax({
url: "/fetch_client",
type: "POST",
data: "id="+$(this).attr('value'),
dataType: "json",
success: function(data, textStatus, xhr){
$('#client_address').attr('value',data.client_address);
$('#client_contact_number').attr('value',data.client_contact_number);
},
error: function(xhr, textStatus, errorThrown){
}
});
});
Can some one please help me as I am new to javascript?
$('#client_id').change(function(){
if ($(this).val() == "Select client") {
$('#client_address').attr('value', "");
$('#client_contact_number').attr('value', "");
} else {
$.ajax({
url: "/fetch_client",
type: "POST",
data: "id="+$(this).attr('value'),
dataType: "json",
success: function(data, textStatus, xhr){
$('#client_address').attr('value',data.client_address);
$('#client_contact_number').attr('value',data.client_contact_number);
},
error: function(xhr, textStatus, errorThrown){
}
});
}
});
I'm passing two string parameters from a jQuery ajax call to an MVC controller method, expecting a json response back. I can see that the parameters are populated on the client side but the matching parameters on the server side are null.
Here is the javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "List/AddItem",
data: "{ ListID: '1', ItemName: 'test' }",
dataType: "json",
success: function(response) { alert("item added"); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
Here is the controller method:
Function AddItem(ByVal ListID As String, ByVal ItemName As String) As JsonResult
'code removed for brevity
'ListID is nothing and ItemName is nothing upon arrival.
return nothing
End Function
What am I doing wrong?
I tried:
<input id="btnTest" type="button" value="button" />
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
and C#:
[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
return Content(ListID + " " + ItemName);
}
It worked. Remove contentType and set data without double quotes.
If you have trouble with caching ajax you can turn it off:
$.ajaxSetup({cache: false});
You need add -> contentType: "application/json; charset=utf-8",
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
In my case, if I remove the the contentType, I get the Internal Server Error.
This is what I got working after multiple attempts:
var request = $.ajax({
type: 'POST',
url: '/ControllerName/ActionName' ,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
dataType: 'json'
});
request.done(function(msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});
And this is the controller code:
public JsonResult ActionName(int projId, int userId)
{
var obj = new ClassName();
var result = obj.MethodName(projId, userId); // variable used for readability
return Json(result, JsonRequestBehavior.AllowGet);
}
Please note, the case of ASP.NET is little different, we have to apply JSON.stringify() to the data as mentioned in the update of this answer.