Insert a variable into data attribute, AJAX

11,770

You seem to have specified an absolute url for your AJAX script:

http://10.0.0.8:9000/demo

It seems that you are violating the same origin policy that is built into browsers and which is preventing you from sending cross domain AJAX calls.

So this AJAX call cannot work unless this HTML page is hosted on http://10.0.0.8:9000.

Also you seem to have a trailing , which results into invalid javascript. I'd also use the JSON.stringify method to properly serialize the request to JSON:

function postForm() {
    var ret = $('#test').val();
    $.ajax({
        type: 'POST',
        url: '/demo',
        data: JSON.stringify({ name: ret }),
        contentType: 'application/json; charset=utf-8',
        success: function(result) {
            // do something iwth the result of the AJAX call here
        }
    });
}

Notice how I have used a relative path here (url: '/demo') to ensure that the same origin policy is not violated and ensure that the AJAX request is sent to the same domain.

If on the other hand you need to send cross domain AJAX calls then you have a couple of possibilities including using JSONP (limited only to GET requests) or CORS both involving modifications to your server side API. If you have no control over your server side API and cannot modify it, you will have to write a server side script on your domain (the one hosting your HTML page containing this javascript) that will act as a bridge/proxy between your domain and the remote domain and then send the AJAX request to your server side script.

Share:
11,770
Gidon
Author by

Gidon

Updated on July 01, 2022

Comments

  • Gidon
    Gidon almost 2 years

    I'm pretty sure this has a simple solution that I'm missing. I have the following ajax script.

    <!DOCTYPE html>
    <html>
    <head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    function postForm() {
        var ret = $('#test').val();
        $.ajax({
                type: 'POST',
                url: 'http://10.0.0.8:9000/demo',
                data: '{"name" : '+ret'}',
                contentType: "application/json; charset=utf-8",
    
            })
        }
    
    </script>
    </head>
    <body>
        <form id="ajaxForm" onSubmit="postForm(); return false;"  method="post"> 
            <input id="test" type="text" name="name" value="Hello JSON" /> 
            <input type="submit" value="Submit JSON" /> 
        </form>
    
    </body>
    </html>
    

    I've pulled the value of the input with id='test' put it in the ret variable. Then I'm trying to insert it into the data attribute and send it via ajax. I've tried various assortments of quotes and nothing seems to be working.... what am I doing wrong?

    Thanks ahead