1

I'm beginner with Ajax scripts and I'm trying to build a script that displays Mysql queries results when the user clicks on a link. I've thought about using the onClick() function calling an Ajax script. Here is my code :

<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script src="/course/format/topics/ajax.js" type="text/javascript"></script>
<div id="stitre">
    <a href="#" onclick="display()" id="link1" class="link"> Link 1</a>
</div>
<div id="one"> </div>
<div id="stitre">
    <a href="#" onclick="display()" id="link2" class="link"> Link 2</a>
</div>
<div id="one"> </div>

My ajax.js code :

$(document).ready(function() { 
for (var i=1; i<3; i++) {
    var id = document.getElementById("#link" + i);
    function display() {
        $.ajax({
            async: false,
            type: "POST",
            url: "myphp.php",
            data: "id=" + id,
            dataType: "json",
            success: function(msg) {
                if(msg.success) {
            $("#one").html(msg);
                } else {
                    alert("error");
                }
            }
        });
    };
}
}); 

and finaly, myphp.php :

<?php
    require_once('config.php');
    mysql_connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass);
    mysql_select_db($CFG->dbname);
    mysql_query("SET NAMES 'utf8'");

    $id = $_GET['id'];
    if($return = display($id)) {
        echo "success";
    } else {
        echo "error";
    }
    echo json_encode($reply);
?>

For now, nothing is displayed when I click on the links.

1
  • if ($return == display($id)) Commented Feb 21, 2013 at 9:55

4 Answers 4

1

There are a number of issues.

  1. Inline event handlers (onclick="display()") are bad. jQuery provides an easy mechanism for binding event handlers to elements, you should use it.
  2. Your display() function isn't globally scoped, it's only visible inside the scope of the anonymous function passed to .ready(). What this means in practice is when you click on your <a> elements they're trying to execute a function they can't see.
  3. Declaring a function inside a for loop in the way you have will result in a single function using the values of the last iteration.
  4. Your id variable is a DOM element, not a string, so passing it as part of the AJAX call data likely won't pass the value you want.
  5. The id attribute on HTML elements is a unique identifier, so does in fact need to be unique. Having two <div id="one"> elements (or other elements with the same id) isn't valid.

Try the following instead:

$(document).ready(function () {
    $('.link').click(function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "myphp.php",
            data: { id: this.id },
            dataType: "json",
            success: function (msg) {
                if (msg.success) {
                    $("#one").html(msg);
                } else {
                    alert("error");
                }
            }
        });
    });
});

The $(document).ready() ensures that the code doesn't execute until the elements exist (the DOM is ready). The $('.link') selects all elements with the class link on them (your <a> elements). The .click() function adds a click event handler to all of those elements. The e parameter of the anonymous function is passed the jQuery normalised event object as an argument.

The call to e.preventDefault() prevents the default behaviour (following the link), and finally the call to $.ajax() submits the AJAX call. I've removed async: false because it shouldn't be needed. Note that inside the event handler function this refers to the element that triggered the event (so the specific <a> element you clicked on).

I haven't addressed the issues with the HTML, but the list of issues above should give you a basis to correct those for yourself.

I'm not a PHP programmer so I can't really speak to the validity of your server-side code. I'd also recommend installing Firebug if you're using Firefox, otherwise learning how to use your browser's developer tools (hit F12 to open them) since it will tell you about any JavaScript errors that are being thrown.

Sign up to request clarification or add additional context in comments.

3 Comments

I've tryed your code that I understand. I still have no results, even if i only write echo "success"; in myphp.php
@Pierrev.d.Erle The dataType property passed to $.ajax() sets the expected data type of the server response. If you set that to json then your code expects the server to return valid JSON, and jQuery will attempt to parse the response text as JSON. In the case that the response isn't valid JSON - and the string "success" isn't - that parse will fail, and the success callback of the AJAX request won't be executed.
Oh ok, I understand. Thanks for your explanations ! Actualy, I think that Moodle blocks my Ajax code for some reasons I don't know.
0

Replace your success callback:

success: function(msg) {
    $("#one").html(msg);
}

msg.success doesn't exist. Besides you don't need to check for success, you already know it has been successful because the success callback is being called!

1 Comment

The success callback is executed when the AJAX call receives a response successfully, that doesn't automatically imply any server-side validation passed.
0

You have to change PHP script,

//Some thing
$reply['success'] = "Success"; //Create an associative array which is going to be input of json_encode()
if($return = display($id)) {
    $reply['success'] = "Some Success Message";
} else {
    $reply['error'] = " Some Error Message";
}
echo json_encode($reply);

In ajax,

$.ajax({
            ...
            ...
            success: function(msg) {
                if(msg.success) {
            $("#one").html(msg);
                } else {
                    alert("error" + msg.error);
                }
            }
        });

And also check your php version, some lower version will not support json_encode(). Note: The above code is not actual. But i hope that will give you some idea to do your stuff.

Comments

0

Might be this way using with class instead:

<div class="stitre">
   <a href="#" onclick="display(this.id)" id="link1" class="link"> Link 1</a>
</div>
<div class="one"></div>
<div class="stitre">
  <a href="#" onclick="display(this.id)" id="link2" class="link"> Link 2</a>
</div>
<div class="one"></div>

then just use this function this way, no need of doc ready:

function display($id) {
    $.ajax({
        async: false,
        type: "POST",
        url: "myphp.php",
        data: {id:$id},   //<----------send like this
        dataType: "json",
        success: function(msg) {
            if(msg.success) {
                $($id).next(".one").html(msg);
            } else {
                alert("error");
            }
        }
    });
}

Note:

<div id="stitre">
   <a href="#" onclick="display()" id="link1" class="link"> Link 1</a>
</div>
<div id="one"></div>
<div id="stitre">
  <a href="#" onclick="display()" id="link2" class="link"> Link 2</a>
</div>
<div id="one"></div>

Other issue is that you are using same id for multiple dom elements, which is not valid at all. Either you can change id to class instead.

1 Comment

That is an issue, but it's only one of several. A correct jQuery approach to solving this problem wouldn't require that line anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.