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);
Related
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);
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() + "¶meter1=value1¶meter2=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() +
"¶m1="xxx" +
"¶m2="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']
I'm trying to fill two text boxes with a single ajax whisperer. I got the following code:
HTML:
<input type="text" name="ICZ" id="ICZ">
<input type="text" name="ODB" id="ODB">
respond.php:
<?php
require_once("../inc/dbconnect.php");
$return_arr = array();
$term=iconv('UTF-8' ,'WINDOWS-1250',$_GET["term"]);
$SQL="some sql";
$RS=sqlsrv_query($Conn,$SQL);
while($row=sqlsrv_fetch_array($RS)) {
$id_lekar=iconv('WINDOWS-1250', 'UTF-8',$row["ID_LEKAR"]);
$jmeno=iconv('WINDOWS-1250', 'UTF-8',$row["JMENO"]);
$odborn=iconv('WINDOWS-1250', 'UTF-8',$row["ODBORN"]);
$row_array['value'] = $id_lekar;
$row_array['value1'] = $odborn;
$row_array['label'] = $id_lekar." - ".$jmeno." - ".$odborn;
array_push($return_arr,$row_array);
}
sqlsrv_close($Conn);
echo json_encode($return_arr);
?>
and jQuery:
$(function() {$('#ICZ').autocomplete({
source: 'respond.php',
minLength:5
});
});
This works but only affect one input field. I would like to fill both so I extend SQL query and extend respond.php with $row_array['value1']. Then I try to redone jQuery:
$(function() {$('#ICZ').autocomplete({
minLength: 5,
source: function(request, response){
$.ajax({
url: "respond.php",
type: "GET",
dataType: "json",
data: {term: request.term},
success:function(response){
var len = response.lenght;
if (len > 0){
var icz = response[0]['value'];
var odb = response[0]['value1'];
document.getElementById('ICZ').value = icz;
document.getElementById('ODB').value = odb;
}
}
});
}
});
});
But this just doesn't do much, no errors in console, I can see the GET request going on when I fill the field with 5 and more characters, but no response. When I try access respond.php?term=XXXXX I'm getting same response in both ways.
use JSON.parse
$.ajax({
url: "respond.php",
type: "GET",
dataType: "json",
data: {term: request.term},
success:function(response){
var response=JSON.parse(response); // parse json to object
var len = response.length;
if (len > 0){
var icz = response[0].value;
var odb = response[0].value1; //access values like this
document.getElementById('ICZ').value = icz;
document.getElementById('ODB').value = odb;
}
}
});
Look if you need to parse json. Print response in console and check if you need to parse it.
Var result =JSON.parse(response);
Getting JSON Error while calling multiple function
Error - Uncaught SyntaxError: Unexpected token ' in JSON at position 0
I am calling multiple function in jquery but it is giving error i have tried so much way but the error get changed but it not working what should i do.
HTML
<div id="div1">
<input type="submit"onclick='Function1()'>
<input type="text" value="Text1" id="input1">
<input type="text" value="Text2" id="input2">
</div>
<div id='div2'></div>
jQuery
function Function1(){
var input1 = $("#input1").val();
var input2 = $("#input2").val();
var datajson = { "input1" : input1, "input2" : input2 };
var data = "'"+JSON.stringify(datajson)+"'";
Post_Funtion('testpost.php',data,'$("#div2").html(html);')
}
function Post_Funtion(URl,DATA,FUNCTION){
var url = encodeURIComponent(URl);
var data = JSON.parse(DATA);
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(html) {
eval(FUNCTION);
}
});
}
You are trying to JSON.stringify() the post data incorrectly, then turning around and parsing it back to pass to the ajax options.
This whole step is needless. Pass the object through as is and jQuery will take care of it from there
function Function1(){
var input1 = $("#input1").val();
var input2 = $("#input2").val();
var data = { "input1" : input1, "input2" : input2 };
Post_Funtion('testpost.php',data,'$("#div2").html(html);')
}
function Post_Funtion(URl,DATA,FUNCTION){
var url = encodeURIComponent(URl);
$.ajax({
data: DATA,
/* other options the same */
....
}
You are trying to call JSON.parse on a string that looks like this:
'{"input1": input1, "input2": input2}'
That is not well-formed JSON. The outer quotes should be dropped. Try this code:
function Function1(){
var input1 = $("#input1").val();
var input2 = $("#input2").val();
var datajson = { "input1" : input1, "input2" : input2 };
var data = JSON.stringify(datajson) // Removed quotes from JSON
Post_Funtion('testpost.php',data,'$("#div2").html(html);')
}
function Post_Funtion(URl,DATA,FUNCTION){
var url = encodeURIComponent(URl);
var data = JSON.parse(DATA);
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(html) {
eval(FUNCTION);
}
});
}
"'"+JSON.stringify(datajson)+"'"; - remove quotes
var data = JSON.stringify(datajson);
Can't see the reason of stringifying and parsing the object back in this case. Try the following:
function Function1(){
var input1 = $("#input1").val();
var input2 = $("#input2").val();
var data = { "input1" : input1, "input2" : input2 };
function cb(response){
$("#div2").html(response);
}
Post_Funtion('testpost.php',data, cb)
}
function Post_Funtion(URl,DATA,FUNCTION){
var url = encodeURIComponent(URl);
console.log(DATA);
$.ajax({
type: "POST",
url: url,
data: DATA,
cache: false,
success: FUNCTION
});
}
PS don't use eval, Why is using the JavaScript eval function a bad idea?
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(']'));