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
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);
}
});
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
$.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.
I am making an AJAX request to a PHP controller, by using jQuery ajax, but when trying to get the posted data with PHP the $_POST is empty. Below is the actual function:
function GetSeriesForManufacturer(manuf) {
selectedmanufacturer = manuf;
//Make an AJax Call For Getting Series Of Manufacturer
var series = null;
$.ajax({
type: "POST",
url: url,
data: "{manufacturer:'" + selectedmanufacturer + "'}",
contentType: "application/json", //; charset=utf-8",
dataType: "json",
cache: false,
async: false,
success: function (response) {
//remove loading gif
$(".loading").hide();
//Append Data
AppendSeries($.parseJSON(response.text), selectedmanufacturer);
//Custom Scrollbar Call
$('.MatchingSeries ul').mCustomScrollbar();
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }
});
}
Thanks in advance!
First, you don't need to stringify data. Just send object literal is ok.
data: {manufacturer: selectedmanufacturer},
Second, you don't need this line:
contentType: "application/json",
Let jQuery do the encoding for you:
$.ajax({
type: "POST",
url: url,
data: {
manufacturer: selectedmanufacturer
},
contentType: "application/json", //; charset=utf-8",
dataType: "json",
cache: false,
async: false,
success: function (response) {
...
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }});
For some reason, I'm only able to pass strings containing numbers to my web service when using jquery ajax. This hasn't been an issue so far because I was always just passing IDs to my wcf service. But I'm trying to do something more complex now but I can't figure it out.
In my interface:
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
DataTableOutput GetDataTableOutput(string json);
My webservice:
public DataTableOutput GetDataTableOutput(string json)
{
DataTableOutput x = new DataTableOutput();
x.iTotalDisplayRecords = 9;
x.iTotalRecords = 50;
x.sColumns = "1";
x.sEcho = "1";
x.aaData = null;
return x;
}
Javascript/Jquery:
var x = "1";
$.ajax({
type: "POST",
async: false,
url: "Services/Service1.svc/GetDataTableOutput",
contentType: "application/json; charset=utf-8",
data: x,
dataType: "json",
success: function (msg) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest.status);
//alert(XMLHttpRequest.responseText);
}
});
The above code WORKS perfectly. But when I change x to "t" or even to "{'test':'test'}" I get a Error 400 Bad Request error in Firebug.
Thanks,
John
EDIT:
Making some progress!
data: JSON.stringify("{'test':'test'}"),
Sends the string to my function!
EDIT2:
var jsonAOData = JSON.stringify(aoData);
$.ajax({
type: "POST",
async: false,
url: sSource,
contentType: "application/json; charset=utf-8",
data: "{'Input':" + jsonAOData + "}",
dataType: "json",
success: function (msg) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest.status);
//alert(XMLHttpRequest.responseText);
}
});
EDIT3: I modified the code block I put in EDIT2 up above.
Swapping the " and ' did the trick!
$.ajax({
type: "POST",
async: false,
url: sSource,
contentType: "application/json; charset=utf-8",
data: '{"Input":' + jsonAOData + '}',
dataType: "json",
success: function (msg) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest.status);
//alert(XMLHttpRequest.responseText);
}
});
However, I have a new problem:
public DataTableOutput GetDataTableOutput(DataTableInputOverview Input)
{
The input here is completely null. The values I passed from jsonAOData didn't get assigned to the DataTableInputOverview Input variable. :(
I modified the code block I put in EDIT2 up above.
Swapping the " and ' did the trick!
$.ajax({
type: "POST",
async: false,
url: sSource,
contentType: "application/json; charset=utf-8",
data: '{"Input":' + jsonAOData + '}',
dataType: "json",
success: function (msg) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest.status);
//alert(XMLHttpRequest.responseText);
}
});
This actually worked but I had to fix the format of the object I was sending to GetDataTableOutputOverview