简体   繁体   中英

JS Post to Php Issue

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";


?>
$(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.

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" ?> <? 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
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM