Passing a form array to Javascript via PHP using jQuery AJAX - javascript

I'm submitting a form via AJAX and utilising jQuery and I need to find out how I cna pass form arrays to it.
For example, my html would be something like:
<input id="standard_field" type="text" name="standard_name">
<input id="some_id_1" type="text" name="my_array[my_name_1]">
<input id="some_id_2" type="text" name="my_array[my_name_2]">
<input id="some_id_3" type="text" name="my_array[my_name_3]">
Now I know you can easily get the name of the standard field in jQuery using something like:
var foo = $('standard_field').val();
But I'm not sure how to get the array data? Also, it needs to be passed to the PHP script from ajax in exactly the same way the PHP script would get it as if the form was submitted without ajax.
So an example of how I would normally pass data:
var foo = $('standard_field').val();
var loadUrl = "some_script.php";
var dataObject = { foo: foo };
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
//..........
})
.fail(function() {
//......
});
// End
function getAjaxData(loadUrl, dataObject, action, type) {
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
So firstly how can I get the data to pass from the form and secondly how can I pass it from jQuery to the PHP script so PHP get's it as an array like it would if it was POST'ed straight to the PHP script?

You should use serialize
HTML:
<form id="form1" action="" method="post">
<input id="standard_field" type="text" name="standard_name">
<input id="some_id_1" type="text" name="my_array[my_name_1]">
<input id="some_id_2" type="text" name="my_array[my_name_2]">
<input id="some_id_3" type="text" name="my_array[my_name_3]">
</form>
JS:
var dataObject = $('#form1').serialize();
var loadUrl = "some_script.php";
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
//..........
})
.fail(function() {
//......
});
// End
function getAjaxData(loadUrl, dataObject, action, type) {
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}

You can use this plugin http://malsup.com/jquery/form/
Example code:
JS:
$('#your_button').change(function() {
var options = {
url: 'your_url',
type: 'POST',
dataType: 'json',
beforeSubmit: function() {
// Callback function to be invoked before the form is submitted
},
success: function(data) {
// Callback function to be invoked after the form has been submitted
},
error: function() {
// Callback function to be invoked upon error
}
};
// do something
});
PHP:
var_dump($_POST);

You can use the String.slice method to extract the label name.
var input = $('#myform input');
var data = [];
var name, label, value = '';
for(var i in input) {
name = input.eq(i).attr('name');
label = name.splice(9, -1);
value = input.eq(i).val();
data[label] = value;
}
data = JSON.stringify(data);
And for detect when it's an array you can user String.indexOf('[') like
For an unknown array structure :
array_name = name.splice(0, name.indexOf('['));
label = name.splice(name.indexOf('['), name.indexOf(']'));

Related

Getting data sent with Ajax from php?

sorry if this has been asked many times but I can't get it to work.
I'm trying to build a restful website, I have a simple form:
<form action="/my/path" method="post" id="myformid">
Name <input type="text" name="name">
<input type="submit" value="Test">
</form>
I convert the data the user inputs using Javascript and I send them to my php file using Ajax:
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
const json = JSON.stringify($("#myformid").serializeArray());
$.ajax({
type: "POST",
url: "/my/path",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And I tried reading the data on php like:
$data = json_decode(file_get_contents('php://input'), true);
$name = $data["name"];
The code works perfectly if I send a JSON in the request body using a tool like Postman, but from what I tested using Ajax the json data arrives as POST data, and I can read it using $_POST["name"], but non with the 'php://input' as I did.
How can I fix it so the JSON gets accepted even sent via Javascript?
Hi you can try like this:
First I use an id attribute for each input i dont really like to serialize stuff but thats me you can do it your way here are the files.
your index.php:
<form method="post" id="myformid">
Name :<input type="text" id="name" name="name">
<input type="submit" value="Test">
</form>
<br>
<div id="myDiv">
</div>
your javascript:
//ajax function return a deferred object
function _ajax(action,data){
return $.ajax({
url: 'request.php',
type: 'POST',
dataType: 'JSON',
data: {action: action, data: data}
})
}
//your form submit event
$("#myformid").on('submit', function(event) {
//prevent post
event.preventDefault();
//validate that name is not empty
if ($("name").val() != "") {
//parameters INS is insert data is the array of data yous end to the server
var action = 'INS';
var data = {
name: $("#name").val()
};
console.log(data);
//run the function and done handle the function
_ajax(action,data)
.done(function(response){
console.log(response);
//anppend name to the div
$("#myDiv").append("<p>"+response.name+"</p>");
});
}
});
your request.php file:
<?php
//includes and session start here
//validate that request parameters are set
if (isset($_POST["action"]) && isset($_POST["data"])) {
//getters
$action = $_POST["action"];
$data = $_POST["data"];
//switch to handle the action to perfom maybe you want to update with the form too ?
switch ($action) {
case 'INS':
// database insert here..
//return a json object
echo json_encode(array("name"=>$data["name"]));
break;
}
}
?>
Results:
Hope it helps =)
From the documentation of .serializeArray().
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string.
And in the example given in the same page, it is clear that you will get an array in php,
to access an element, you should try-
`$data[0]['name']`
Also, have you tried print_r($data), is it NULL??
Change your ajax codes
$('#btnSubmit').on('click', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/new.php",
data: $("#myformid").serialize(),
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Also you need some changes in form
<form action="new.php" method="post" id="myformid">
Name <input type="text" name="name">
<input id="btnSubmit" type="button" value="Test">
And you can get POST data in php file like $_POST['name']
You can set directly form serialize in ajax request to send params
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/my/path",
data: $("#myformid").serialize(),
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And you can get POST in your PHP using $_POST
print_r($_POST);

Modify result of .serialize() on the fly [duplicate]

Is it possible to send form elements (serialized with .serialize() method) and other parameters with a single AJAX request?
Example:
$.ajax({
type : 'POST',
url : 'url',
data : {
$('#form').serialize(),
par1 : 1,
par2 : '2',
par3: 232
}
}
If not what's the best way to submit a form together with other parameters?
Thanks
serialize() effectively turns the form values into a valid querystring, as such you can simply append to the string:
$.ajax({
type : 'POST',
url : 'url',
data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}
Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:
var data = form.serialize() + '&' + $.param(object)
See http://api.jquery.com/jQuery.param for further reference.
I dont know but none of the above worked for me, Then i used this and it worked :
In form's serialized array it is stored as key value pair
We pushed the new value or values here in form variable and then we can pass this variable directly now.
var form = $('form.sigPad').serializeArray();
var uniquekey = {
name: "uniquekey",
value: $('#UniqueKey').val()
};
form.push(uniquekey);
If you want to send data with form serialize you may try this
var form= $("#formId");
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()+"&variable="+otherData,
success: function (data) {
var result=data;
$('#result').attr("value",result);
}
});
$("#add_form").submit(function(e) {
e.preventDefault();
var total_qty = $('#total_qty').text();
var total_amt = $('#total_amt').text();
$("#add_btn").val('adding....');
$.ajax({
url: 'action.php',
method: 'post',
data: $(this).serialize() + "&total_qty="+total_qty + "&total_amt="+total_amt,
success: function(data){
console.log(data);
}
});
});
pass value of parameter like this
data : $('#form_id').serialize() + "&parameter1=value1&parameter2=value2"
and so on.
Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:
// ...
url: "MyUrl", // For example --> #Url.Action("Method", "Controller")
method: "post",
traditional: true,
data:
$('#myForm').serialize() +
"&param1="xxx" +
"&param2="33" +
"&" + $.param({ paramArray: ["1","2","3"]}, true)
,
// ...
encode in js :
var temp = $("#pay_property_amount").serialize();
temp = btoa(temp);
and pass in ajex
data: { temp_data : temp },
decode in php
$temp_data = base64_decode($this->input->post('temp_data'));
if($temp_data){
$temp_data = $this->unserializeForm($temp_data);
}
function unserializeForm($str) {
$returndata = array();
$strArray = explode("&", $str);
$i = 0;
foreach ($strArray as $item) {
$array = explode("=", $item);
if (preg_match('/(%5B%5D)/', $array[0])) {
$array[0] = str_replace('%5B%5D','',$array[0]);
if(array_key_exists($array[0],$returndata)){
$returndata[$array[0]][]=$array[1];
}else{
$returndata[$array[0]] =array();
$returndata[$array[0]][]=$array[1];
}
}else
{
$returndata[$array[0]] = $array[1];
}
}
return $returndata;
}
Those who want to add new data to form data can use this method.
Exemple:
$("form#myForm").submit(function(e){
e.preventDefault();
let formData = jQuery("#myForm").serializeArray();
let newData = [
{name:"city", value: "Ankara"},
{name:"jobs", value: "Full-Stack Web Developer"},
{name:"action", value: "ajax_proccess"}
];
let postData = formData.concat(newData);
console.log(formData);
console.log(newData);
console.log(postData);
jQuery(".alert").text("İş: " + postData[4]['value']);
jQuery.ajax({
url: jQuery("#myForm").attr('action'),
type: 'POST',
dataType: 'json',
data: postData,
success: function(data) {
//let response = JSON.parse(data);
console.log(data);
alert('Submitted.');
jQuery(".alert").text(newData[5]);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="" id="myForm">
<input type="hidden" name="name" value="Mahmut Yüksel">
<input type="hidden" name="surname" value="Mert">
<input type="hidden" name="countary" value="Turkey">
<input type="submit" value="Gönder">
</form>
<div class="alert">İş: </div>
You can also use serializeArray function to do the same.
You can create an auxiliar form using jQuery with the content of another form and then add thath form other params so you only have to serialize it in the ajax call.
function createInput(name,value){
return $('<input>').attr({
name: name,
value: value
});
}
$form = $("<form></form>");
$form.append($("#your_form input").clone());
$form.append(createInput('input_name', 'input_value'));
$form.append(createInput('input_name_2', 'input_value_2'));
....
$.ajax({
type : 'POST',
url : 'url',
data : $form.serialize()
}
I fix the problem with under statement ;
send data with url same GET methode
$.ajax({
url: 'includes/get_ajax_function.php?value=jack&id='+id,
type: 'post',
data: $('#b-info1').serializeArray(),
and get value with $_REQUEST['value'] OR $_GET['id']

How can i post data and file by using ajax on event onclick

HTML here.
<form id="myForm">
<input type="text" name="name">
<input type="file" name="userImage">
<button onclick="post('./example.php')" type="button">Save</button>
</form>
Now i want to post it by using post() function
Java-script:
Function post(url){
$.ajax({
url:url,
type: 'POST',
data: $("#myform").serialize(),
success: function (data) {
alert("successfully posted.");
}
});
}
But not serialized file
My advice is: try to have apart html and js defining the event callback on "attacheventlistener" function or "on" jquery's function (this way is easier).
Your problem is that you are passing the string "url" when you need pass a valid url, so write the url directly on ajax url field or define a data attribute on your form tag, e.g. data-url="http://whatever", and catch this value from the event.
If you use jquery's "on" function is extremly easy, you could to get it data's value via jquery's "data" function over "this" var.
Something like ...
$("#myForm").on("click",
function() {
post(this.data("url"));
});
But probably you do not need url being a var.
If I understand correctly, the problem is that nothing is being posted.
The thing is is that you are trying to do a file upload via ajax, this is not wrong but it needs to be done differently shown here:
jQuery Ajax File Upload
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
});
First of all i need to say that, if you want to upload file, i mean if your form have file input then add the form attribute enctype="multipart/form-data" according to RFC-7578. you can also see the uses http://www.w3schools.com/tags/att_form_enctype.asp.
Then move to the html part again. Suppose you have a form input like
<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileId"/>
<input type="text" name="firstName" id="name">
<button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>
Now post the file data using ajax:
function post(url){
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: $('#fileId')[0].files[0],
success: function (data) {
alert("successfully posted.");
}
});
}
I think this should be worked fine.
UPDATE:
if you want to post text data as well then you should use FormData object.
function post(url){
var formData = new FormData();
var files = document.getElementById("fileId").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: formData,
success: function (data) {
alert("successfully posted.");
}
});
}

Javascript Circular reference exception

I am trying to update the description field for a record in a database using a JQuery.change for the input on the view. However, after wiring up my clientside code I am now getting a circular reference exception when trying to stringify the JSON in order to make the ajax call. Any help would be greatly appreciated.
Here's the code:
<div class="divTableCell">
<label for="CheckRunDescription" id="checkRunDescriptionLabel">Description:</label>
<input type="text" id="CheckRunDescription" style="width: 270px;" />
</div>
The JQuery:
$('#CheckRunDescription')
.change(function() {
$(this).data("old", $(this).data("new") || "");
var newDetails = $(this).data("new", $(this).val());
updateCheckRunDetails(newDetails);
});
function updateCheckRunDetails(newDetails) {
var checkRunID = $('#checkRunID').val();
var js = JSON.stringify({ checkRunDetails:newDetails, checkRunID:checkRunID });
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: './PayInvoicesWS.asmx/UpdateCheckRunDetails',
data: js,
dataType: "json",
success: function (data) {
},
error: function (data) {
}
});
}
You are trying to stringify a jQuery object.
var newDetails = $(this).data("new", $(this).val());// returns `$(this)`
I am guessing you want the input value passed to the function
Try
$('#CheckRunDescription')
.change(function() {
var newDetails = $(this).val();
$(this).data("old", $(this).data("new") || "").data("new", newDetails );
updateCheckRunDetails(newDetails);
});

Form convert to wrong json format

I have a login form and I want to send a Post which contains a json.
Here is what I've done so far.
<form id="myForm">
Login
<input id="login" type="text" name="login" value=""/>
Password
<input id="password" type="password" name="password" value=""/>
<button type="submit" >Login</button>
</form>
and my js file
$("#myForm").submit(function(event) {
var frm = $("#myForm");
var data = JSON.stringify(frm);
event.preventDefault();
$.ajax({
url: "/register/",
data: data,
type: "POST",
contentType: "application/json"
});
});
Here is jsfiddle https://jsfiddle.net/p143s6tp/
I expected json to look like this :
{
"login" : "some_value",
"password" : "some_value"
}
but I got this :
{"0":{"0":{},"1":{},"2":{}},"length":1,"context":{"location":{}},"selector":"#myForm"}
I read some topics where people use .serializeArray() , but as a result I got array of single objects
You are stringifying the form jQuery object returned by the selector $("#myForm");.
.serializeArray() would yield the output in the following format (name,value pairs),
[{"name":"login","value":"test"},{"name":"password","value":"test"}]
You can modify the output returned by .serializeArray().
var frm = $("#myForm");
var formData = frm.serializeArray();
var data = {};
$.map(formData, function (obj,i) {
data[obj['name']] = obj['value'];
});
Applying JSON.stringify() will yield:
{"login":"test","password":"test"}
Updated Fiddle
The simplest way:
JS
var login = $('#login').val();
var password = $('#password').val();
$("#myForm").submit(function(event) {
$.ajax({
url: "/register/",
data: {'login':login,'password':password},
type: "POST",
success: function(data) {
alert(data);
}
});
});
PHP
$login = $_POST['login'];
$password = $_POST['password'];
echo 'login:' . $login . ' - password: ' . $password;
$("#myForm").submit(function(event) {
var frm = $("#myForm");
var data = frm.serialize();
event.preventDefault();
$.ajax({
url: "/register/",
data: JSON.stringify(data),
type: "POST",
contentType: "application/json"
});
});
As yourself noted, you have to use .serializeArray(). It returns array of names and values which you can convert to desired format using Array's methods.
Something like this:
var data = {};
frm.serializeArray().forEach(function(el) {
data[el.name] = el.value;
});
var json = JSON.stringify(data);

Categories