[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

jQuery Ajax to POST or GET string in order to MySQL using PHP?

Posted on 2011-10-27
8
Medium Priority
?
295 Views
Last Modified: 2012-05-12
Hi,
I have a function below that uses the jQuery sortable plugin.
The alert from the function below displays the following --> "92","67",66","23"
which means icon with id 92 is in position 1, icon with id 67 is in position 2 etc...

I am trying to work out what should go in the ajax section of the code to POST or GET  "92","67",66","23" to the same page so I can then update myMySQL table with the new position of the icons.

Also, is there a way of testing to see if AXAJ is working?

Thanks in advance for your help.
 
 
<script>
 $(function() {
		$("#sortable3" ).sortable({'update': function(event, ui){
		  var position='';
		  
		  for (i=0; i < this.children.length; i++) {
			if (position.length) {
			  position += ',';
			}
			position += '"' + this.children[i].icon_id + '"' ;
		  }
				
				 alert(position);
				 $.ajax({
					 type: "GET",
					 url: "arrange_icons2.php?update_icons=A&",
					 data: position,
					 dataType: "text"
				 }); 
		}
	  }); 

    });
</script>    
<?php    
   
    if(isset($_POST['position'])){ 
		$position = $_POST['position'];
		$pos_array = explode(",",$position);

		foreach($pos_array as $key => $value){
			$query_icons = "UPDATE icons SET icon_position = '".$key."' WHERE id = '".$value."'";
			mysql_query($query_icons, $conn_data) or die(mysql_error());
		}
}

?>

Open in new window

0
Comment
Question by:sabecs
  • 4
  • 4
8 Comments
 
LVL 3

Accepted Solution

by:
varontron earned 2000 total points
ID: 37043035
The 'data' key in the object you pass to 'ajax' must have an object, or a string in object-syntax, as it's value.  So give the values "position" a key like below (note lines 1 and 9:)
var position='position:[';
		  
		  for (i=0; i < this.children.length; i++) {
			if (position.length) {
			  position += ',';
			}
			position += '"' + this.children[i].icon_id + '"' ;
		  }
				position += "]"
				 alert(position);
				 $.ajax({
					 type: "GET",
					 url: "arrange_icons2.php?update_icons=A&",
					 data: position,
					 dataType: "text"
				 }); 

Open in new window


Here is the relevent part of the jquery docs:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

Here is the doc link:  http://api.jquery.com/jQuery.ajax/
0
 

Author Comment

by:sabecs
ID: 37043502
                       
Thanks varontron for your help,
I had problems with the quotes and brackets which I have now removed so position is now numbers seperated by commas ->  76,56,76,89,44
 
It works using page reload with -->   self.location = "arrange_icons2.php?group_name=A&position="+position;
   
But how do I get it to work with ajax below?
   
             $.ajax({
             type: "GET",
             url: "arrange_icons2.php?update_icons=A&",
             data: position,
             dataType: "text"
                             });


If have also updated my PHP code to:

if(isset($_GET['position'])){
$position = $_GET['position'];
$pos_array = explode(",",$position);
 $group_name = $_GET['group_name'];
            
foreach($pos_array as $key => $value){
      $update_icons = "UPDATE icons2 SET group_name = '".$group_name."', icon_position = '".$key."' WHERE id = '".$value."';";
      //echo $query_icons."</br>";
      mysql_query($update_icons, $conn_data) or die(mysql_error());
      }
 $insertGoTo = "arrange_icons2.php";
  header(sprintf("Location: %s", $insertGoTo));
}
0
 
LVL 3

Expert Comment

by:varontron
ID: 37043890
ok, so basically what happens is that jquery converts the value associated to the data key (an object) into a url param string.  That's why it has to be an object with key:value pairs. So, I actually left off the curly brackets.  That's the problem.

First, note line 1 and 9 again:
var position='{position:[';
		  
		  for (i=0; i < this.children.length; i++) {
			if (position.length) {
			  position += ',';
			}
			position += '"' + this.children[i].icon_id + '"' ;
		  }
				position += "]}"
				 alert(position);
				 $.ajax({
					 type: "GET",
					 url: "arrange_icons2.php?update_icons=A&",
					 data: position,
					 dataType: "text"
				 }); 

Open in new window

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:sabecs
ID: 37043966
Thanks again varontron,

the alert creates the following---> {position:[,"59","76","70","96","65","90"]}

but I can't see my PHP code doing anything?

if(isset($_GET['position'])){
            $position = $_GET['position'];
            $pos_array = explode(",",$position);
        $group_name = $_GET['group_name'];
            
            foreach($pos_array as $key => $value){
                  $update_icons = "UPDATE icons2 SET group_name = '".$group_name."', icon_position = '".$key."' WHERE id = '".$value."';";
                  //echo $query_icons."</br>";
                  mysql_query($update_icons, $conn_data) or die(mysql_error());
            }
       $insertGoTo = "arrange_icons2.php";
 
      header(sprintf("Location: %s", $insertGoTo));
}
0
 
LVL 3

Assisted Solution

by:varontron
varontron earned 2000 total points
ID: 37044237
I wonder if the first empty index in the array is the problem.   eliminate that:
for (i=0; i < this.children.length; i++) {
			position += '"' + this.children[i].icon_id + '"' ;
                        if (i < position.length - 1) {
			  position += ',';
			}
		  }
				position += "]}

Open in new window


also, add a success handler to ajax so you can see what's coming back

                                 $.ajax({
					 type: "GET",
					 url: "arrange_icons2.php?update_icons=A&",
					 data: position,
					 dataType: "text",
                                         success: function(data) {
                                               alert(data);
                                         }
				 }); 

Open in new window

0
 

Author Comment

by:sabecs
ID: 37048375
Thanks varontron again for your help, I still could not get the code above to work, but got the following to work and all is good execept I would like to know why and what the difference is between the code?

Works
 $.ajax({ url: "arrange_icons2.php?group_name=A&position="+position });

 Didn't work
 $.ajax({
       type: "GET",
       url: "arrange_icons2.php?group_name=E&",
       data: position,
       dataType: "text"
       });


 
$(function() {
		$("#sortable3" ).sortable({'update': function(event, ui){
		 
		 var position='';
		  
		  for (i=0; i < this.children.length; i++) {
			if (position.length) {
			  position += ',';
			}
			position += this.children[i].icon_id ;
		  }
			   $.ajax({ url: "arrange_icons2.php?group_name=A&position="+position });
		}
	  }); 

 });

Open in new window

0
 
LVL 3

Assisted Solution

by:varontron
varontron earned 2000 total points
ID: 37048463
The goal is to send url parameters with your request.  In your solution, you've appended a comma delimited string to the url, with a key, so it works as expected.  You've appended the proper syntax, so it works.

Alternatively, using the 'data' key in the object passed to the ajax function, you are supposed to pass a value for that key as an object, or as a string in object syntax.  That object or string is converted into url parameters by jquery.

i believe the reason it is not working is because of the leading comma created in the loop (the comma before 59.)  

{position:[,"59","76","70","96","65","90"]}

Open in new window



If that comma was removed, or if the index it represents was quoted, it would probably work.  You could try hardcoding it into the function.

{position:["","59","76","70","96","65","90"]}

Open in new window


or

{position:["59","76","70","96","65","90"]}

Open in new window



That leading comma could throw off the jquery function that is parsing the string or object into the url params.  In some cases, jquery, and browsers as well can be finicky about JSON syntax.

hth,
Dave
0
 

Author Closing Comment

by:sabecs
ID: 37048494
Thanks Dave, your help was greatly appreciated... Cheers.. Andrew
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month17 days, 21 hours left to enroll

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question