javascript - ajax and jquery, can send data to sever but not receive it -


i'm extremely new ajax/node/jquery please excuse rookie errors.

i'm trying send data node server , update page response using jquery, can send data server unable response. sure success method not firing never receive alert.

so, aim on clicking size_button, contents of size_form sent server. finished item process contents of size_form example sending server , updating response required.

jquery code:

$(document).ready(function() {  $('#size_button').click(function(e){ $('#response').html("searching size...");  var url = "http://localhost:8081/search_size"; // script handle form input. $.ajax({        type: "post",        crossdomain: true,        url: url,        data: $("#size_form").serialize(), // serializes form's elements.        //data: $('#size_form');        success: function(data)        {            alert(data); // show response php script.        $('#response').html(data);        }      }); e.preventdefault(); // avoid execute actual submit of form.  }); }); 

node.js code:

var express = require('express'); var app = express(); var bodyparser = require('body-parser');  // create application/x-www-form-urlencoded parser var urlencodedparser = bodyparser.urlencoded({ extended: false })  app.post('/search_size', urlencodedparser, function(req, res) {   response = {batch_size: req.body.batch_size}; if(req.body.batch_size){     var size = req.body.batch_size;     console.log('looking batches ' +size+ ' items');     res.end(json.stringify(response));   } else {   console.log('recieved request 0 items');   }    //res.end('request recieved...');   res.end(json.stringify(response)); });   var server = app.listen(8081, "localhost", function () {  var host = server.address().address  var port = server.address().port  console.log("server listening @ http://%s:%s", host, port)  }) 

html code:

<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <script src="jquery.js"></script> </head> <body>         <form action='' method='post' id='size_form'>     <p>search size</p>     <input type='text' name="batch_size" id='batchsize'/>     <input type='submit' value='submit'id='size_button' method='post'/>     </form>     <div id='response'></div>    </body> </html> 

so turns out trick cors or cross origin resource sharing, managed fix problem installing , using cors module.

npm install cors --save

server.js code:

import module:

var cors = require('cors')

use module server app variable:

app.use(cors())

for more info: www.npmjs.com/package/cors


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -