简体   繁体   中英

Using javascript ajax to call php

I am trying to use localization in javascript where localization strings are stored in a php file and get_string() function is used to get the localized values in php. I've written a script called alertpopup.php

$alertmessage = $_POST['msg'];

switch($alertmessage)
{
    case '1':
        $alertmessage = get_string('first');
        break;
    case '2':
        $alertmessage = get_string('second');
        break;
    case 'deletecomment':
        $alertmessage = get_string('random');
        break;  
}

echo json_encode(Array('Message' => $alertmessage));

and a script in javascript to get value from this php script:-

            var answer;
        $.ajax( {
        type: "POST",
        data: "msg=1",
        url: "alertpopup.php",
        success: function(data) {
        var alertmsg = $.parseJSON(data);

            if (alertmsg.Message != null) {
                answer = confirm(alertmsg.Message);
                document.location.reload();
            }

        }
       });
        if(answer) {
                     something
                }
                else{
                    something else
                }

However, I keep getting error:- Uncaught TypeError: Object function (E,F){return new o.fn.init(E,F)} has no method 'parseJSON'

Can someone help me with the issue?

What version of jQuery are you using?

The API doc states that parseJSON was added in v1.4.1. Make sure you're not using an older version.

Try replacing following code

var alertmsg = $.parseJSON(data);

with

var alertmsg = jQuery.parseJSON(data);

EDIT:

OR

School days method :)

var alertmsg = eval(data);

Some people may not agree with this due to some security or some thing like, but give it a try.

since you are getting the result of an ajax call in json... you don't need to parse the json there...

remove the parseJson() and try

UPDATED

var answer;
    $.ajax( {
    type: "POST",
    data: "msg=1",
    dataType: "json",   //added
    url: "alertpopup.php",
    success: function(data) {

        if (data.Message != null) {
              if (confirm(data.Message)) {
                   something
               }else{
                   something else  
               }
            document.location.reload();
        }

    }

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