How to send a serialized array to a php document? - javascript

I've got a JavaScript array named seat with many values in it.
As follows,I've serialized to be sent to a php file named confirm.php.
$('btnsubmit').click(function() {
var seat = [];
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: seatar
})
})
And this is the code in my php file.
$seatarr = "";
if(isset($_POST['data']))
{
$seatarr = $_POST["data"];
print_r($seatarr);
}
I've tried with my level best, looking at the previous questions asked on this section. But no matter how hard I try to fix it, this code never works. Why not?

You're just sending raw JSON, but you're expecting to get a URI-encoded form with a data field in it. You can get that if you change your ajax call to use data: {data: seatar}:
$('btnsubmit').click(function() {
var seat = [];
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
})
});
jQuery will automatically turn that object into a URI-encoded submission with a single field in it.
Then use json_decode if you want to parse it on the server:
if(isset($_POST['data']))
{
$seatarr = json_decode($_POST["data"]);
print_r($seatarr);
}
Also, as Mr. Blue pointed out, your button selector is probably incorrect. You have $('btnsubmit') which is looking for a <btnsubmit>...</btnsubmit> element. You probably meant $("#btnsubmit") (if you have id="btnsubmit" on the button) or $("[name=btnsubmit]") (if you have name="btnsubmit" on the button).

Another solution can be to rewrite the data like this:
seatar = $(this).serialize() + "&" + $.param(seatar);
and decode like T.J Crowder did propose:
if(isset($_POST['data']))
{
$seatarr = json_decode($_POST["data"]);
print_r($seatarr);
}

Related

Ajax array only returns 1 value?

I am new to PHP and Ajax so please bear with me. I've searched around and found some answers but still am having trouble. I have an array of check box input values. If a user checks an item it is added to my array list. An example would be:
listOfPrograms = [chrome, firefox, sqlworkbench]
I want to send this array list to a PHP script on my server. My current Ajax script is as follows:
function ajaxPostToPhp(listOfPorgrams)
{
$.ajax
({
url: 'script.php',
type: 'post',
data: ("listOfPrograms" : listOfPrograms), // I believe this is where my issues lies as I do not know exactly that this is doing. I have read the PHP documentation. I tried converting to JSON and kept getting a 500 error.
success: function(data)
{
console.log(data);
}
});
}
My PHP script is as folllows:
$myArray = $_Request['listOfPrograms'];
echo $myArray;
This returns only 1 item from the array. I tried setting myArray = [] but I get an undefined index.
Thanks for your help! Sorry for such a noob question.
You need to fix a few things:
1- Javascript array:
var listOfPrograms = ['chrome', 'firefox', 'sqlworkbench'];
2- Ajax Data:
function ajaxPostToPhp(listOfPrograms)
{
myListData = {};
myListData['Programs'] = listOfPrograms;
$.ajax({
url: 'script.php',
type: 'post',
data: myListData,
success: function(data)
{
console.log(data);
}
});
}
3- Php Code:
$myArray = $_POST['Programs'];
var_dump($myArray);
You are passing an array as post parameter but they can only be strings. You should convert the array to a JSON string first. An easy function for that purpose is JSON.stringify()
var listOfPrograms = ["chrome", "firefox", "sqlworkbench"]
// I guess you need strings here
function ajaxPostToPhp(listOfPorgrams) {
$.ajax ({
url: 'script.php',
type: 'post',
// Convert listOfPrograms to a string first
data: ("listOfPrograms" : JSON.stringify(listOfPrograms)),
success: function(data) {
console.log(data);
}
});
}
jquery will kindly turn array values in ajax post data to an array for you. the issue is that in php you can't just echo an array. as a commenter stated, your php file needs to look like
$myArray = $_Request['listOfPrograms'];
echo json_encode($myArray);
also you should consider using $_POST over $_REQUEST

How to access the serialized data in PHP file in the following scenario?

How to access the serialized data in a PHP file in following situation?
The code and the serialized data is as follows:
$(document).ready(function() { $(document).on('click', '#delete_url', function (e) {
e.preventDefault();
var items = new Array();
$("input:checked:not(#ckbCheckAll)").each(function() {
items.push($(this).val());
});
var str = $("#user_filter").serialize();
$.ajax({
type: "POST",
url: "manage_users.php?op=delete_bulk_users&items="+items,
data: str,
dataType: 'json',
success: function(data) {
//var message = data.success_message;
var redirect_link = data.href;
alert(redirect_link);
window.location.href = redirect_link;
}
});
});
});
The data I'm getting in after serialize in str is as follows:
op=group_filter&page=1&from_date=11%2F10%2F2000&social_login=&to_date=11%2F10%2F2013&login_criteria=all&user_name=&user_state=&user_email_id=&user_city=
Now the PHP file(manage_users.php) is as follows:
/*The code is actually one of the switch casees*/
prepare_request();
$request = empty( $_GET ) ? $_POST : $_GET ;
$op = $request['op'];
switch( $op ) {
case "delete_bulk_users":
print_r($request);/*For printing the received array of values after form submission
Here I'm not getting serialized data */
}
Thanks in advance.
The serialize function is intended to be used to create a query string for a URL from a collection of inputs (or an entire form), and will out of necessity encode characters such as / (which denotes a directory in a URL). There's no way to tell .serialize() to convert to the "proper" format because it already is.
If you're using the result of .serialize() as part of an AJAX request it's fine to do that like so:
$.ajax({
url: 'yourpage.php',
data: str, // the string returned by calling .serialize()
... // other options go here
}).done(function(response) {
// do something with the response
});
Your server should handle decoding those characters when it receives the request and provide the correct values to you.
If you're using it for something else you could try using the native JavaScript decodeURIComponent function to convert those encoded characters back, like so:
str = decodeURIComponent(str);
Note that calling decodeURIComponent and then trying to use it for an AJAX request won't work.
For more information on URI encoding take a read through the MDN entry for encodeURIComponent.

How to convert simple form submit to ajax call;

I have a form with input field which can be accessed like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
and earlier call was
document.forms["algoForm"].submit();
and form was
<form name="algoForm" method="post" action="run.do">
It all run fine
Now I wanted convert it to the ajax call so that I can use the returned data from java code on the same page. So I used soemthing like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
var data = 'algorithm = ' + algorithm + '&input = ' + input;
$.ajax(
{
url: "run.do",
type: "POST",
data: data,
success: onSuccess(tableData)
{ //line 75
alert(tableData);
}
}
);
However the above code doesn't run. Please help me make it run
Let's use jQuery's serialize to get the data out of the form and then use the jQuery's ajax function to send the data to the server:
var data = $("form[name=algoForm]").serialize();
$.ajax({
url: "run.do",
type: "POST",
data: data,
success: function(tableData){
alert(tableData);
}
});
data expects a literal object, so you need:
var data = {
'algorithm': algorithm,
'input': input
};
Instead of retrieving all the parameter value and then sending them separately (which can be done server side as well, using below code), Use this:
var $form = $("#divId").closest('form');
data = $form.serializeArray();
jqxhr = $.post("SERVLET_URL', data )
.success(function() {
if(jqxhr.responseText != ""){
//on response
}
});
}
divId is id of the div containing this form.
This code will send all the form parameters to your servlet. Now you can use request.getParameter in your servlet to get all the individual fields value on your servlet.
You can easily convert above jquery post to jquery ajax.
Hope this helps :)
// patching FORM - the style of data handling on server can remain untouched
$("#my-form").on("submit", function(evt) {
var data = {};
var $form = $(evt.target);
var arr = $form.serializeArray(); // an array of all form items
for (var i=0; i<arr.length; i++) { // transforming the array to object
data[arr[i].name] = arr[i].value;
}
data.return_type = "json"; // optional identifier - you can handle it on server and respond with JSON instead of HTML output
$.ajax({
url: $form.attr('action') || document.URL, // server script from form action attribute or document URL (if action is empty or not specified)
type: $form.attr('method') || 'get', // method by form method or GET if not specified
dataType: 'json', // we expect JSON in response
data: data // object with all form items
}).done(function(respond) {
console.log("data handled on server - response:", respond);
// your code (after saving)
}).fail(function(){
alert("Server connection failed!");
});
return false; // suppress default submit action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I don't know how but this one runs well,
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
$.post('run.do', {
algorithm : algorithm,
input : input
}, function(data) {
alert(data);
}
);

Passing a javascript array to a php page using post method

I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.

howto "submit" a part of a form using jQuery

I'm got a form laid out like a spreadsheet. When the user leaves a row, I want to submit fields from that row to the server using jQuery Ajax. The page is one large form, so this isn't really a javascript clicking the submit button scenario - the form is huge and I only want to send a small portion of the content for reasons of speed.
I've got the code written that identifies the row and iterates through the fields in the row. My issue is how to build the dat object in order to submit something comprehensible I can disassemble and store at the server end.
At the moment my code looks like this
var dat=[];
$("#" + finalrow).find("input").each(function () {
var o = $(this).attr("name");
var v = $(this).val();
dat.push({ o: v });
});
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
The assembling of dat doesn't work at all. So how should I build that dat object in order for it to "look" as much like a form submission as possible.
You can add the elements that contain the data you want to send to a jQuery collection, and then call the serialize method on that object. It will return a parameter string that you can send off to the server.
var params = $("#" + finalrow).find("input").serialize();
$.ajax({
url: 'UpdateRowAjax',
type: 'POST',
data: params ,
success: function (data) {
renderAjaxResponse(data);
}
});
You can use $.param() to serialize a list of elements. For example, in your code:
var dat= $.param($("input", "#finalrow"));
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
Example of $.param(): http://jsfiddle.net/2nsTr/
serialize() maps to this function, so calling it this way should be slightly more efficient.
$.ajax 'data' parameter expects a map of key/value pairs (or a string), rather than an array of objects. Try this:
var dat = {};
$("#" + finalrow).find("input").each(function () {
dat[$(this).attr('name')] = $(this).val();
});

Categories