2

I am working on a project for a client and they want to be able to update a list of costs dynamically depending on the registrants status as member/non-member or student. So I thought AJAX would have been the best way to do this but I am having trouble with my implementations. Every time I send my object I get a syntax error. I have placed the code below.

JavaScript

function checkMember(){
    var member = document.getElementById("user_mem_id");
    if(member.value == "" || member.value.trim() == ""){
        document.getElementById("testError").innerHTML = "Please enter a membership id<br>";
        document.getElementById("testError").style.color = "red";
    }else{
        var json = { "data":[{"membership_id":member.value}]}
        var xmlHttp = false;
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
        }catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
            }catch (e2) {
                xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
            }
        }

        if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
            xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
        }

        xmlHttp.open("POST","member_check.php",true);
        xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlHttp.send("data=" + json); 

        xmlHttp.onreadystatechange=function(){
            if (xmlHttp.readyState==4 && xmlHttp.status==200){
                    document.getElementById("testError").innerHTML=xmlHttp.responseText;
                    console.log(xmlHttp.responseText);
                    json_last_error;
            };
        };
    }
}

PHP

<?php

    if(isset($_POST["data"]))
    {
        $data = $_POST["data"];
        $res = json_decode($data, true);
        echo $data[membership_id];
    }

The other issue is that when I try and access the membership "cell" of the data array I get illegal off set string. Thus I thought I had declared my original JSON object incorrectly but I appears (as I have viewed many examples on here and else where) that I have declared that correctly.

10
  • 1
    And the error is..? But to clarify, you're sending unescaped json through your request? You do know only jquery or other libraries can do that, right? Commented Feb 27, 2014 at 17:47
  • - Syntax error, malformed JSON Commented Feb 27, 2014 at 17:49
  • You can't send unescaped, raw json through a simple request like that. jQuery is able to because it actually transforms the data into a proper query string. Commented Feb 27, 2014 at 17:51
  • 1
    The problem with your array is that you try to access your json string instead of you decoded array. try $res["data"]["membership_id"]; instead. Commented Feb 27, 2014 at 17:51
  • it might be kinda cheating but jquery could save you some pain: api.jquery.com/jQuery.post Commented Feb 27, 2014 at 17:53

3 Answers 3

2

I think you need to use stringify in order to perform the post successfully.

var json = { "data":[{"membership_id":member.value}]};
json_data = JSON.stringify(json);

then use json_data in your ajax call.

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

3 Comments

This wouldn't be turning it into json; its already json; it'd be turning it into a string.
sorry, yes you're quite right but doesn't he need to do that to post it?
I never said that he didn't. In fact, I already said as much. Also, there's a bit more wrong with the code than that. I'm giving others the chance to correct that in an answer, but if it isn't in a bit(maybe 10 minutes), I'll post my own answer.
1

There are quite a few things wrong with your code. As I stated in my first comment to you, you need to escape your json before you send it in the query string, as json converted to a string, without any special rules applied turns into [object Object], and that isn't valid json, nor is it parsed as such.

To do that, use JSON.stringify(json);. Example:

    function checkMember(){
    var member = document.getElementById("user_mem_id");
    if(member.value == "" || member.value.trim() == ""){
        document.getElementById("testError").innerHTML = "Please enter a membership id<br>";
        document.getElementById("testError").style.color = "red";
    }else{
        var json = { "data":[{"membership_id":member.value}]}
        var xmlHttp = false;
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
        }catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
            }catch (e2) {
                xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
            }
        }

        if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
            xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
        }

        xmlHttp.open("POST","member_check.php",true);
        xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlHttp.send("data=" + JSON.stringify(json));
        //json turned into proper string
        //I should also note, you should url-encode this string if it contains
        //any special characters using encodeURIComponent()

        xmlHttp.onreadystatechange=function(){
            if (xmlHttp.readyState==4 && xmlHttp.status==200){
                    document.getElementById("testError").innerHTML=xmlHttp.responseText;
                    console.log(xmlHttp.responseText);
                    //json_last_error; //Commented this out, as it will
                    //echo an error, causing the script to halt, as it doesn't
                    //exist.
            };
        };
    }
}

Secondly, you send an object whose key 'data' contains an array of objects.. not a simple object:

<?php

if(isset($_POST["data"]))
{
    $data = $_POST["data"];
    $res = json_decode($data, true);
        echo $data[membership_id]; // There are many things wrong here
        //     ^       ^ this is not a constant and likely does not exist.
        //     |- This is still your string, which doesn't work
}
<?php

if(isset($_POST["data"]))
{
    $data = $_POST["data"];
    $res = json_decode($data, true);
        echo $res['data'][0]['membership_id'];
        //      ^   ^     ^      ^
        //      |   |first item  |-string
        //The result|-string
}

Hopefully my comments will be self explanatory.. but in case they are not... $res is your decoded array, 'data' is the first position of that array, 0 is the first position of the array at that position, and 'membership_id' is the item you want to access. You access members as strings, indexes as integers.

2 Comments

Thanks. So in summary I should basically stringfy JSON before sending to PHP, and once in PHP I should use the decoded variable? Any cases in which you would not want to stringfy the JSON
@soccermanstan Cases where you would not want to stringify json, would be using a javascript library like jQuery, which turns it into a query string anyway(unless specific options are set), or one is not using ajax, and needs to modify the object directly. And yes; once in php, use the decoded variable. Otherwise you're treating a string like an array of characters.
1

The basic problem with your code is the ";" terminator when you are defining variable. Check your following line

json = { "data":[{"membership_id":member.value}]}

You haven't put a semicolon at the end. (however it might still work a few times but mostly its an error)

Rather you have written a lot of code too. I would suggest you to use jquery's $.ajax function to simplify your task.

Also in case if you only have membership id in your json data its more easy to create a json object like the one below

var json = {"membership_id" : member.value " } ;

Also you need to send your json data after quoting in string using JSON.stringify(json)

1 Comment

While semi-colons are required in js, this is not why it isn't parsing.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.