Please enable / Bitte aktiviere JavaScript!
Veuillez activer / Por favor activa el Javascript![ ? ]
How to make an AJAX request? - Q&A

How to make an AJAX request?

0 like 0 dislike
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 | 93 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: '', method: 'GET', dataType: 'json', success: function (users) { resolve(users.filter(function (user) { return <= 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: '', method: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data) }); }
answered by
Welcome to Bug-code Q&A, where you can ask questions and receive answers from other members of the community.

24.8k questions

46.2k answers


12.3k users

24,788 questions
46,220 answers
12,337 users