0

I am stuck on this one. I think this should be simple but I am have no success. I am just trying to post a variable in a href tag over to a php function on a separate file. I am trying to test my JS with an alert box on success. I am getting no alert box, 'Success alert box test!'.

Any idea what I am doing wrong? I am guessing it is the problem is with my success function.

Thanks again! Much appreciated.

HTML:

<a href="#" class="target" data-review="1">Click here</a>

JS:

$(document).ready(function() {
    $( ".target" ).click(function(e) {
        e.preventDefault();
        var review_id = this.data('review');
        $.ajax({
            url : "vote_add.php",
            type : "POST",
            dataType: "json",  
            data : {
                reviewId : review_id
            },
            success : function(data) {
                if (data == 'success')  {
                    alert('Success alert box test!');
                } else {
                    alert(data);    
                }
            }
        });
    });
});

Vote_add.php:

<?php

echo "success";


?>
aebabis
  • 3,657
  • 3
  • 22
  • 40
Jason
  • 79
  • 1
  • 7
  • Use your browser's developer console to see what the requests return. There's also a function to handle failures using jQuery's ajax, along with success one, use it to debug your app. To cut down on your troubles, you didn't return proper json from php. – N.B. Feb 11 '14 at 22:13
  • 3
    `Vote_add.php != vote_add.php` – display-name-is-missing Feb 11 '14 at 22:13
  • I'm not sure if this is the problem, but I don't think you're using `data` correctly. I think you want `this.attr('data-review')`. If that doesn't fix it, could you tell us if you're getting any errors in the JS console? – aebabis Feb 11 '14 at 22:16
  • Going to try these suggestions out. Thanks – Jason Feb 11 '14 at 22:18
  • 1
    `'success'` is no `json`. – GolezTrol Feb 11 '14 at 22:24
  • @acbabis I think `data('review')` is just as fine. http://api.jquery.com/data/ – display-name-is-missing Feb 11 '14 at 22:37
  • @DanielLisik Neat, I didn't know that worked. I would still advise against it. The documentation says: "The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)." That means the OP might introduce bugs if he tries to change the attribute value later. – aebabis Feb 11 '14 at 22:54
  • Try getting rid of that `dataType` property. – StackSlave Feb 11 '14 at 23:42
  • Thanks guys, tried your suggestions. It looks like my code is all wrong and not correct JSON. Do you know if "onclick" and "$.post" functions not work with Jquery 10? – Jason Feb 11 '14 at 23:49
  • Scrapped the code. Thanks again. Starting fresh. – Jason Feb 12 '14 at 02:06

2 Answers2

0
$(document).ready(function() {
$( ".target" ).click(function(e) {
        e.preventDefault();

        var review_id = $(this).data('review');
        $.ajax({
            url : "/echo/json/",
            type : "POST",
            dataType: "json",  
            data : {
                reviewId : review_id
            },
            success : function(data, status) {
                if (status == 'success')  {
                    alert('Success alert box test!');
                } else {
                    alert(data);    
                }
            }

            });

});
});

You have error on line 5th this should be $(this) - the jQuery object and also you should use 2nd parameter for success which is status.

For easier debug just use FireBug or DevTools.

0

A couple things to improve your code and to my experience, what I believe you should change:

  • $(this).data('review') should work.

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

  • Your callback functions on the $.ajax() options you provide should be like .done(), .fail(), .always() and .then()

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8.

  • Depending on the way your web service was setup, you should be able to set a breakpoint in your server code (I assume you have access to it or built it yourself?). If not possible, check the data object returned by .fail() with Firebug or any other developer toolbar and look for xhr.statusText or xhr[0].statusText (again, depending on how your web service returns it.)

Success: Type: Function( PlainObject data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.

jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method.

  • If you are using "POST" to the web service you might want to send it as a JSON string. JSON.stringify() can assist with that. Some browser support is lacking but you can fix this with a polyfill

  • Last but not least, if you are sending json you want to expect json back. <? echo "success" ?> isn't going to cut it I'm afraid. Check out this post to see what I mean.

The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses jQuery.parseJSON() when the browser supports it; otherwise it uses a Function constructor. Malformed JSON data will throw a parse error (see json.org for more information). JSON data is convenient for communicating structured data in a way that is concise and easy for JavaScript to parse. If the fetched data file exists on a remote server, specify the jsonp type instead.

.

$(function () {
    var ajaxOptions = {
        url: "vote_add.php",
        type: "POST",
        dataType: "json"
    };

    $(".target").click(function (e) {
        var options,
            optionsData = {
                reviewId: $(this).data('review')
        };

        e.preventDefault();

        //options = $.extend({}, ajaxOptions, { data: optionsData });
        options = $.extend({}, ajaxOptions, { data: JSON.stringify(optionsData) });

        $.ajax(options).done(function (data) {
            // success so use your data object
            // are you looking for a property?
            var myProperty = 'myProperty';
            if (data.hasOwnProperty(myProperty)){
                var myValue = data[myProperty];
            }
        }).fail(function (xhr) {
            // do something on error
            console.warn("myscript.js > " + xhr.statusText + ' ' + xhr.status);
        }).always(function() {
            // do something no matter what happens
        });
    });
});
Community
  • 1
  • 1
Tim Vermaelen
  • 6,869
  • 1
  • 25
  • 39