Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Getting Error When Trying to Pass JSON PHP to JS with Ajax!

    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 505
    Answer it

    Hey, I'm in desperate need. I have made a JSON object with PHP named userAuth and I am trying to pass it to a JS file with Ajax, here is my PHP code (auth.php):

     

    $userAuth->access = 1;
    
    json_encode($userAuth);

     

    Here is my JS (auth.js):

     

    const xmlhttp = new XMLHttpRequest();
    
    xmlhttp.onreadystatechange = function() {
    
    if (this.readyState == 4 && this.status == 200) {
    
    const userAuth = JSON.parse(this.responseText);
    
    console.log(userAuth.access);
    
    }
    
    };
    
    xmlhttp.open("GET", "auth.php", true);
    
    xmlhttp.send();

     

    Yet I am being thrown this error in console:

     

    Uncaught SyntaxError: Unexpected token A in JSON at position 0
        at JSON.parse (<anonymous>)
        at XMLHttpRequest.xmlhttp.onreadystatechange (auth.js:4)
    xmlhttp.onreadystatechange @ auth.js:4
    XMLHttpRequest.send (async)
    (anonymous) @ auth.js:10

     

    I have no idea why it's not working, I've followed a tutorial and I'm desperate! 

     

    Thanks in advance & Regards,

    flugs

 1 Answer(s)

  • hi,
    first please check the response using log in js file:- console.log(responseText).
    check the json from php is correct and get same in js file.
    can use JSON.stringify(responseText) on basis of consoled result or JSON.parse(JSON.stringify(responseText))
    thanks
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: