8 Replies - 1623 Views - Last Post: 22 September 2013 - 08:39 AM

#1 CONNERtheCODER  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 27-June 13

JQuery .ajax() post to php database query

Posted 20 September 2013 - 06:17 PM

Forgive me if this seems like it's been answered before. I have searched and found many similar discussions but nothing seems to help me fix this problem.

I am not even sure I'm getting into my .change() function, but once I do I'd like to set var id to the row id which corresponds to my database id (which will allow me to run my update query by my primary key). The next thing id like to do is set var field to the column header of the td selected so I know what field from my database to select. The next thing i'd like is my var text to reflect the changed text from the textbox to send to the update query.

Now, I'd like to be able to send that to table_edit_ajax.php as a POST and run my update query. I am just really confused as to how to do all of that. I am very new to ajax and javascript, obviously.


Here is my script:

<script type="text/javascript">
    $(document).ready(function()
    {
        $(".edit_td").click(function()
        {
            $(this).children(".text").hide();
            $(this).children(".editbox").show();

        }).change(function()
            {
                alert("working");
                var id=$(this).parent();
                var field=$("#input_"+ id).val();
                var text=$(this).children(".editbox").val();

                var dataString = 'id='+ id +'&field='+ field +'&text='+ text;
                //$("#first_"+ID).html('<img src="load.gif" />'); // Loading image

                if(input != text)
                {
                    $.ajax({
                    type: "POST",
                    url: "table_edit_ajax.php",
                    data: dataString,
                    cache: false,
                    success: function(html)
                    {
                        $("#first_"+ID).html(first);
                        $("#last_"+ID).html(last);
                    }
                    });
                }
                else
                {
                    alert('Enter something.');
                }
            });

        // Edit input box click action
        $(".editbox").mouseup(function() 
        {
            return false
        });

        // Outside click action
        $(document).mouseup(function()
        {
            $(".editbox").hide();
            $(".text").show();
        });

    });
    </script>


Here is my php code:

public function displayTable($table)
{
  //connect to DB
  $con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

echo "<table id='table' border='1'>";   //start an HTML table

$dbtable = $table;
$fields =array();
$result = mysqli_query($con, "SHOW COLUMNS FROM ".$dbtable);

//fill fields array with fields from table in database
while ($x = mysqli_fetch_assoc($result))
{
    $fields[] = $x['Field'];
}

$fieldsnum = count($fields);    //number of fields in array

//create table header from dbtable fields
foreach ($fields as $f)
{
    echo "<th>".$f."</th>";
}

//create table rows from dbtable rows
$result = mysqli_query($con, "SELECT * FROM ".$dbtable);

while ($row = mysqli_fetch_array($result))
{
    $rowid = $row[$fields[0]];
    echo "<tr class='edit_tr' id='".$rowid."'>";
    foreach ($fields as $f) 
    { 
        echo "<td class='edit_td'><span id='span_".$rowid."' class='text'>".$row[$f]."</span>
        <input type='text' value='".$row[$f]."' class='editbox' id='input_".$rowid."'/> </td>"; 
    }
    $rowid++;
    echo "</tr>";
}

echo "</table>";    //close the HTML table

//close connection
mysqli_close($con);
}


Is This A Good Question/Topic? 0
  • +

Replies To: JQuery .ajax() post to php database query

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4138
  • View blog
  • Posts: 13,073
  • Joined: 08-June 10

Re: JQuery .ajax() post to php database query

Posted 20 September 2013 - 11:08 PM

line #12: id is a jQuery object, not a string/number.

check in your dev tools the contents of your AJAX call.
Was This Post Helpful? 0
  • +
  • -

#3 CONNERtheCODER  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 27-June 13

Re: JQuery .ajax() post to php database query

Posted 21 September 2013 - 07:01 AM

I have changed my script and added this to my php foreach td loop: data-field='".$f.". For some reason my change event isn't triggering. Any ideas? Thanks.

<script type="text/javascript">
		$(document).ready(function()
		{
			$(".edit_td").click(function()
			{
				$(this).children(".text").hide();
				$(this).children(".editbox").show();
				
			}).children('.editbox').change(function()
				{
					alert("working");
					var id=$(this).closest('tr').attr('id');
					var field=$(this).data('field');
					var text=$(this).val();
					
					var dataString = 'id='+ id +'&field='+ field +'&text='+ text;
					//$("#first_"+ID).html('<img src="load.gif" />'); // Loading image
					document.write("<label>" + dataString + "</label>");

					if(input != text)
					{
						$.ajax({
						type: "POST",
						url: "table_edit_ajax.php",
						data: dataString,
						cache: false,
						success: function(html)
						{
							$("#first_"+ID).html(first);
							$("#last_"+ID).html(last);
						}
						});
					}
					else
					{
						alert('Enter something.');
					}
				});

			// Edit input box click action
			$(".editbox").mouseup(function() 
			{
				return false
			});

			// Outside click action
			$(document).mouseup(function()
			{
				$(".editbox").hide();
				$(".text").show();
			});

		});
		</script>

Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4138
  • View blog
  • Posts: 13,073
  • Joined: 08-June 10

Re: JQuery .ajax() post to php database query

Posted 21 September 2013 - 10:01 AM

impossible to tell without the according HTML code.

EDIT: document.write() will certainly kill your script, at latest after the first run.
Was This Post Helpful? 0
  • +
  • -

#5 laytonsdad  Icon User is offline

  • Let it rip!
  • member icon

Reputation: 466
  • View blog
  • Posts: 1,991
  • Joined: 30-April 10

Re: JQuery .ajax() post to php database query

Posted 21 September 2013 - 01:49 PM

Use .append instead of document.write
Was This Post Helpful? 0
  • +
  • -

#6 CONNERtheCODER  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 27-June 13

Re: JQuery .ajax() post to php database query

Posted 21 September 2013 - 02:22 PM

I have fixed mostly everything except for the database update query. For some reason it isn't running properly. Here is my new script:

<script type="text/javascript">
		$(document).ready(function()
		{
			$(".edit_td").click(function()
			{
				$(this).children(".text").hide();
				$(this).children(".editbox").show();
				
			}).children('.editbox').change(function()
				{
					var id=$(this).closest('tr').attr('id');
					var field=$(this).data('field');
					var text=$(this).val();
					var dataString = {id:id, field:field, text:text};
					
					if (field != text)
					{
						$.ajax({
						type: "POST",
						url: "classes/table_edit_ajax.php",
						data: dataString,
						cache: false,
						success: function(html)
						{
							alert("IT WORKED!");
						}
						});
					}
					else
					{
						alert('Enter something.');
					}
				});

			// Edit input box click action
			$(".editbox").mouseup(function() 
			{
				return false
			});

			// Outside click action
			$(document).mouseup(function()
			{
				$(".editbox").hide();
				$(".text").show();
			});

		});
		</script>


and my table_edit_ajax.php file:

<?php
	//connect to DB
	$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
	
	echo 'in table_edit';
		
	$id = mysqli_escape_String($con, $_POST['id']);
	$table = "owners";
	$field = $_POST['field'];
	$text = mysqli_escape_String($con, $_POST['text']);
	$query = "UPDATE owners SET ".$field."='".$text."' WHERE id = '".$id."'";
	mysqli_query($con, $query);
	
	//close connection
	mysqli_close($con);

?>

Was This Post Helpful? 0
  • +
  • -

#7 andrewsw  Icon User is online

  • say what now
  • member icon

Reputation: 6408
  • View blog
  • Posts: 25,887
  • Joined: 12-December 12

Re: JQuery .ajax() post to php database query

Posted 21 September 2013 - 02:52 PM

What does "it isn't running properly" mean? Do you get errors? If so, post them.

Echo (or print_r()) your $query variable in the PHP and then try to run this statement in phpMyAdmin or similar. As you are using Ajax this text will possibly be in the 'html' variable on success.

You could also print out the values of id, field and text in the Javascript (console.log) to check that the correct values are being passed.

This post has been edited by andrewsw: 21 September 2013 - 02:56 PM

Was This Post Helpful? 0
  • +
  • -

#8 CONNERtheCODER  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 27-June 13

Re: JQuery .ajax() post to php database query

Posted 22 September 2013 - 06:32 AM

This is the log from my dataString: Object {id: "1000", field: "cell_phone", text: "8435098471"}

I cannot get logconsole() in my php to work, though. print_r() does nothing, either.
Was This Post Helpful? 0
  • +
  • -

#9 andrewsw  Icon User is online

  • say what now
  • member icon

Reputation: 6408
  • View blog
  • Posts: 25,887
  • Joined: 12-December 12

Re: JQuery .ajax() post to php database query

Posted 22 September 2013 - 08:39 AM

You can't use console.log() in PHP, it's Javascript.

You still haven't explained what it's doing (or not doing).

If the success-message shows then check the content of html, maybe it contains an error message.

And, of course, you have a record with id, 1000 and a field named "cell_phone"..?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1