ajax GET call with node.js / express server - ajax

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...

Related

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

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);
}
});```

Ajax call always triggers fail handler even though success is returned by the server

The following JavaScript always triggers the fail handler even though the return value is success from the server side:
$.ajax(payload)
.done(function(data, statusText, jqxhr) {
document.getElementById('myModal').innerHTML = "<p>Record Saved ... </p>";
modal.style.display = "block";
refresh_html_page(document.getElementById("sheetname").value);
})
.fail(function(jqxhr, statusText, errorThrown) {
document.getElementById('myModal').innerHTML = "<p>Record Not Saved ... </p>";
modal.style.display = "block";
refresh_html_page(document.getElementById("sheetname").value);
})
.always(function () {
// Re-enable the inputs
$inputs.prop("disabled", false);
});
Returned JSON string:
[{"result":"success","row":11}]
Any thoughts?
Good news. I was able to crack it. The solution was as follows:
Set up a call back function in the payload
Have a dummy action in the newly created call back function
Prefixed the call back function name in the server side while creating the jasonp response
Client side:
function handleJSONPResponse(data, status, request) {
console.log('response', data);
}
// Fire off the request to /form.php
var payload = {
crossDomain: true,
url: "https://script.google.com/macros/s/XXXXXXXXXXXXXXXXX/exec",
method: "POST",
dataType: "jsonp",
data: serializedData,
jsonpCallback: 'handleJSONPResponse'
};
Server Side (e is the payload sent from client):
return ContentService
.createTextOutput(e.parameters.callback + '(' + JSON.stringify({"result":"success", "row": nextRow})+ ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
It was wonderful solving the problem. Thank you very much for your kind inputs and encouragement. Much appreciated.

Return bool value from Ajax

I am calling the below function from my .aspx page and all I want to check whether this function returned true or false. I tried many things but I get undefined as result.
I am calling function using below code
if (IsIncetiveAllowed())
{
sCondition = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']";
xmlNode = $(XMLCombos).xpath(sCondition)[0];
XMLCombos.firstChild.removeChild(xmlNode);
}
function IsIncetiveAllowed() {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "pp060.aspx/CheckIncentiveAllowed",
data: "{'typeOfApplication': '" + m_TypeOfMortgage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d)
return true;
else
return false;
},
error: function (response) {
MessageBox.Show("An error occurred checking IsIncetiveAllowed method.", null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
}
Please Help!
If you pass a callback to the IsIncetiveAllowed function, you can make it execute your code with the result of the ajax call after it has been made.
IsIncetiveAllowed(function(is_allowed) {
if (is_allowed) {
sCondition = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']";
xmlNode = $(XMLCombos).xpath(sCondition)[0];
XMLCombos.firstChild.removeChild(xmlNode);
}
else {
// Not allowed
}
});
function IsIncetiveAllowed(callback) {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "pp060.aspx/CheckIncentiveAllowed",
data: "{'typeOfApplication': '" + m_TypeOfMortgage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d)
callback(true);
else
callback(false);
},
error: function (response) {
MessageBox.Show("An error occurred checking IsIncetiveAllowed method.", null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
}
First off, you never want to use synchronous Ajax. Synchronous Ajax blocks the browser, the user interface freezes and the user cannot scroll, click or do or anything while synchronous requests load. Don't use them.
Second, it's useful to break up your operation into separate parts. What you have here is
A part can post JSON to the server
This is the most re-usable part, it works the same for all JSON you want to post to any URL.
A part that knows how to talk to to a specific endpoint on the server
This is the second most reusable part, it can send any data to a specific endpoint.
A part that uses this endpoint
This is the least reusable part, it can send specific data to a specific endpoint.
It makes sense to have a separate function for each part. jQuery supports this easily, because all Ajax methods return promises, and promises can be given from function to function.
Part 1, as a jQuery extension for maximum re-usability:
$.fn.postJSON = function(url, data) {
return $.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data)
});
};
Part 2, as a stand-alone function. Note that I am matching the remote API endpoint name. You can write more functions like this to wrap other API endpoints.
function checkIncentiveAllowed(typeOfApp) {
return $.postJSON("pp060.aspx/CheckIncentiveAllowed", {
typeOfApplication: typeOfApp
}).fail(function (err) {
MessageBox.Show("An error occurred in checkIncentiveAllowed method.",
null, MessageBoxButtons.OK, MessageBoxIcon.Error);
console.log(err);
});
}
Part 3, to be used inside an event handler for example:
checkIncentiveAllowed(m_TypeOfMortgage).done(function (response) {
var path = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']",
xmlNode = $(XMLCombos).xpath(path)[0];
if (response.d && xmlNode) {
xmlNode.parentNode.removeChild(xmlNode);
} else {
// not allowed
}
});
Well this is happening because the ajax call is asynchronous. You can put your code present in if block to the ajax callback function to implement your logic

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 :-)

Express res.jsonp returns two callback names to Safari Extension AJAX call

I'm building an extension in Safari, using Express.js on the back end. I make an AJAX call to the server, and the server responds with what appears to be a double callback name:
jQuery191026131771644577384_1364321159940 && jQuery191026131771644577384_1364321159940([
{
"foo": "bar"
}
]);
Here's the AJAX:
$.ajax({
type : "GET",
data : { 'something': 'something more'},
url : "http://localhost:3001/api/login/?callback=?",
dataType: 'jsonp',
success: function(data, text){
console.log(data)
},
error: function (request, status, error) {
console.log("ERROR: " + status + error );
}
});
...and here's the Express.js:
app.get('/api/login', function(req, res){
res.jsonp([{'foo':'bar'}]);
});
The browser is reporting a parse error, likely because of the double callback stamp above.
Clues?
It's not a double callback, it's the same as doing func && func(), it just makes sure that the function exists before calling it, so avoid throwing an exception.
Hector has it right in the comments: Try removing callback=? from the URL

Resources