How to make an AJAX request?

0 like 0 dislike
53 views
Tell me what a mistake this writing the query?
Me even the console errors are pounding, so guess he is not able to...

Here's the js file:
function someFunction ( user_id, post_id ) { $.ajax({ url: "http://my-website/ajax/u-favorite.php", type: "POST", data: { userID: user_id, postID: post_id }, success: success_add_favorite() }); }


PHP file:
if ( isset( $_POST["add_favorite_btn"] ) ) { add_favorite( $_POST["userID"], $_POST["postID"] ); }
asked by | 53 views

2 Answers

0 like 0 dislike
So you add_favorite_btn parameter in the request is not sent.
answered by
0 like 0 dislike
You have the function success_add_favorite() is executed immediately and not in e as a success.
Write it without an immediate call:
success: success_add_favorite

In jQuery after 1.9 version of the parameter type: 'POST' is not present, there is a method: 'POST'

When you use the $function.ajax is better to return it to the Deferred object, so you will know the promise when it is done not only in the callback success or error:
function someFunction(userID, postID) { return $.ajax({...}); } someFunction(a, b).done(function () { //> Request was successful });


You are sending json, so specify it in Content-Type: 'application/json'. Select the type which receives, for example dataType: 'json'

Can write your own functions using deferred promise objects, like so:
getUsers().done(function (users) { console.log(users); }); function promise(callback) { var deferred = $.Deferred(); callback && callback(deferred.resolve, deferred.reject); return deferred; } function getUsers() { return promise(function (resolve, reject) { $.ajax({ url: 'https://jsonplaceholder.typicode.com/users', method: 'GET', dataType: 'json', success: function (users) { resolve(users.filter(function (user) { return user.id <= 5; })); }, error: reject }); }); }


And also the equivalent of the Promise.all:
promiseAll([promise, promise, promise]).done(function () { //> All promises completed successfully }); promiseAll function(promises) { return $.when.apply(null, promises); }


Here's an example of correct feature post request:
addPost({ title: 'foo', body: 'bar', userId: 1 }).done(function (response) { console.log(response); //> {title: "foo", body: "bar", userId: 1, id: 101} }); function addPost(data) { return $.ajax({ url: 'https://jsonplaceholder.typicode.com/posts', method: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data) }); }
answered by

Related questions

0 like 0 dislike
0 answers
asked Oct 8, 2018 by frontend-front
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
24,509 questions
45,932 answers
0 comments
345 users