Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.ajax() in node.js?

Tags:

jquery

node.js

Is it possible to use jQuery.ajax() in node.js exactly as it is syntax-wise?

I am trying to share non-UI browser code with node.js. I do not want to replace all the existing function calls with my own wrapper.

Currently when I try it, it would say "No Transport" by default because jQuery does domain detection. If I turn it off by setting jQuery.support.cors it would say XMLHttpRequest.open() not available.

like image 322
voidvector Avatar asked Dec 26 '11 20:12

voidvector


People also ask

Can I use AJAX in node JS?

This can be done by Ajax request, we are sending data to our node server, and it also gives back data in response to our Ajax request. Step 1: Initialize the node modules and create the package. json file using the following command.

What is the difference between NodeJs AJAX and jQuery?

NodeJs is an open-source framework based on JavaScript v8 engine. AJAX is a web development technique for making asynchronous calls to the server. jQuery is a JavaScript library for designing and make some web development tasks easy. It makes it possible to run javascript outside of the browser.

Can I use jQuery in node JS?

js: We can use jQuery in Node. js using the jquery module. Note: Use the 'jquery' module not the 'jQuery' module as the latter is deprecated.


3 Answers

I was able to solve the "No Transport" issue using the XMLHttpRequest module, like this:

var $ = require('jquery'),     XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;  $.support.cors = true; $.ajaxSettings.xhr = function() {     return new XMLHttpRequest(); }; 
like image 107
webXL Avatar answered Sep 21 '22 17:09

webXL


also consider najax, a wrapper for the node request module which allows jquery style syntax for server-side requests

https://github.com/alanclarke/najax

var najax = require('najax');
najax('http://www.google.com', function(html){ console.log(html); });
najax('http://www.google.com', { type:'POST' }, function(html){ console.log(html); });
najax({ url:'http://www.google.com', type:'POST', success: function(html){ console.log(html); });
najax({ url:'http://www.google.com', type:'POST' }).success(function(resp){}).error(function(err){});

najax.get, najax.post, najax.put, najax.delete...
like image 44
alzclarke Avatar answered Sep 19 '22 17:09

alzclarke


If you want the exact jQuery.ajax syntax, try https://github.com/driverdan/node-XMLHttpRequest

But really if you have control over what you're calling ajax for, you should do it with node's http.request or a module like request

like image 40
fent Avatar answered Sep 20 '22 17:09

fent