Solved

Javascript serialize and post to php

Posted on 2014-02-28
16
505 Views
Last Modified: 2014-03-03
I would love to have help in making this javascript code work with serialized and also post to php.

First, here is two buttons. When I click one of them my div #order_somenumber changes from width 48% or 98%

<input type="button" value="1/2 size" class="button"  name="48%" />
<input type="button" value="Full Size" class="button"  name="98%" />

Open in new window


And the javascript to enforce it.
<script>    
        $(document).ready(function() {
            $('.button').click(function(){
                var widthValue = $(this).attr('name');

                $('#order_some number').animate({
                        width: widthValue
                    }, 600, function() {

                });
             }); 
        });
    </script>

Open in new window


Now I need to serialize the above #order and also via ajax post something like this

$.ajax({
                url: "folder/folder2/folder3/changehighlight.php",
                type: "post",
                data: {
                   size: 1,
                   id: ui.element.attr('id')
                }
            });

Open in new window


And finally via some kind of trick make the 1/2 size button disappear, when the size value is set to size: 1, and the full size button disappear, when the size value is set to size: 2,

Can you help me by merging the codes into one working solution.
I am working with jQuery and UI as well.
Please post in full examples, as my javascript syntaxing brain still is young!
0
Comment
Question by:sofuscomer
  • 6
  • 5
  • 3
  • +1
16 Comments
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39896388
0
 

Author Comment

by:sofuscomer
ID: 39896920
Hi Ray, I read your article and like it. It helps me understand parts of it, but its not a solution for now. I simply do not know how to merge the two codes into one.
Its probably basic for a lot of you guys, but not for me yet :-)
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39897187
Sorry, I don't think I can make it any simpler.  Much of this learning process is just trial and error, taking examples and modifying them to see what different effects you can achieve.  The first thing you need is an understanding of JavaScript.  You don't have to be a pro at it, just understand the basics.  If jQuery is like finance, JavaScript is like arithmetic.  You can't get to the other without some sense of the basics.  You'll also need to understand CSS, but fortunately all of my students have found that the understanding of jQuery and CSS come together in a way that each reinforces the other.

For many years the "goto" resource was Karl Swedberg's site, but that is in the sunset now.  The best, community-sourced learning site is http://learn.jquery.com/

Some other resources that I can endorse:
http://www.codecademy.com/tracks/jquery

You might want to spend a little time here:
http://try.jquery.com/

Simple but mostly accurate examples are available from W3Schools.

If you want to be really smart about it, save all of your work in teaching libraries.  Each example should have a title and description of the problem (you can put these in comments at the top of the code) then an example of the code that solves the problem.  If you start with the basics and build up from there, you will soon have a collection of problems and solutions that can be reapplied to the larger challenges.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39897249
I'm not entirely sure what you're after, but take a look at this. It uses data attributes on the buttons to store data, instead of using the name attribute. Also not sure where you get the size and id values from to pass to your AJAX call.

//HTML
<input type="button" value="1/2 size" class="button"  data-width="48%" data-size="1" />
<input type="button" value="Full Size" class="button"  data-width="98%" data-size="2" />

//jQuery
$('.button').click(function(){
	//store which button was clicked
	clickedButton = $(this);

	$('#order_somenumber').animate({
		//set the width to the data-width value of the clickedButton
		width: clickedButton.data('width')
	}, 600, function() {
		//now the animation is complete, lets make an AJAX request.
		$.ajax({
			url: "folder/folder2/folder3/changehighlight.php",
			type: "post",
			data: {
				size: clickedButton.data('size')
			}			
		})
		.done(function() {
			//The ajax call is complete, so lets hide this button and show the rest			
			clickedButton.hide();
			$(".button").not(clickedButton).show();
		});
	});
});

Open in new window

0
 

Author Comment

by:sofuscomer
ID: 39897772
Hi Ray,
Great work
Now I guess all that is missing is how to serialize the #order
Cause they appear like this
id="order_1234"
id="order_1235" etc etc etc...

My current code is like this.

And my php scripts needs to have the id of the order also..
So size=1, id=1294 etc etc.

$('.button').click(function(){
	//store which button was clicked
	clickedButton = $(this);

	$('#order').animate({
		//set the width to the data-width value of the clickedButton
		width: clickedButton.data('width')
	}, 1000, function() {
		//now the animation is complete, lets make an AJAX request.
		$.ajax({
			url: "folder/folder2/ajax/sizeupdate.php",
			type: "post",
			data: {
				size: clickedButton.data('size')
			}			
		})
		.done(function() {
			//The ajax call is complete, so lets hide this button and show the rest			
			clickedButton.hide();
			$(".button").not(clickedButton).show();
		});
	});
});
    </script>

Open in new window

0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39897845
Firstly, I'm Chris not Ray!

Secondly, that's not your code - it's mine :)

You mention order numbers, such as id="order_1234" but nowhere in any of your code do you show us the HTML that this refers to. Can you explain how the buttons from your original post relate to the order numbers and size that you need.

Maybe show us more of you HTML that you need the jQuery to work with
0
 
LVL 34

Expert Comment

by:Slick812
ID: 39898095
greetings sofuscomer, , Your description of where you need to go in code, and what needs to be done in code, and what page elements are affected (multiple forms I guess?) by code, is NOT CLEAR to me at all! ! !

You give this as your ajax function -
$.ajax({
  url: "folder/folder2/folder3/changehighlight.php",
  type: "post",
  data: {size: 1, id: ui.element.attr('id') }
  });

Open in new window


But you do NOT have any -
    .done(function(data) {

at ALL, nothing ! ! the purpose of AJAX is to send data AND get data back from a PHP POST page call, but you do not show any code to use any data that is returned in the .done(function(data){
   How can that be any good? ? ?

Maybe we can do this one step at a time? First here is my code for a page where on a button in a FORM when clicked the whole form resizes  AND the button display text goes from 1/2 to FULL size. I do Not think a two button GUI that hides buttons, is any good for this , so I just use ONE button per FORM. see code below.
<!doctype html>
<html><head><title>jQuery Form Test AJAX</title>
<style>
.dv1{width:760px;
border:1px solid #000;}

.order{
width:48%;
background:#fbdba0;
margin:12px auto;
padding:9px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$( document ).ajaxError(function( event, request, settings, exc ) {
alert("ERROR from Ajax POST= Server-Status: "+request.status+", post-URL: "+settings.url+", post-Data: "+settings.data+", error because: "+exc);
});


$(document).ready(function() {
  $('.button').click(function(){

    var bnt = $(this);
	var size1 = bnt.data('size');
	var wid = "48%";
	var  bntText = "1/2 Size";
	if (size1 == 2) {
      bntText = "Full Size";
      bnt.data('size',1);
      } else {
      bnt.data('size',2);
      wid = "97%";
      }
    var bntID = bnt.attr('id');
    var frmID = "#order"+bntID.substr(3); 

//$(frmID).width(wid);
    $(frmID).animate({width: wid}, 600, function() {bnt.val(bntText); });
  }); 
});
</script>
</head>
<body><h3 style="text-align:center;">Test AJAX Form Submit</h3>

<div class="dv1">
<form name="formAj1" class="order" id="order1234">
Name: <input type="text" name="uname" size="16" value="" /> more than 4 characters<br />
Age: <input type="text" name="age" size="5" maxlength="3" value="" /> Years: older than 17 years<br />
<input type="button" id="bnt1234" value="Full Size" class="button" data-size="1" />
</form>
<form name="formAj2" class="order" id="order1235" action="formnon.php" method="post">
Name: <input type="text" name="uname" size="16" value="" /> more than 4 characters<br />
Age: <input type="text" name="age" size="5" maxlength="3" value="" /> Years: older than 17 years<br />
<input type="button" id="bnt1235" value="Full Size" class="button" data-size="1" />
</form>
<form name="formAj3" class="order" id="order1236" action="formnon.php" method="post">
Name: <input type="text" name="uname" size="16" value="" /> more than 4 characters<br />
Age: <input type="text" name="age" size="5" maxlength="3" value="" /> Years: older than 17 years<br />
<input type="button" id="bnt1236" value="Full Size" class="button" data-size="1" />
</form>
</div>

</body></html>

Open in new window

In this I have ALL functional elements (the three buttons and three forms) with distinctive ID's like  "bnt1235" and "order1235", that way I can know what to do with what button and what form, the form button id MUST HAVE the same Number ending as the from id it's inside of, like "bnt1236" and "order1236". That way I can change the correct form size, the way you state it as -
    "And my php scripts needs to have the id of the order also..
    So size=1, id=1294 etc etc."

makes no sense at all? ?

In my JS I get the button ID with -
var bntID = bnt.attr('id');

and then change it to a Jquery Form ID with -
var frmID = "#order"+bntID.substr(3);

then the frmID can be used to do any JS operation on that particular form, including the serialize() needed for a ajax post call -
$(frmID).serialize());

I do not use the kinda wacky button name , data-width to set the widths, I just use a string that changes -
var wid = "48%";
 from the data-size that is changed in a single button

any way, this is my far fetched GUESS, at what may be helpful to you, after we get the button and form size to work, maybe some work can be done on the ajax part?
But I really do NOT understand WHY you say you want a button Click to Change the Form size 48%  AND AJAX the form data to a php page, seems like it is unusual and I see no purpose to doing Both? ?
0
 

Author Comment

by:sofuscomer
ID: 39899009
Sorry Chris, And thanks Chris and Slick812.
I obviously have not explained my question well enough. Sorry for that.
But in essence this code below using the resizable jQueryUI does what I want to the <li> in the #sortable div.

This code works already. The code I am asking help for resembles this behaviour, except that it must be a click that animate moves my div id="order_1234" from either 48-98% or reverse.

<script>
$( "#sortable li" ).resizable({
    grid: [ 48, 98 ],
    maxWidth: 98,
    minWidth : 48,
    stop: function(event, ui) {
        if(ui.originalSize.width < $("#sortable").width() / 2) {
            ui.element.css({width: '98%'});
            $.ajax({
                url: "folder1/folder2/inc-ajax/inc-sizeupdate.php",
                type: "post",
                data: {
                    size: 2,
                   id: ui.element.attr('id')
                }               

            });
        } else {
            ui.element.css({width: '48%'});
            $.ajax({
                url: "folder1/folder2/inc-ajax/inc-sizeupdate.php",
                type: "post",
                data: {
                    size: 1,
                   id: ui.element.attr('id')
                }

            });
        }
    }
});
</script>

Open in new window


Now all that I need for the code that I ask here to do, is not to drag resize, but instead toggle between 48% width and 98% width, when either a button or ui-icon etc is clicked.
With a animation showing a resize from either 48-98% width or reverse.

In my php table i store the number 1 or 2. 1 is half size and 2 is full size.

If the div id="order_1234" is already 48% the click must send the id of the #order_1234 and a size = 2. (Make this div full size width and update the mysql size from 1 to 2.)

If the div id="order_1234" is already 48% (Half size in my layout), the click must do the same, except send a size = 1. (Make this div half size width and update the mysql size from 2 to 1.)

Hope this explains better?
0
 
LVL 34

Expert Comment

by:Slick812
ID: 39899108
I do get some new view about the "workings" for your -
"If the div id is "order_1234" , the "re-size" button click must change the size, AND send the id of the order_1234 and the new size. "

But as for me, my problem is IF you have 8 div's wid ID's, order_1231 to order_1238,  AND 8 (or 16) buttons somewhere on the page (beside the div's I guess? ?), how to effectively MATCH the 8 different buttons to the corresponding DIV in javascript code as -
$('.button').click( function() {
  var buttonC = $(this);

when you are DRAGGING in this code -
$( "#sortable li" ).resizable({

the element (div) wid ID you need is delivered here -
stop: function(event, ui) {

in the ui parameter.

but in this button click -
$('.button').click( function() {

ONLY the button element is there as $(this) and NO idea which div to work on. I gave you my version of obtaining the order ID, by getting the button ID and using it to make the needed div ID, which is as simple as this -
var bntID = $(this).attr('id');
var divID = "#order"+bntID.substr(3);

There are other ways to match up button clicks to other elements (div), but this is what I have in my code, and as written, it works for me.

Just so you know, your code as -
if(ui.originalSize.width < $("#sortable").width() / 2) {
            ui.element.css({width: '98%'});
            $.ajax({
                url: "folder1/folder2/inc-ajax/inc-sizeupdate.php",
                type: "post",
                data: {
                    size: 2,
                   id: ui.element.attr('id')
                }               

            });
        } else {
            ui.element.css({width: '48%'});
            $.ajax({
                url: "folder1/folder2/inc-ajax/inc-sizeupdate.php",
                type: "post",
                data: {
                    size: 1,
                   id: ui.element.attr('id')
                }

            });
        }

Open in new window

is very ineffective, you have TWO operations for  $.ajax({  , that do the same exact thing Except for the size, my view is that it is better to use variables (that's what they are for) -
stop: function(event, ui) {
  var width1 = '48%';
  var size1 = 1;

  if(ui.originalSize.width < $("#sortable").width() / 2) {
  width1 = '98%';
  size1 = 2;
  }

  ui.element.css({width: width1 });
  $.ajax({ url: "folder1/folder2/inc-ajax/inc-sizeupdate.php",
       type: "post",
       data: {size: size1,
         id: ui.element.attr('id')
         }               
      });

  }

Open in new window

You do not have any code for the AJAX data return, you really should get something returned to check and see if the Database update worked or not, in your easy development testing, it may always work, but in production the database code may not work for an odd reason, or change-update in the server version, mysql version.

Not sure I can write any code for the multi-BUTTON click thing, as my code before seems to cover the situation for the matching, hopefully you can form a code try and if it is problems, maybe I can look?
But I am not sure about the BUTTON element you do or do not want to use, there are thousands of different colorful buttons in web design, and you say - "when either a button or ui-icon etc is clicked", , to me a CLICK event is handled in code same for any element, so there is some reluctance for me to do new code for this, as you may not understand it, ,  as you do not seem to understand or apply my last Click code? ?
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39899199
Show us some HTML and we can figure out how you tie up your buttons to the divs.

It's a fairly easy thing to do, but without seeing the HTML, we're working blind
0
 

Author Comment

by:sofuscomer
ID: 39899740
Hi I cannot not show you the actual page, but here is a view of the source:

First my CSS for the item 48% and the item w2 98%

.item {
			float: left;
			width: 48%;
			height: auto;
			padding: 0;
			margin: 4% 1%;
}

.item.w2 {
			float: left;
			width: 98%;
			height: auto;
			padding: 0;
			margin: 4% 1%;
}

Open in new window



All these divs have an id of order_1234. The number is the ID of that item, that I also need to send to my php script where an update function looks for the item carrying that id and update size from either 1 or 2

The class is either "item" or "item w2"

I want a button or normal link. (DOES NOT HAVE TO BE A BUTTON) to animate the div id="order_1234", and update size from either 1 to 2 or reverse.


Here is the source.
<div id="order_1916" class="item w2"><a href="javascript:void()" title="Delete this Item" class="ui-icon ui-icon-trash" onclick="deleteBox(1916)">Delete Item</a>
<a href="../lakjdslj/123321/ite/jh364yfh4619/1916-9sgt2f8dw5ao.jpg" class="openme" data-caption="&copy; Sofus Comer, www.sofuscomer.com" data-type="image">
<div id="itembox" style="background-image:url(lakjdslj/123321/ite/jh364yfh4619/1916-9sgt2f8dw5ao.jpg);background-size:contain;background-repeat: no-repeat; background-position:center center;">
</div>
</a>
</div>



<div id="order_1915" class="item"><a href="javascript:void()" title="Delete this Item" class="ui-icon ui-icon-trash" onclick="deleteBox(1915)">Delete Item</a>
<a href="../lakjdslj/123321/ite/jh364yfh4619/1915-dulmegkor327.jpg" class="openme" data-caption="&copy; Sofus Comer, www.sofuscomer.com" data-type="image">
<div id="itembox" style="background-image:url(lakjdslj/123321/ite/jh364yfh4619/1915-dulmegkor327.jpg);background-size:contain;background-repeat: no-repeat; background-position:center center;">
</div>
</a>
</div>



<div id="order_1918" class="item"><a href="javascript:void()" title="Delete this Item" class="ui-icon ui-icon-trash" onclick="deleteBox(1918)">Delete Item</a>
<a href="../lakjdslj/123321/ite/jh364yfh4619/1918-vrqmzjco6t2y.jpg" class="openme" data-caption="&copy; Sofus Comer, www.sofuscomer.com" data-type="image">
<div id="itembox" style="background-image:url(lakjdslj/123321/ite/jh364yfh4619/1918-vrqmzjco6t2y.jpg);background-size:contain;background-repeat: no-repeat; background-position:center center;">
</div>
</a>
</div>



<div id="order_1914" class="item w2"><a href="javascript:void()" title="Delete this Item" class="ui-icon ui-icon-trash" onclick="deleteBox(1914)">Delete Item</a>
<a href="../lakjdslj/123321/ite/jh364yfh4619/1914-av364prxt9zh.jpg" class="openme" data-caption="&copy; Sofus Comer, www.sofuscomer.com" data-type="image">
<div id="itembox" style="background-image:url(lakjdslj/123321/ite/jh364yfh4619/1914-av364prxt9zh.jpg);background-size:contain;background-repeat: no-repeat; background-position:center center;">
</div>
</a>
</div>



<div id="order_1913" class="item"><a href="javascript:void()" title="Delete this Item" class="ui-icon ui-icon-trash" onclick="deleteBox(1913)">Delete Item</a>
<a href="../lakjdslj/123321/ite/jh364yfh4619/1913-id93cjklfe4y.jpg" class="openme" data-caption="&copy; Sofus Comer, www.sofuscomer.com" data-type="image">
<div id="itembox" style="background-image:url(lakjdslj/123321/ite/jh364yfh4619/1913-id93cjklfe4y.jpg);background-size:contain;background-repeat: no-repeat; background-position:center center;">
</div>
</a>
</div>



<div id="order_1917" class="item"><a href="javascript:void()" title="Delete this Item" class="ui-icon ui-icon-trash" onclick="deleteBox(1917)">Delete Item</a>
<a href="../lakjdslj/123321/ite/jh364yfh4619/1917-n9z3ebkh48a0.jpg" class="openme" data-caption="&copy; Sofus Comer, www.sofuscomer.com" data-type="image">
<div id="itembox" style="background-image:url(lakjdslj/123321/ite/jh364yfh4619/1917-n9z3ebkh48a0.jpg);background-size:contain;background-repeat: no-repeat; background-position:center center;">
</div>
</a>
</div>



<div id="order_1912" class="item w2"><a href="javascript:void()" title="Delete this Item" class="ui-icon ui-icon-trash" onclick="deleteBox(1912)">Delete Item</a>
<a href="../lakjdslj/123321/ite/jh364yfh4619/1912-h3ionzk09gsf.jpg" class="openme" data-caption="&copy; Sofus Comer, www.sofuscomer.com" data-type="image">
<div id="itembox" style="background-image:url(lakjdslj/123321/ite/jh364yfh4619/1912-h3ionzk09gsf.jpg);background-size:contain;background-repeat: no-repeat; background-position:center center;">
</div>
</a>
</div>



<div id="order_1911" class="item w2"><a href="javascript:void()" title="Delete this Item" class="ui-icon ui-icon-trash" onclick="deleteBox(1911)">Delete Item</a>
<a href="../lakjdslj/123321/ite/jh364yfh4619/1911-x8jqvwfgtlse.jpg" class="openme" data-caption="&copy; Sofus Comer, www.sofuscomer.com" data-type="image">
<div id="itembox" style="background-image:url(lakjdslj/123321/ite/jh364yfh4619/1911-x8jqvwfgtlse.jpg);background-size:contain;background-repeat: no-repeat; background-position:center center;">
</div>
</a>
</div>



<div id="order_1910" class="item w2"><a href="javascript:void()" title="Delete this Item" class="ui-icon ui-icon-trash" onclick="deleteBox(1910)">Delete Item</a>
<a href="../lakjdslj/123321/ite/jh364yfh4619/1910-4ktdsm5fhz7u.jpg" class="openme" data-caption="&copy; Sofus Comer, www.sofuscomer.com" data-type="image">
<div id="itembox" style="background-image:url(lakjdslj/123321/ite/jh364yfh4619/1910-4ktdsm5fhz7u.jpg);background-size:contain;background-repeat: no-repeat; background-position:center center;">
</div>
</a>
</div>

Open in new window


I am using these versions of jQuery:

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

Open in new window


Sincerly hopes that this is a bit closer to being understandable.
0
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 39900033
OK. Here's something that might get you going. When you build your HTML drop in a couple of data attributes to store the orderid and size. That way it's just easier to get at the info:

//HTML
<div id="order_1916" class="item w2" data-orderid="1916" data-size="2">
	<a class="change" href="#">Change</a>
</div>

<div id="order_1915" class="item" data-orderid="1915" data-size="1">
	<a class="change" href="#">Change</a>
</div>


//jQuery
$('.change').click(function(e) {
	e.preventDefault();
	
	//get some details
	item = $(this).parents('.item')
	newWidth = (item.data('size') == 1) ? '98%' : '48%';
	newSize = (item.data('size') == 1) ? 2 : 1;
	orderID = item.data('orderid');

	//change the size
	item.animate({ width: newWidth }, 600, function() {
		//now make the AJAX call
		$.ajax({
			url: "yourScript.php",
			type: "post",
			data: { size: newSize, orderid: orderID }			
		})
		.done(function(response) {
			//The ajax call is complete
			item.data('size', newSize);			
		});
	});
});

Open in new window

0
 

Author Closing Comment

by:sofuscomer
ID: 39900247
Thank you very much Chris. Your solution was nail on!
Thanks to Slick812  for your help also. Would love to have given you points as well.
I hope that this is the most correct way to end this Q & A.
Atb Sofus
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39900267
Thanks for the points.

For future reference, when you accept an answer, you can also accept other answers as 'assisted' and award a share of the points if you want to. Often more than one expert will help you get to where you want to go :)

Good luck with it
0
 
LVL 34

Expert Comment

by:Slick812
ID: 39901182
just a reminder from slick, we can help you if you give enough info about where you need to go (the page result display or operation) AND what html-javascript-css you use now , or the stuff you want to use (as you finally gave as - <div id="order_1918" class="item"> ), but you started with a question about "Javascript serialize", but there was no serialize needed. I tried to guess at your HTML to help you, but it was not even close.
More time spent by you building a good question, will save EVERYONE much time to get an answer for u.
// I do not need points anymore, but a thanks makes me feel less like a posting machine here.
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39901203
@Slick812 +1

“a problem well put is half solved.”
John Dewey
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

679 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