I am attempting to get our knockout form to submit to a php script and am getting undefinedIndex errors. I am pretty sure it is the way we are sending the data over in our ajax function.
Here is the ajax:
$.ajax({
url: '/orders/add',
type: 'post',
data: {payload:ko.toJSON(allModel)},
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Here is the PHP (we use laravel)
return json_decode($_POST["payload"]);
Pete is correct. You need to use just one data field. If you want a variable, define it before the $.ajax post
var dataPayload = ko.toJSON(allModel);
$.ajax({
url: '/orders/add',
type: 'post',
data: {payload: dataPayload},
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Related
I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
I have a simple code-form like this:
$.ajax({
url: "http://myurl/test.php",
type: "POST",
dataType: "html",
data: {
action: "login"
},
success: function (data) {
console.log(data)
}
});
When on PHP server page, I try to print $_POST["action"] yet this field is blank. Why does it work fine if I use $.post(url,data,function)?
$.ajax({
url: "http://myurl/test.php",
type: "POST",
dataType: "html",
data: {
method: "login"
},
success: function (data) {
console.log(data);
}
});
login is a php function
You may use method instead of type.
$.ajax({
url: "http://myurl/test.php",
method: "POST", // <-- Use method, not type
dataType: "html",
data: {
action: "login"
},
success: function (data) {
console.log(data)
}
});
Problem is solved.....
There is a problem with the callback on success event...and yesterday I focused my attention only on the request php in the developers tool....when I used Curl (with the right request) all work correctly and I forgot to check client code in success callback....
Never use post method with developers console,it's very easy to lose more time :=)
I am noob at using jquery and ajax. I need to change the form from $.post to $.ajax .
var disqus_config = function() {
this.callbacks.onNewComment = [function(comment) {
$.post("sendnotification", { comment: comment.id, post: $post->id,author:$author->id}, function(result){
alert(result);
});
}];
};
I know I need to end something like here but I am stuck how to use post datas(comment,post,author) inside this function
$.ajax({
url: 'sendnotification',
type: 'POST',
data: 'query=' + query ,
dataType: 'JSON',
async: true,
success: function(data){
process(data)
}
Thanks
Just use the same object literal you did for $.post, eg (gotta assume that's some PHP or something in there)
$.ajax({
url: 'sendnotification',
type: 'POST',
data: { comment: comment.id, post: {$post->id}, author: {$author->id} },
dataType: 'json',
async: true,
success: function(data){
process(data)
}
});
I believe dataType: 'JSON' should be changed to dataType: 'json'
Also, use the same data array as you used in your $.post variant.
$.ajax({
url: 'sendnotification',
type: 'POST',
data: { comment: comment.id, post: $post->id,author:$author->id } ,
dataType: 'json',
async: true,
success: function(data){
process(data)
}
});
i have one AJAX function getting results from php file as bellow
$.ajax({
type: "POST",
url: "GeteT.php",
cache:false,
data:"id="+ encodeURIComponent(1),
dataType:'json',
success: function(json)
{
g_foo = json.foo;
}
});
now i want to use the value of g_foo but i can't i try using console.log but i am facing strange problem. like
if i use function like that
$.ajax({
type: "POST",
url: "GeteT.php",
cache:false,
data:"id="+ encodeURIComponent(1),
dataType:'json',
success: function(json)
{
g_foo = json.foo;
console.log(g_foo);
}
});
now i can see the value return from php file
if now i use function like that
$.ajax({
type: "POST",
url: "GeteT.php",
cache:false,
data:"id="+ encodeURIComponent(1),
dataType:'json',
success: function(json)
{
g_foo = json.foo;
}
});
console.log(g_foo);
now i got error undefined g_foo;
thanks
As ajax is asynchronous, there's no way of making sure that g_foo is available as soon as you call the $.ajax() request, hence it's not available outside that callback.
You could however, specify async:false to that .ajax() call, but it will most likely block the browser, attempting to wait for the request, something I don't think you want to happen.
To use it outside you have two ways:
1)make the call syncronous like this (this is not a best practice as the browser has to wait for the call to continue the flow):
$.ajax({
type: "POST",
url: "GeteT.php",
cache:false,
data:"id="+ encodeURIComponent(1),
dataType:'json',
async: false,
success: function(json)
{
g_foo = json.foo;
}
});
console.log(g_foo);
2) call a function on success and continue the flow from there using whatever data has been returned from the function (this is the best practice)
$.ajax({
type: "POST",
url: "GeteT.php",
cache:false,
data:"id="+ encodeURIComponent(1),
dataType:'json'
success: function(json)
{
g_foo = json.foo;
yourfunction(g_foo);
}
});
function yourfunction(g_foo){
//here g_foo is set
}
All,
I want to send a variable "itemId" via GET to a controller action through AJAX. In the Controller Action, I should be able to retrieve the value using $_GET["itemId"];
Can I send the querystring with "data" tag instead of appending it to the "url"?
I have the following code:
$.ajax({
type: 'GET',
url: "/controller/controlleraction",
data: itemId,
cache: false,
dataType: "html",
success: function(html_input)
{
alert(html_input);
}
});
How can I do this?
data: {itemId: itemId},
$.ajax({
type: 'GET',
url: "/controller/controlleraction",
data: ({itemId: itemId}),<------change it to this
cache: false,
dataType: "html",
success: function(html_input)
{
alert(html_input);
}
});
Make itemId a JavaScript object before making the AJAX request. For example:
var itemId = {'itemId': 1000};
data: {itemId: "you info"},
or
data: "itemId=you info",