2

So, I've been looking for a variety of sources to answer my question the last few day and thus have found nothing that's worked for me. I'll preface this further by saying that in regards to PHP and Javascript I started learning them like a week ago. I also understand that there will likely be better ways to format/write the code I'm about to post so please bear with me! :)

Essentially, I am trying to use a page name play.php in combination with AJAX to echo MYSQL queries back onto the page inside certain page elements.

So the code for main.js which is linked directly to play.php. I've tried about three different way that I've seen in various answers and have not gotten the information I wanted. I either get no response or I get undefined in all of them.

    function selectChar(uname, cname) 
{   
    var data = {
        username : uname,
        charname : cname
    };
    $.ajax({
        data : data,
        type : 'Get',
        url : 'start.php',
        dataType:"json",
        success : function (result) { 
        var data_character = JSON.parse(result);
        var cnamediv = document.getElementById('charactername');
        cnamediv.innerHTML = "";
        cnamediv.innerHTML = data_character[0].name;
        }
    }); 
}

The one above I see most often and the one below I just found earlier today. I get undefined when I attempt to call the array.

function selectChar(uname, cname) 
{
    $.get("start.php?username="+uname+"&charname="+cname).done(function(data_character){
        var cnamediv = document.getElementById('charactername');
        cnamediv.innerHTML = "";
        cnamediv.innerHTML = data_character[0].name;
    });
}

and finally the PHP code that queries the database and echos the data back.

<?php
    $conn = new mysqli($hostname,$username,$dbpassword, $dbname);

    if(!$conn) {
        die('Could not connect: ' . mysql_error());
    }

    $username = $_GET['username'];
    $charname = $_GET['charname'];

    $sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
    $result = mysqli_query($conn,$sql);

    //Send the array back as a JSON object
    echo json_encode($result);
?>

I'm not looking for someone to do work for me but I do require some guidance here. What would be an appropriate way to make this work? Is my code terribly incorrect? Am I missing an aspect of this altogether? Please, I would really seriously appreciate any help someone could give me!

P.S. I did just get done reviewing several other similar questions none of which seemed to help. Either there was never a conclusive outcome as to what worked for them or the solution didn't work when I attempted it.

5
  • Well, for one, your first AJAX method is POST, but you're using $_GET in your PHP code. If you're using POST to send the data, then you should use $_POST to retrieve it. Commented Feb 14, 2017 at 22:10
  • Sorry I had changed it about five minutes ago when I was looking at one of the other threads posts. Commented Feb 14, 2017 at 22:11
  • If you looked at a single tutorial on performing SQL queries in PHP, you would have seen that you have to make a "fetch" call to get the row of results from the database. There are also examples in the mysqli documentation. Commented Feb 14, 2017 at 22:43
  • @Barmar I know how to make fetch calls for database results but it had not worked for me in any way thus far. I tried change a variety of things between both the .php and .js files to bridge the gap. Even after assigning the fetched data to a variable and attempting to json_encode and echo it, I wasn't able to retrieve anything except undefined. Commented Feb 15, 2017 at 0:01
  • @Barmar Tutorials require too much reading, I want to figure it out on my own and unkowningly want to add SQL injection possibility's in my code. Just because I want to share the contents of my database to the outside world. Commented Feb 18, 2017 at 23:32

2 Answers 2

2

try this:
php get post and return json_encode

    if(!$conn) {
        die('Could not connect: ' . mysql_error());
    }

    $username = $_POST['username'];
    $charname = $_POST['charname'];

    $sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
    $result = mysqli_query($conn,$sql);
    $rows = array();
    while($r = mysqli_fetch_assoc($result)) {
     $rows[] = $r;
     }
    //Send the array back as a JSON object
    echo json_encode($rows);
?>

JS ajax response and request

 $.ajax({
        data : data,
        type : 'POST',
        url : 'start.php',
        dataType:"json",
        success : function (result) { 
        console.log(result);
        document.getElementById('charactername').innerHTML = result[0].username;
        }
    }); 
Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately, it did not seem to work in retrieving the data! I'm not sure why it's been unsuccessful :(
in ajax response add console.log(result);, and change this result[0].name; for this result[0].username;
I ended up figuring it out! My other ajax requests worked but for whatever reason that one did not until I changed the url to be more specific. It's weird though, they're all in the same folder and the other ajax requests didn't require a more specific url to work. Your solution did end up working for the request though when I figured the URL problem out! Thanks!
0

Hey Logan the issue may be with how the AJAX request is being sent. Try adding the processData property to your request and setting it to false. It just means the data won't be read as a query string and it is as raw data.

$.ajax({
        data : data,
        type : 'POST',
        url : 'start.php',
        dataType:"json",
        processData: false,
        success : function (result) { 
        console.log(result);
        document.getElementById('charactername').innerHTML = result[0].username;
        }
    }); 

I would also try echo json_encode($_POST) to see if the you get the following response back :

{username: "hello", charname: "hl"}

1 Comment

I ended up figuring it out! My other ajax requests worked but for whatever reason that one did not until I changed the url to be more specific. It's weird though, they're all in the same folder and the other ajax requests didn't require a more specific url to work.Thanks for stopping by anyway! :)

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.