Post serialized form data and extra variables using JQuery - php

I am trying to use this piece of code to serialize a form AND send an extra variable not found in the form, at the same time. The following line of code is what I expected, but sadly does not work.
var thePage = theFilename();
$.post("pagedetail.php", { $("#PageDetailForm").serialize(), thePage: thePage },
function(data) {
alert(data);
});
Any ideas?

var serialized = $('#PageDetailForm').serialize();
serialized.thePage = thePage;
$.post("pagedetail.php", serialized,
function(data) {
alert(data);
});

what you can do is to add the extra data to an hidden input and catch it in the
pagedetail.php page .
eg lats say your form
<form id='PageDetailForm'>
<input type="hidden" name="value" id="value" value="the value u wamnt to add goes here" />
....other inputs
</form>
after this just do your normal $.post
$.post("#pagedetail.php",$("#PageDetailForm").serialize(),function(data){
$("#ans").html(data);
// in the pagedetail.php
$echo $_POST['value'];
hope dis help if ur still confused hola me #dplumptre

Try this for the second parameter to $.post:
{ form: $("#PageDetailForm").serialize(), thePage: thePage }

Hopefully you still need this :).
Try the serializeArray() method and then push some additional data in the resulting array, so you don't have splitted arrays etc.:
var postData = $('#form-id').serializeArray();
var additionalData = $('#additionalDataID').val();
postData.push({name: 'additionalName', value: additionalData});
and finally:
$.post(URL, postData);

Try sortable('toArray'):
var thePage = theFilename();
$.post("pagedetail.php", { pageDetailForm: $("#PageDetailForm").sortable('toArray'), thePage: thePage },
function(data) {
alert(data);
});

Related

Multiple submit buttons on one page but distinguishable (jquery)

I am trying to write a code that 'stores items for later' - a button that has url of the item as hidden input, on submit it calls a php script that does the storage in a db. I am more into php, very little knowledge of anything object-oriented, but I need to use jquery to call the php script without moving over there
The problem is how to assign the x and y variables when I have multiple forms on one page
I was only able to write the following
$("form").bind('submit',function(e){
e.preventDefault();
var x = $("input[type=hidden][name=hidden_url]").val();
var y = $("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php?url='+x+'&tit='+y,
success: function() {
alert( "Stored!");
location.reload();
}
});
});
It works fine if you have something like...
<form method="post" action="#">
<input type="hidden" id="hidden_url" name="hidden_url" value="<?php echo $sch_link; ?>"/>
<input type="hidden" id="hidden_title" name="hidden_title" value="<?php echo $sch_tit; ?>"/>
<input type="submit" id="send-btn" class="store" value="Store" />
</form>
..once on the page, I've got about 50 of them.
These are generated via for-loop I suppose I could use $i as an identifier then but how do I tell jquery to assign the vars only of the form/submit that was actually clicked?
You'll have to scope finding the hidden fields to look within the current form only. In an event handler, this will refer to the form that was being submitted. This will only find inputs matching the given selector within that form.
$("form").bind('submit',function(e){
e.preventDefault();
var x = $(this).find("input[type=hidden][name=hidden_url]").val();
var y = $(this).find("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php',
data: {
url: x,
tit: y
},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
As #Musa said, it's also better to supply a data key to the $.ajax call to pass your field values.
Inside your form submit handler, you have access to the form element through the this variable. You can use this to give your selector some context when searching for the appropriate inputs to pass through to your AJAX data.
This is how:
$("form").bind('submit',function(e) {
e.preventDefault();
// good practice to store your $(this) object
var $this = $(this);
// you don't need to make your selector any more specific than it needs to be
var x = $this.find('input[name=hidden_url]').val();
var y = $this.find('input[name=hidden_title]').val();
$.ajax({
url: 'save_storage.php',
data: {url:x, tit: y},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
Also, IDs need to be unique per page so remove your id attribute from your inputs.

How do I get jquery variable value to be read by PHP $_POST?

I'm able to successfully get all the values from a multi-select form into one nice delimited variable, but I can't figure out how to get the value to my PHP script? How do I get the 'output' value read by PHP's $_POST array? Any help would. Be. Awesome. :D
<script type="text/javascript">
function ValidatePageForm() {
var result = new Array();
$("#select-to option").each(function() {
result.push($(this).val());
});
var output = result.join("-");
alert(output);
}
</script>
suppose you have a form
<form>
<input type="hidden" name="output" id="output">
....
</form>
send javascript variable to HTML
var output = result.join("-");
$('#output').val(output);
and when you submit the form
you wil get data in $_POST['output']
I believe your looking for something like echo $_POST['value']; ??
You can use Jquery serialize to post all the data of the form including multi select
var submit_data = $('#output').serialize();
var post_data = submit_data ;
$.ajax({
type: "POST",
url: 'submitform.php',
data: post_data,
success: function(data)
{
}
});
You will get all the value in $_POST on submitform.php
Let me know it works for you

Pass an array from PHP to javascript using PHP

Could someone help me with how to pass an array of values from PHP and retrieve it using AJAX. What i have found is only to pass a single value from PHP. When i try passing the value of an array i dont know how to receive it at the AJAX side
This is my PHP code:
$success[];
$timeout[];
$fail[];
while($row1 = mysql_fetch_array($masterresult))
{
$success[]=$row1[1];
$timeout[]=$row1[2];
$fail[]=$row1[3];
}
echo json_encode(array("a"=>$success,"b"=>$timeout,"c"=>$fail));
And below is by AJAX call:
var channel;
function overall(){
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
window['channel']="overall";
$.ajax({
type:"GET",
url:"dash2.php",
data:{channel:channel},
dataType:'json',
success:function(data){
console.log(data.a);
console.log(data.b);
console.log(data.c);
}
});
}
How should i pass those php array values onto this ajax call? could someone help me with the code
What you want to do is encode it as JSON.
$yourArray = array('asdf', 'qwer', 'zxcv');
echo 'var yourJavaScriptArray = ' . json_encode($yourArray) . ';';
This makes all of your arbitrary data safe for use in JavaScript as well.
If you are only doing this with AJAX, no need for the var part. Just output from json_encode() directly.
Whether it is one value or multiple values in an array for example, you should always use:
json_encode($your_php_var)
json_encode your array on PHP end.
Use that JSON object in JavaScript without any additional effort, its part of JavaScript.
When you send it back to PHP just json_decode it in PHP.
Reference: PHP Manual
Hope this example will help you. Imagine if you have some input data on html form and need to send them by AJAX, do something with them on server side and recive the result on client side and do some stuff with it.
<form id="my_form" method="post" action="<?=$ServerSideUrl?>">
<input type="text" name="field_1" value="">
<input type="text" name="field_2" value="">
<input type="text" name="field_3" value="">
</form>
Here is you AJAX script, i used in this example JQuery
$('#my_form').ajaxSubmit({
dataType: 'html',
error: function() {
alert('some error text');
},
complete: function(data) {
//data this is the result object which returned from server side
//for example you shpold alert the sum of thouse 3 field
alert(data.sum);
}
});
Here is your server side code
<?
$data = array();
$data["sum"] = $_POST["field_1"] + $_POST["field_2"] + $_POST["field_3"];
echo my_json_encode($data);
return true;
?>
So when your AJAX will be complete it alert the sum of three field on your form,
You can use JSON in combination with jQuery for that.
<?php
$myArray = array('a', 'b');
echo json_encode($myArray);
?>
Ajax
$.get('http://localhost/index.php',
function(data) {
var response = jQuery.parseJSON(data);
console.log(response);
}
);
In your code:
var channel;
function overall(){
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
window['channel']="overall";
$.ajax({
type:"GET",
url:"dash2.php",
data:{channel:channel},
dataType:'json',
success:function(data){
console.log(data["a"]);
console.log(data["b"]);
console.log(data["c"]);
}
});
}

Reading serialized jquery data in PHP (multiple checkboxes)

JQUERY:
$(document).ready(function(){
$('form').submit(function(){
var content = $(this).serialize();
//alert(content);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/test/generate',
timeout: 15000,
data:{ content: content },
success: function(data){
$('.box').html(data).fadeIn(1000);
},
error: function(){
$('.box').html('error').fadeIn(1000);
}
});
return false;
});
});
HTML:
<form>
<input type="checkbox" value="first" name="opts[]">
<input type="checkbox" value="second" name="opts[]">
<input type="checkbox" value="third" name="opts[]">
<input type="submit">
</form>
How do i process (or read) multiple checked checkbox's value in PHP? I tried doing $_POST['content'] to grab the serialized data but no luck.
Replace:
data:{ content: content } // <!-- you are prefixing with content which is wrong
with:
data: content
Now in your PHP script you can use $_POST['opts'] which normally should return an array.
Try
echo $_POST['opts'][0]. "<br />";
echo $_POST['opts'][1]. "<br />";
echo $_POST['opts'][2]. "<br />";
You post an array to the Server and it is available in the post variable 'opts'. Remember: Unchecked boxes dont get posted.
The chosen answer still didn't work for me, but here is what did:
var checkedBoxesArr = new Array();
$("input[name='checkedBoxes']:checked").each(function() {
checkedBoxesArr.push($(this).val());
});
var checkedBoxesStr = checkedBoxesArr.toString();
var dataString = $("#" + formID).serialize() +
'&checkedBoxesStr=' + checkedBoxesStr;
[The above code goes in your javascript, before serializing the form data]
First, cycle through the checked boxes and put them into an array.
Next, convert the array to a string.
Last, append them to the serialized form data manually - this way you can reference the string in your PHP alongside the rest of the serialized data.
This answer came partly from this post: Send multiple checkbox data to PHP via jQuery ajax()
there are an Error in your code :
The url should be url: 'http://localhost/test/generate.php' with the extension name

Fetch input value from certain class and send with jquery

<input id="u1" class="username">
<input id="u2" class="username">
<input id="u3" class="username">
...
How to fetch input value with "username" class and send with ajax jquery to php page.
i want to recive data like simple array or simple json. (i need INPUT values and not ids)
var inputValues = [];
$('input.username').each(function() { inputValues.push($(this).val()); });
// Do whatever you want with the inputValues array
I find it best to use jQuery's built in serialize method. It sends the form data just like a normal for submit would. You simply give jQuery the id of your form and it takes care of the rest. You can even grab the forms action if you would like.
$.ajax({
url: "test.php",
type: "POST",
data: $("#your-form").serialize(),
success: function(data){
//alert response from server
alert(data);
}
});
var values = new Array();
$('.username').each(function(){
values.push( $(this).val());
});

Categories