I have a very simple php page with a jquery function
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "test.php",
type: "POST",
data: {
myvar: 1,
},
success: function(result) {
console.log("it works");
}
});
});
</script>
My AJAX function is supposed to be triggered as soon as the document is ready. My test.php just shows my $_POST.
<?php
var_dump($_POST);
die();
Nothing is happening. I should go to test.php and see the var_dump. It works if I have a button and start the AJAX function on the click but not like that... Isn't possible to do so ?
Since on the Back-end part you expect $_POST the best you can do is to use
FormData API
jQuery(function($) {
// Your object
const data = {
myvar: 1,
foo: "foo",
};
// Create FormData from Object
const FD = new FormData();
Object.entries(data).forEach(([prop, val]) => FD.append(prop, val));
$.ajax({
url: "test.php",
type: "POST",
processData: false, // https://api.jquery.com/jquery.ajax/
data: FD, // pass the formData and enjoy with $_POST in PHP
success: function(result) {
console.log("it works", result);
}
});
});
I test your code work with datatype like :
ajax page:
$(document).ready(function() {
$.ajax({
url: "test.php",
type: "POST",
dataType: 'json', //add that line
data: {
myvar: 1,
},
success: function(result) {
console.log(result);
console.log(result['name']);
}
});
});
Related
GET:$.get(..)
POST:$.post()..
What about PUT/DELETE?
You could use the ajax method:
$.ajax({
url: '/script.cgi',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
$.ajax will work.
$.ajax({
url: 'script.php',
type: 'PUT',
success: function(response) {
//...
}
});
We can extend jQuery to make shortcuts for PUT and DELETE:
jQuery.each( [ "put", "delete" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
and now you can use:
$.put('http://stackoverflow.com/posts/22786755/edit', {text:'new text'}, function(result){
console.log(result);
})
copy from here
Seems to be possible with JQuery's ajax function by specifying
type: "put" or
type: "delete"
and is not not supported by all browsers, but most of them.
Check out this question for more info on compatibility:
Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
From here, you can do this:
/* Extend jQuery with functions for PUT and DELETE requests. */
function _ajax_request(url, data, callback, type, method) {
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
}
jQuery.extend({
put: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'PUT');
},
delete_: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'DELETE');
}
});
It's basically just a copy of $.post() with the method parameter adapted.
Here's an updated ajax call for when you are using JSON with jQuery > 1.9:
$.ajax({
url: '/v1/object/3.json',
method: 'DELETE',
contentType: 'application/json',
success: function(result) {
// handle success
},
error: function(request,msg,error) {
// handle failure
}
});
You should be able to use jQuery.ajax :
Load a remote page using an HTTP
request.
And you can specify which method should be used, with the type option :
The type of request to make ("POST" or
"GET"), default is "GET". Note: Other
HTTP request methods, such as PUT and
DELETE, can also be used here, but
they are not supported by all
browsers.
ajax()
look for param type
Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
For brevity:
$.delete = function(url, data, callback, type){
if ( $.isFunction(data) ){
type = type || callback,
callback = data,
data = {}
}
return $.ajax({
url: url,
type: 'DELETE',
success: callback,
data: data,
contentType: type
});
}
You can do it with AJAX !
For PUT method :
$.ajax({
url: 'path.php',
type: 'PUT',
success: function(data) {
//play with data
}
});
For DELETE method :
$.ajax({
url: 'path.php',
type: 'DELETE',
success: function(data) {
//play with data
}
});
If you need to make a $.post work to a Laravel Route::delete or Route::put just add an argument "_method"="delete" or "_method"="put".
$.post("your/uri/here", {"arg1":"value1",...,"_method":"delete"}, function(data){}); ...
Must works for others Frameworks
Note: Tested with Laravel 5.6 and jQuery 3
I've written a jQuery plugin that incorporates the solutions discussed here with cross-browser support:
https://github.com/adjohnson916/jquery-methodOverride
Check it out!
CRUD
this may make more sense
CREATE (POST)Request
function creat() {
$.ajax({
type: "POST",
url: URL,
contentType: "application/json",
data: JSON.stringify(DATA1),
success: function () {
var msg = "create successful";
console.log(msg);
htmlOutput(msg);
},
});
}
READ (GET)Request
// GET EACH ELEMENT (UNORDERED)
function read_all() {
$.ajax({
type: "GET",
url: URL,
success: function (res) {
console.log("success!");
console.log(res);
htmlOutput(res);
},
});
}
// GET EACH ELEMENT BY JSON
function read_one() {
$.ajax({
type: "GET",
url: URL,
success: function (res) {
$.each(res, function (index, element) {
console.log("success");
htmlOutput(element.name);
});
},
});
}
UPDATE (PUT)Request
function updat() {
$.ajax({
type: "PUT",
url: updateURL,
contentType: "application/json",
data: JSON.stringify(DATA2),
success: function () {
var msg = "update successful";
console.log(msg);
htmlOutput(msg);
},
});
}
DELETE (DELETE)Request
function delet() {
$.ajax({
type: "DELETE",
url: deleteURL,
success: function () {
var msg = "delete successful";
console.log(msg);
htmlOutput(msg);
},
});
}
GitHub Reference
You could include in your data hash a key called: _method with value 'delete'.
For example:
data = { id: 1, _method: 'delete' };
url = '/products'
request = $.post(url, data);
request.done(function(res){
alert('Yupi Yei. Your product has been deleted')
});
This will also apply for
I have an API I'm trying to query which requires an initial request to generate the report, it returns a report ID and then in 5 seconds you can pull it from that report ID.
This is what I have which works perfectly and returns the reportID:
$(document).ready(function(){
$("#r2").click(function(){
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result.reportID);
}});
});
});
It returns this:
{"reportID":1876222901}
I'm trying to make it call another ajax call on the back of the first one to collect the report using the reportID as the data varaible "ref". So for example, the second ajax query should have ref: 1876222901
$(document).ready(function(){
$("#r2").click(function(){
$('#loading').show();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result);
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'get',
ref: result.reportID
},
success: function(result){
console.log(result);
}
});
}});
});
});
What I am stuck with is the way I am passing the variable from the result of the first ajax call to the second. It doesn't seem to make it there. How should I send my report ID 1876222901 into my second ajax call please?
You can do this without jQuery just using browser built-in DOM APIs and the fetch API
const r2 = document.getElementById('r2')
const loading = document.getElementById('loading')
const handleAsJson = response => response.json()
const fetchRef = ({reportId}) =>
fetch(`report.php?type=get&ref=${reportId}`)
document.onready = () => {
r2.addEventListener('click', () => {
loading.show();
// you don't have to interpolate here, but in case these
// values are variable...
fetch(`report.php?type=${'queue'}&ref=${2}`)
.then(handleAsJson)
.then(fetchRef)
.then(handleAsJson)
.then(console.log)
})
}
The solution is instead of writing
ref: result.reportID
You have to write it like this
ref: result.reportID.reportID
Because as your said, the first time you use console.log(result.reportID) the result is {"reportID":1876222901}. Which means you have to chaining dot notation twice to be able to reach the value 1876222901 in the next ajax call.
To be clear:
$(document).ready(function(){
$("#r2").click(function(){
$('#loading').show();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result); // as you said, console.log(result.reportID) return {"reportID":1876222901}
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'get',
ref: result.reportID //which means, this line would be => ref: {"reportID":1876222901}
// we will correct it like this => ref: result.reportID.reportID
// then we properly get => ref:1876222901
},
success: function(result){
console.log(result);
}
});
}});
});
});
Hopefully it fixes your error.
I think you can try to make another function for calling after your first ajax like
$(document).ready(function(){
$("#r2").click(function(){
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result.reportID);
callSecondAjax(result.reportID)
}});
});
});
now make that function like
function callSecondAjax(reportId){
// do some stuff
}
I initiate a function after an ajax load(), but the function I intimate calls upon an additional function, which isn't working. How do I initiate ajaxstuff() after load()?
function ajaxstuff(data) {
$.ajax({
type: "POST",
url: "do-it.php",
data: {data},
success: function() {
console.log('I got this far'); // this doesn't work / isn't called
}
});
}
function doit() {
$('form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
console.log('I got this far'); // this works
ajaxstuff(formData);
}
}
$('.popup-loader').click(function() {
$(this).append('<div class="popup"></div>');
$('.popup').load('popup.php', function() {
doit(); // this works
}
});
Check for errors in your console, also, in your AJAX add an async option. set it to FALSE ("Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called"):
function ajaxstuff(data) {
$.ajax({
async: false,
type: "POST",
url: "do-it.php",
data: data,
success: function(result) {
console.log(result); //check in your console for errors
}
});
}
Syntax error in ajaxstuff function. data: {data}, , probably should be data: data,
Also when you're passing a FormData object to $.ajax, you have to specify processData: false and contentType: false
$.ajax({
type: "POST",
url: "do-it.php",
data: data,
processData: false,
contentType: false,
success: function() {
console.log('I got this far');
}
});
I have the following span:
<span class='username'> </span>
to populate this i have to get a value from PHP therefor i use Ajax:
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
}
})
}
Now when i debug i see that the returned data (data) is the correct value but the html between the span tags stay the same.
What am i doing wrong?
Little update
I have tried the following:
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html('RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRr');
}
})
}
getUsername();
Still there is no html between the tags (no text) but when i look at the console the method is completed and has been executed.
Answer to the little update
The error was in my Ajax function i forgot to print the actual response! Thank you for all of your answers, for those of you who are searching for this question here is my Ajax function:
public function ajax_getUsername(){
if ($this->RequestHandler->isAjax())
{
$this->autoLayout = false;
$this->autoRender = false;
$this->layout = 'ajax';
}
print json_encode($this->currentClient['username']);
}
Do note that i am using CakePHP which is why there are some buildin methods. All in all just remember print json_encode($this->currentClient['username']);
The logic flow of your code is not quite correct. An asynchronous function cannot return anything as execution will have moved to the next statement by the time the response is received. Instead, all processing required on the response must be done in the success handler. Try this:
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: { },
success: function(data){
$('.username').html(data); // update the HTML here
}
})
}
getUsername();
Replace with this
success: function(data){
$('.username').text(data);
}
In success method you should use something like this:
$(".username").text(data);
You should set the html in callback
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html(data);
}
})
}
Add a return statement for the function getUsername
var result = "";
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
result = data;
}
})
return result;
}
You can use .load()
Api docs: http://api.jquery.com/load/
In your case:
$('.username').load(myBaseUrl + 'Profiles/ajax_getUsername',
{param1: value1, param2: value2});
I'm doing a (simple) ajax call on window load:
$(window).load(function () {
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
...........
How can I do something, for instance a function or event after this ajax proces is finished. The problem is I have to append something to the data recieved by the ajax call. But I can't append on window load because the data is still being processed.
Put it in the success handler of the ajax call:
$(window).load(function () {
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
// do whatever you want with data
}
});
});
You can call that in the success callback function of Ajax request
success: function(data) {
myFunction() ; // If function
$('#elementID').click() // If you want to trigger a click event
}
You may use the
`$(document).ready`
So it will be similar to this:
$(document).ready(function(){
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
//Your code should be here
After
success: function(data) {
for (var ii = 0; ii < data.length; ii++){
building html here
}
your code here
}
you want to enter in your functions within the success function for the ajax call but before the call is complete.
You could also do
$.ajax({
url: someUrl,
type: "get",
dataType: "",
context: document.body
}).done(function() {
// do whatever when is done
onCompleteFunction();
});
this should execute your request when page is just loaded.
$(function(){
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
// do whatever you want with data
}
});
});
or you can do:
$(function(){
$.ajax({
url: someUrl,
type: "get",
dataType: "",
complete: function(data) {
// do whatever you want with data
}
});
});