WordPress - Get server time using ajax and admin-ajax.php - ajax

I am new to using Ajax to get WordPress data.
The following code should return the server time but the response always is "400 Bad Request".
$.ajax({
url: obj + "?action=wps_get_time&format=U",
success: function(data) {
console.log(data);
}
});
Also tried it as POST and it was the same.
$.ajax({
url: obj,
method: "post",
data: { action: "wps_get_time", format: "U" },
success: function(data) {
console.log(data);
}
});
Any suggestions what's wrong please? Can't figure.
I always thought there are actions I can use always such as wps_get_time, without using a plugin. Am I wrong?
Ist there any easy way to get the server time by ajax?
Thank you all in advance.

The code below will return server time in Indochina and log it to console.
$.ajax({
type: 'GET',
cache: false,
url: location.href,
complete: function (req, textStatus) {
var dateString = req.getResponseHeader('Date');
if (dateString.indexOf('GMT') === -1) {
dateString += ' GMT';
}
var date = new Date(dateString);
console.log(date);
}
});```

Related

Variable loses some value when used in Ajax API Call

I have an issue that causes my variable “tempid” to lose some of its values when put into the second API call. As you can see from my image, if I log the variable to console (console.log(tempid)) it shows just fine. However, as soon as I place it in an API call it has some of the value but not all. Could you please help me by explaining why this would happen?
[console example][1]
$(document).ready(function() {
$.ajax({
url: "/api/Template/GetTemplates?classId=7ac62bd4-8fce-a150-3b40-16a39a61383d",
async:true,
dataType: 'json',
success: function(data) {
$(data).each(function (data) {
if (this.Name === "Name of Template"){
var tempid = this.Id
console.log (tempid)
var tempurl = "/api/V3/Projection/CreateProjectionByTemplate?id=" + tempid + "&createdById=703853d4-ffc4-fce3-3034-0b838d40c385"
$.ajax({
url: tempurl,
async: false,
dataType: 'json',
success: function(data) {
}
});
}
});
}
});
})
[1]: https://i.stack.imgur.com/gyesK.png
I found the answer, the console is just showing a shortened version of the URL and happened to cut off part of the tempid. Thank you

Laravel 5.4 not able to parse FormData javascript object sent using Jquery Ajax

Lately I've been trying to solve an issue with no luck, basically I'm trying to submit a form to the server using AJAX, the form has files, so I'm using the FormData javascript object in JQuery 1.12. The data arrives to the server but in I way I don't know how to format it.
This is my AJAX function:
function saveMenu(id){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_method', 'PUT');
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
$.ajax({
type: 'PUT',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{url('myUrl')}}",
data: formData,
enctype: 'multipart/form-data',
processData: false,
success: function(response) {
toastr.success('Yai! Saved successfully!')
},
error: function(response) {
toastr.error('Oh oh! Something went really wrong!')
},
complete: function() {
$( "#form-wrapper" ).toggleClass( "be-loading-active" )
}
});
}
and when I perform a dd($request->all()); in my controller I get something like this:
array:1 [
"------WebKitFormBoundaryRCIAg1VylATQGx46\r\nContent-Disposition:_form-data;_name" => """
"_token"\r\n
\r\n
jtv4bnn8WQnP3eqmKZV3xWka2YOpnNc1pgrIfk0D\r\n
------WebKitFormBoundaryRCIAg1VylATQGx46\r\n
Content-Disposition: form-data; name="blocks[43][title]"\r\n
\r\n
...
Things I've tried:
Set the HTTP verb to POST. Same result.
Set the AJAX contentType: false, contentType: application/json. Empty response.
Remove enctype: 'multipart/form-data'. Same response.
Any help is appreciated.
This fixed it for me
data: form_data,
contentType: false,
processData: false,
processData: false prevents jQuery from parsing the data and throwing an Illegal Invocation error. JQuery does this when it encounters a file in the form and can not convert it to string (serialize it).
contentType: false prevents ajax sending the content type header. The content type header make Laravel handel the FormData Object as some serialized string.
setting both to false made it work for me.
I hope this helps.
$('#my-form').submit(function(e) {
e.preventDefault();
var api_token = $('meta[name="api-token"]').attr('content');
form_data = new FormData(this);
$.ajax({
type: 'POST',
url: '/api/v1/item/add',
headers: {
Authorization: 'Bearer ' + api_token
},
data: form_data,
contentType: false,
processData: false,
success: function(result,status,xhr) {
console.log(result);
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
also remember to use $request->all(); $request->input() excludes the files
I've been trying to debug that for 2 hours and i found out that method PUT is not working with formData properly.
Try changing
type : "PUT"
into
method : "POST"
Then change your method on your backend from put to post and you'll see the difference.
I used below codes to test it
$("#menu-form").submit(function (){
var fd = new FormData();
fd.append('section', 'general');
fd.append('action', 'previewImg');
fd.append('new_image', $('.new_image')[0].files[0]);
$.ajax({
method : 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token()}}'
},
url: "{{url('upload-now')}}",
data : fd,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
},
});
return false;
});
And in my controller
public function test(Request $request){
dd($request->all());
}
Ill try to research more about this issue.
Laravel 7,
if use method PUT in ajax, you can follow
1. change method method: 'PUT' to method: 'POST'
2. add formdata.append with _method PUT like this example :
$('#updateBtn').click(function(e){
e.preventDefault();
var frm = $('#tambahForm');
frm.trigger("reset");
$('.edit_errorNama_kategori').hide();
$('.edit_errorGambar').hide();
var url = "/pengurus/category/"+$('#edit_id').val();
var formdata = new FormData($("#editForm")[0]);
formdata.append('_method', 'PUT'); //*** here
$.ajax({
method :'POST', //*** here
url : url,
data : formdata,
dataType : 'json',
processData: false,
contentType: false,
success:function(data){
if (data.errors) {
if (data.errors.nama_kategori) {
$('.edit_errorNama_kategori').show();
$('.edit_errorNama_kategori').text(data.errors.nama_kategori);
}
if (data.errors.gambar){
$('.edit_errorGambar').show();
$('.edit_errorGambar').text(data.errors.gambar);
}
}else {
frm.trigger('reset');
$('#editModal').modal('hide');
swal('Success!','Data Updated Successfully','success');
table.ajax.reload(null,false);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Please Reload to read Ajax');
console.log("ERROR : ", e);
}
});
});
its works for me
Finally I gave up trying to make it work and tried a more vanilla approach, I still don't know the reason why the request is formated like that, but the XMLHttpRequest() function works perfectly and the migration is not a big deal.
The equivalent of the function I posted about would be:
function saveMenu(action){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var request = new XMLHttpRequest();
request.open("POST", "{{url('myUrl')}}");
request.send(formData);
request.onload = function(oEvent) {
    if (request.status == 200) {
      toastr.success('Yai! Saved successfully!');
    } else {
      toastr.error('Oh oh! Something went really wrong!');
}
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
  };
}
Bit late, but;
This will solve your problem;
var formData = new FormData(document.getElementById('form'));
console.log(...formData);
var object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
Then you can send this object to the server. This is much more readable and works great.
OR
You can simply send this directly;
JSON.stringify(Object.fromEntries(formData));
This is the newer approach.
And don't give up :-)

Weird object returned from AJAX request

I have this method:
var chineseCurrency = getChinese();
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
});
}
That is what printed when console.log(chineseCurrency);:
I am not able to make chineseCurrency equal to "price", so it would be "6.80071377". How can I do that? Tried chineseCurrency.responseText, nope, chineseCurrency['responseText'], nope. Tried to JSON.parse(chineseCurrency), nope. Nothing works!
Sorry if repeated, couldn't find any answer at Stackoverflow.
How do I return the response from an asynchronous call?
Data that is received as response to asynchronous ajax call cannot be returned from the function that calls $.ajax. What you are returning is XMLHttpRequest object (see http://api.jquery.com/jquery.ajax/) that is far from the desired data.
var chineseCurrency = null;
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny",
success: function(data) {
alert("success1: chineseCurrency=" + chineseCurrency);
chineseCurrency = data.ticker.price;
alert("success2: chineseCurrency=" + chineseCurrency);
// do what you need with chineseCurrency
}
});
}
You are not taking the data from that is returned from the Ajax call. instead you are just returning the ajax object.
Change your code to :
$.ajax(
{
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
data :{},
error : function(data)
{
console.log('error occured when trying to find the from city');
},
success : function(data)
{
console.log(data); //This is what you should return from the function.
}
});

How to send parameters with jquery $.get()

I'm trying to do a jquery GET and i want to send a parameter.
here's my function:
$(function() {
var availableProductNames;
$.get("manageproducts.do?option=1", function(data){
availableProductNames = data.split(",");;
alert(availableProductNames);
$("#nameInput").autocomplete({
source: availableProductNames
});
});
});
This doesn't seem to work; i get a null in my servlet when i use request.getParameter("option");
If i type the link into the browser http://www.myite.com/manageproducts.do?option=1 it works perfectly.
I also tried:
$.get(
"manageproducts.do?",
{option: "1"},
function(data){}
which doesn't work either.
Can you please help me?
EDIT:
also tried
$.ajax({
type: "GET",
url: "manageproducts.do",
data: "option=1",
success: function(msg){
availableProductNames = msg.split(",");
alert(availableProductNames);
$("#nameInput").autocomplete({
source: availableProductNames
});
}
});
Still getting the same result.
If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:
$.get('manageproducts.do', { option: '1' }, function(data) {
...
});
as it would send the same GET request.
Try this:
$.ajax({
type: 'get',
url: 'manageproducts.do',
data: 'option=1',
success: function(data) {
availableProductNames = data.split(",");
alert(availableProductNames);
}
});
Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.
I got this working : -
$.get('api.php', 'client=mikescafe', function(data) {
...
});
It sends via get the string ?client=mikescafe
then collect this variable in api.php, and use it in your mysql statement.
This is what worked for me:
$.get({
method: 'GET',
url: 'api.php',
headers: {
'Content-Type': 'application/json',
},
// query parameters go under "data" as an Object
data: {
client: 'mikescafe'
}
});
will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe
Good Luck.

ajax GET call with node.js / express server

I´m trying to write a small ajax live search for node.js. First of all here is my Clientside code:
$('#words').bind('keyup', function(){
getMatchingWords($('#words').val(), function (data){
console.log('recieved data');
console.log(data);
$('#ajaxresults').show();
});
});
function getMatchingWords(value, callback) {
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
type: 'GET',
dataType: 'json',
success: function(data) { if ( callback ) callback(data); },
error : function() { if ( callback ) callback(null); }
});
}
and here ist my serverside route:
app.get('/matchword/:value', function(req, res) {
console.log(req.params.value);
res.writeHead(200, {'content-type': 'text/json' });
res.write( JSON.stringify({ test : 'test'}) );
res.end('\n');
});
it works but i don´t recieve any data. data in the callback function is always null. so what i am doing wrong? thx for the help
Change
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
to
$.ajax('/matchword' + value + '/', {
What's the URL that you're making the $.ajax() request from? If the page containing that client-side JS wasn't also loaded from 127.0.0.1:3000, the error you're seeing is due to the same-origin requirement on AJAX requests.
hey better late than never...
I was looking at your problem because I am also trying to put a simple live search together with an express.js back end.
first of all I put your url into a local variable. As I don't think that was your problem.
Particularly if your express / node log was showing a 200 response. then the url was fine...
It seems your function wasn't returning data (correct ?) if so try this.
var search_url = "..."// your url
function getMatchingWords(value, callback) {
$.ajax(search_url, {
type: 'GET',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
var returned_data = data;
console.log("returned_data ="+returned_data);//comment out or remove this debug after test
callback(returned_data);
},
error: function( req, status, err ) {
console.log( 'something went wrong', status, err );
}
});
}
you might also need to add / modify your headers subject to the set up...
headers : { Authorization : auth },
type: 'GET',
dataType: 'json',
crossDomain:true,
the auth variable being an encoded auth pair somewhere else in your code (if your web service is requires some kind of auth...

Resources