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

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']

Related

Unable to send multiple data parameters with jQuery AJAX

I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});

Can't pass String to controller through ajax

I'm new of web development with play framework and ajax,Now I want to pass the string in the form to controller with ajax but I don't know how to do.Could you please help me?Here is my code:
html:
<form onsubmit="return newSearch();" id="formId">
<input type="search" placeholder="Search for more" id="searchBar_chat">
</form>
<script type="text/javascript" >
function newSearch()
{
var s = document.getElementById("chatDialgue");
var searchValue = document.getElementById("searchBar_chat").value;
s.innerHTML = s.innerHTML + '<li>'+ searchValue +'</li>';
document.getElementById("searchBar_chat").value ="";
$.ajax({
url: "DataMatch/searchContentMatch",
type:"GET",
cache: false,
dataType:"text",
data:"searchValue",
success: function (responseData) {
s.innerHTML = s.innerHTML + '<li>'+responseData+'</li>';
}
});
return false;
}
</script>
controller:
public class DataMatch extends Controller{
public String searchContentMatch (String search) {
// Search match
return "HI"+search;
}
}
First of all, in the data parameter of $.ajax() you have to build a query string, so the correct way is concatenating the key ("search") with its value (searchValue).
Then, you don't need neither that return false statement in the script nor the return keyword on the onsubmit form attribute.
Lastly, since you're using jQuery, take advantage of its selection capabilities and replace document.getElementById with $.
<form onsubmit="newSearch();" id="formId">
<input type="search" placeholder="Search for more" id="searchBar_chat">
</form>
<script type="text/javascript" >
function newSearch(){
var searchValue = $("#searchBar_chat").val();
$("#chatDialgue").append('<li>'+ searchValue +'</li>');
$("#searchBar_chat").val("");
$.ajax({
url: "DataMatch/searchContentMatch",
type:"GET",
cache: false,
dataType: "text",
data: "search=" + searchValue,
success: function (responseData) {
$("#chatDialgue").append('<li>' + responseData + '</li>');
}
});
}
</script>
Pass it as a Query Parameter since it is just a single string.
var search="searchValue";
$.ajax({
url: "DataMatch/searchContentMatch?search="+search,
type:"GET",
cache: false,
dataType:"text",
success: function (responseData) {
s.innerHTML = s.innerHTML + '<li>'+responseData+'</li>';
}
});
You should use the Javascript router instead of hardcoding the endpoint in your Javascript code. This will allow you to change the endpoint name later on if needed. Also, you want to pass a query string parameter, so it goes directly in the URL. Here is how to use the reverse route:
#helper.javascriptRouter("jsRoutes")(
routes.javascript.DataMatch.searchContentMatch
)
//HTML here
var endpoint = jsRoutes.controllers.DataMatch.searchContentMatch(searchValue).url;
$.ajax({
url: endpoint,
type:"GET",
cache: false,
success: function (responseData) {
s.innerHTML = s.innerHTML + '<li>'+responseData+'</li>';
}
});
One more thing, to the previous answer, do not forget about parameter in the routes file:
GET /api/search/:search controllers.DataMatch.searchContentMatch(search: String)

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);

Passing a form array to Javascript via PHP using jQuery AJAX

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(']'));

Suppressing and adding parameters for ajax call

I am trying to make an ajax call for two separate click events. The difference is for the second click event the variable testOne should not be part of the call and instead there would be a new variable. How should I approach this?
var varOne = '';
var varTwo = '';
var varThree = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: {
testOne: varOne,
testTwo: varOne
}
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
varOne = 'xyz123';
varTwo = '123hbz';
testAjax();
});
$('.clickTwo').click(function(){
//varOne = 'xyz123'; // I dont need this for this click
varTwo = '123hbz';
varThree = 'kjsddfag'; // this gets added
testAjax();
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
Make some like this
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data= {
varOne: 'xyz123',
varTwo: '123hbz',
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data= {
varThree : 'kjsddfag',
varTwo: '123hbz',
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
You can also do the same in other way with minimum line of code, you can call the ajax on click event and pass the data based on the element triggered the click event.
like this:
$('.ajax').click(function(e){
if($(this).hasClass('clickOne')){
var data= { varOne: 'xyz123'; varTwo: '123hbz'; }
}else{
var data= { varThree : 'kjsddfag'; varTwo: '123hbz'; }
}
$.ajax({
type: "POST",
dataType: 'json',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
e.preventDefault();
});
<div class="ajax clickOne"></div>
<div class="ajax clickTwo"></div>
In this way you can put as many conditions for different data variable.
You should be doing it like this:
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data {
varOne = 'xyz123',
varTwo = '123hbz'
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data = {
varTwo = '123hbz',
varThree = 'kjsddfag'
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
This way you absolute control over which variables are added to which ajax call. You should not use global variables unless you really need them to be global, which doesn't seem to be the case.
You can pass whatever JavaScript object to the data parameter of the ajax method.
I just wanted to add something. I often hide value inside the value attribute of the button tags to produce something like this.
I haven't been able to test this of course but I thought it was worth mentioning.
jquery:
var fields = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: fields
}).done(function(data) {
$('.result').html(data);
});
}
$('#btn').click(function(){
var varCount = 0;
var vars = $(this).val().split('|');
$.each( vars, function( key, value ) {
varCount++;
fields = fields + 'var' + varCount + '=' + value + '&';
});
fields = fields.slice(0,-1);
$(this).val('123hbz|kjsddfag');
testAjax();
});
html:
<button id="btn" value="xyz123|123hbz"></button>
A more optimized and cleaner version -
var varTwo='junk1'
var varOne='junk2'
var varThree='junk3'
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.ajaxClick').click(function(){
var data={};
if(this.classList.contains('clickOne')){
data.varOne=varOne;
data.varTwo=varTwo;
}else{
data.varThree=varThree;
data.varTwo=varTwo;
}
testAjax(data);
});
<div class="ajaxClick clickOne"></div>
<div class="ajaxClick clickTwo"></div>

Categories