Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 14 of 14
  1. #1
    New Coder
    Join Date
    Oct 2011
    Posts
    15
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Ajax/Jquery with PHP/SQL

    I'm losing my mind trying to understand how ajax/jquery work. My site is based around phpbb, although I don't think that matters much for this. All I want, is for a js function (below)

    Code:
    function RoSave(frm)
    {    
        var strImageData = canvas.toDataURL();  
            
        $.ajax({
            url: "{ROOT_PAHT}easterdraw.php", // place your Ajax URL here
            type: "post",
            data: "image_data="+encodeURIComponent(strImageData)+"&title="+encodeURIComponent(frm.title.value),
            success: function(msg)
            {
                 msg = "Successfully submitted egg!"
                 }
        });
    }
    
    function centerElt(eid,w,h)
    {
        elt=document.getElementById(eid);
        var centerY= Math.floor(Math.round($(window).height()/2));
        var centerX= Math.floor(Math.round($(window).width()/2));
    
        elt.style.top=(centerY-Math.floor(Math.round(h/2))-50)+$(window).scrollTop() + "px";
        elt.style.left=(centerX-Math.floor(Math.round(w/2)))+"px";
    
        // elt.style.display='block';
    	$("#"+eid).show('slow');
    }
    to call and execute a php file (easterdraw.php) when the Save button is clicked.

    PHP Code:
    <?php

    $image 
    = ($_POST['image_data']);
    $title = ($_POST['title']);

    echo 
    $title;
    echo 
    $image;

    $insert_array = array(
    'title' => $title// need this to avoid discrepancies lol
    'username' => $user->data['username'],
    'image' => $image,
    );

    $sql "INSERT INTO " EASTER_CONTEST_TABLE " " $db->sql_build_array('INSERT'$insert_array);
    $db->sql_query($sql);


    ?>
    html
    Code:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
    <input type="button" class="button2" value="Submit" onclick="centerElt('RoSave',400,300);"></p>
    
    <div id="RoSave" class="ajax form" style="width:400px;">
        <form method="post">   
        <fieldset>
            <legend>Drawing information:</legend>
            <div><label>Picture title:</label> <input type="text" name="title" size="30" /></div>    
        </fieldset>
        <p align="center">
        <input type="button" value="Save" onclick="RoSave(this.form);">
        <input type="button" value="Cancel" onclick="$('#RoSave').hide('slow');">
        </p>
        </form>
    </div>
    I *cannot* for the life of me figure out how to get the variable ($title) and image(css canvas) to pass to the php successfully so that it inserts into the sql table correctly. The $user->data['user_id'] variable is global on my site (so it will work no matter what page its on, always defined.). I'd prefer the image be saved as a text blob, but really even file saving is fine at this point.

    I've tried jquery as well
    Code:
    $.post('easterdraw.php', $("#form").serialize();, function(data){
    $("#RoSave").html(data);
    )};
    Anyways if someone could explain to me what I'm doing wrong, or outline (as if for a moron) how jquery or ajax get the variables from the page and pass them to php, I would be very grateful. I've been struggling with this for hours now.
    Last edited by vipaka; 04-05-2012 at 07:58 PM.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    If you use a type "POST" request, the parameters handed over to PHP will be available in the $_POST associative array. So the image_data parameter will be available as $_POST["image_data"] and not $image of course.

  • #3
    New Coder
    Join Date
    Oct 2011
    Posts
    15
    Thanks
    1
    Thanked 0 Times in 0 Posts
    right now the php looks like this (and still doesn't work).

    PHP Code:

    $save 
    = (isset($_POST['save'])) ? true false;

    if (
    $save)
    {
    $image file_get_contents($_POST['image_data'])
    $title = ($_POST['&title']);

    echo 
    $title;
    echo 
    $image;

    $insert_array = array(
    'title' => $title// need this to avoid discrepancies lol
    'username' => $user->data['username'],
    'image' => $image,
    );

    $sql "INSERT INTO " EASTER_CONTEST_TABLE " " $db->sql_build_array('INSERT'$insert_array);
    $db->sql_query($sql);


  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    Where does file_get_contents come from? It is a PHP method to open and read a file from the server(!). But image_data is just a string containing the image data as a data URL (base64 encoded).

    And "save" doesn't seem to be a parameter, neither is "&title". You have three parameters "image_data", "author" and "title". The & ampersand is just a separator and will be automatically removed from PHP when processing the query string.

  • Users who have thanked devnull69 for this post:

    vipaka (04-05-2012)

  • #5
    New Coder
    Join Date
    Oct 2011
    Posts
    15
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I've never tried to write something in Ajax or Jquery before, I'm really just throwing things against the wall to see what sticks at this point.

    Thanks for the variable info, I'll fix them now.

    I think the bigger issue (beyond the misnamed variables) is the fact that *nothing* is happening when I click save. I tried changing the php file to nothing but echo "yes" and it did nothing. Somewhere along the way, the ajax is not meeting up with the file its suppose to be calling (which is in the root directory), or the function isn't coming back true, or something. :S I can't start debugging the code until it actually starts to do what its suppose to do. Right now it does absolutely nothing.

  • #6
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    Ok, so back to the basics:

    1. Any syntax errors (look at the Javascript Console) ?
    2. Did you include jQuery?
    3. You used encodeURIComponent on one parameter, which is correct but you should use it on every parameter (also title and author)
    4. Where did you define the variable canvas?

  • #7
    New Coder
    Join Date
    Oct 2011
    Posts
    15
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by devnull69 View Post
    Ok, so back to the basics:

    1. Any syntax errors (look at the Javascript Console) ?
    2. Did you include jQuery?
    3. You used encodeURIComponent on one parameter, which is correct but you should use it on every parameter (also title and author)
    4. Where did you define the variable canvas?
    1. No syntax errors. In phpbb syntax errors (anywhere in the pathway) make a blank white page, header error messages or log in the php_error.log file, none of which has happened.
    2. I gave up on the Jquery, right now its just using ajax, php and html.
    3. Okay.
    4. var roCanvas={}; is at the top of the js file.

    Edit: I edited the first post with the updated codes. Still not getting any sort of reaction from the script (it doesn't even close the popup or change the url address when I click save). *sigh*
    Last edited by vipaka; 04-05-2012 at 07:36 PM.

  • #8
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    1. I wasn't talking about PHP errors but rather about Javascript errors. Please take a look at your Javascript console
    2. You need jQuery for $.ajax() !
    4. So you defined "roCanvas" but in your code example you use the variable "canvas". Where is it defined?

    New: {ROOT_PAHT} should probably be {ROOT_PATH}

  • #9
    New Coder
    Join Date
    Oct 2011
    Posts
    15
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by devnull69 View Post
    1. I wasn't talking about PHP errors but rather about Javascript errors. Please take a look at your Javascript console
    2. You need jQuery for $.ajax() !
    4. So you defined "roCanvas" but in your code example you use the variable "canvas". Where is it defined?

    New: {ROOT_PAHT} should probably be {ROOT_PATH}
    1. I don't have a js console, but the virtual one on google is finding only type and reference errors (because of missing files).
    2. Ack! Do I need to use $.post jquery or am I totally off track already?
    3. var canvas = document.getElementById('RoCanvas'); a few lines beneath the other one.

  • #10
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    2. I mean, do you have a line like this?
    Code:
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

  • #11
    New Coder
    Join Date
    Oct 2011
    Posts
    15
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Yes.
    Code:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>

  • #12
    New to the CF scene
    Join Date
    Jun 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Are you still struggling with this? See the code from our "Draw a Robot" app (I'm the creator or RoCanvas):

    Code:
    function saveRobot(frm)
    {
        if(!frm.agree.checked)
        {
            alert("Please accept the distribution terms!");
            frm.agree.focus();
            return false;
        }
        
        var strImageData = canvas.toDataURL();  
            
        $.ajax({
            url: "http://re.trotoys.com/drawarobot/",
            type: "post",
            data: "save=1&pic="+encodeURIComponent(strImageData)+"&robot="+frm.robot.value+"&author="+frm.author.value
                +"&url="+frm.url.value,
            success: function(msg)
            {
               window.location="http://re.trotoys.com/robots/id/"+msg+"/new/1/";
            }
        });
    }
    In order to have things working you need to pass this.form when calling the function. Perhaps it's best to visit my app and use View source to figure out how it works. I can share the PHP code too if that can help.

  • #13
    New Coder
    Join Date
    Aug 2008
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    YES please do share PHP!!!

    Sorry to exhume this thread but I have been trying to figure this one out too. How do you define a variable based on the ajax data?

  • #14
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,710
    Thanks
    25
    Thanked 660 Times in 659 Posts
    thighmister, You really should start your own thread. Reviving a 9 month old one will confuse the people that read the first post and try to answer that persons question, skipping yours.

    Most of the time (very close to all the time but I just know someone has an exception to that, they always do) The return (data via jquery, that's what the top post is using) of an ajax call is a php script to write information to the screen, not to send variables to javascript. The return can be written to a <div> that was created to show the data or it can create it's own div. Or it can replace or add to the contents of something already on the page.

    Changing the page without refreshing the page is what ajax is all about.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •