Making Key Value pair for the form elements in JavaScript - javascript

I have a module where the forms created are dynamic. So the number of inputs can defer always. Also, the array key can also defer.
My current method of posting form is this:
name = form_options[option_1] value = 1
On submitting the form using POST, I get the form as array in $_POST, which looks like this.
form_options(
option_1 => 1
)
But, now I am trying to implement the same thing using AJAX. So, I would need a common module to get all form values.
I found a way to do it.
var objectResult = $('#options_form').serializeArray();
console.log(objectResult);
This gives me a result like this:
0: Object
name: "form_options[option_1]"
value: "1"
How can parse this result to get an array like $_POST array, which I can send as data in AJAX.
P.S: All the form elements have name field as form_options[key]

You should use this for get post data in PHP file.
// You can use like this
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: "POST", // Enter Request type GET/POST
url: 'action.php', // Enter your ajax file URL here,
dataType: 'json', // If you are using dataType JSON then in php file use die( json_encode($resultArray) );
data: objectResult, // Put your object here
beforeSend: function(){
alert('before');
},
error: function(data) {
console.log(data);
},
success: function(response){
console.log(response);
}
});
// In php file get values like this way
$_POST['form_options']

try like this,
In JQuery:
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: 'POST',
url: 'yoururl'',
data: objectResult ,
success:function(data){
alert(data);
}
});
In your php:
<?php echo var_dump($_POST);?>

You can use jquery serialize with ajax directly, there is no need to use serializeArray:
$.ajax({
type:"post",
url:"formHandleSkript.php",
data: $("#options_form").serialize(),
success: function(response){
$(".result").html(response);
}
});
For more information see http://api.jquery.com/serialize/

Related

Jquery get json data from data type dataString

I have the following jquery function which submits data to the database :
$('#book_client_form').submit(function (event) {
dataString = $("#book_client_form").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>operations/book_client",
data: dataString,
success: function (data) {
console.log(data);
$('.job_card_id').val(data[0].id);
$(".info_box_reload").show('slow');
setInterval(function () {
$(".add_new_client_div").hide('slow');
$(".clients_table_div").show('slow');
}, 3000);
}
});
event.preventDefault();
return false;
});
Once the data is supposed to returned the last insert id in json format which gives me the following output :
[{"id":"17"}]
But when I try to pass it to a text field or alert it , I get an undefined output or passes empty. Please advise on how can I pass it to the text input? I'm using datatype : datastring.
did you try parsing the JSON data?
data = JSON.parse(data);
console.log(data[0].id); // you can see the id in the dev console
$('.job_card_id').val(data[0].id);
or you can set dataType : 'jsonp' to get a JavaScript object as response
use dataType, its case sensitive.

send a form with serialize() function and extra data in ajax()

I'm programming a web page for a company in CI3, and I've another problem.
I need to send to wizard.php(controller)a serialized form and a javascript variable, but, I think that I can't send 2 variables at the same time, here is my code.
var idCompany =5;
$(document).on('submit', '#period-form', function(event) {
event.preventDefault();
$.ajax({
url: '<?php echo base_url()?>wizard/insertPeriod/'
type: 'POST',
dataType: 'json',
data: $("#period-form").serialize(),
success : function (json) {
$("#alert").append(json.response_alert);
},
error : function (xhre) {
console.log(xhre);
}
})
});
As you can see, idCompany is an attribute, it has value but, I put value in another function. is possible add values to a serialized form? or how I can send a serialized form and a variable at the same time?
The serialize function simply creates an URL query string from all the form elements. So you can manually add the variable to the result of the serialize() function like this:
data: $("#period-form").serialize() + '&idCompany=' + idCompany
var data = $('#period-form').serializeArray();
data.push({ name: "<somename>", value: "<somevalue>" });
You can use push method to add more name - value pairs.

Ajax Error Potentially Due to Incorrect Data Object Being Passed

Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.

Getting PHP variable to jquery script file by AJAX call

So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results.
My php file is echoing data that should be printed in my results div.
Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??
Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1 on the javascript.
You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so
echo data[0];
which in this case wiill echo the text peiceofdata.
write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({
type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});
Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});

jQuery AJAX with Multiple Array data Parameters

I've successfully posted a single array, but I can't figure out how to send more than one array in an AJAX post. Here is my code for one array:
var a = new Array();
// fill array
var a_post = {};
a_post['array1[]'] = a;
$.ajax({
url: "submitOrder.php",
data: a_post,
type: 'post',
success: function(data) {
alert(data);
}
});
And in submitOrder.php I have:
$array1= $_POST['array1'];
foreach ($array1 as $a => $b)
echo "$array1[$a] <br />";
This works fine. However, when I try to add a second array b_post to the data: field, it doesn't work. I tried data: {a_post, b_post}, and a few variations of that, but I can't get it to work properly. While I'm at it, how would I then load submitOrder.php after posting rather than show an alert of the data?
UPDATE
Using Nicolas' suggestion, I got this to work changing the data field to:
data: {'array1':JSON.stringify(a), 'array2':JSON.stringify(b)},
However, I also need to add the rest of the form data that has been input by the user. I can get this data with $(this).serialize() but if I try to add that to the data field, it does not work. How can I add this data to the above line?
Thanks.
SOLUTION
What ended up working the way I originally had hoped for (with Nicolas' help):
var formData = $(this).serializeArray();
var a_string = JSON.stringify(a);
formData.push({name: 'array1', value: a_string});
var b_string = JSON.stringify(b);
formData.push({name: 'array2', value: b_string});
$.ajax({
url: "submitOrder.php",
data: formData,
type: 'post',
success: function(data) {
alert(data);
}
});
The data should be encapsuled this way
data: {'first_array':JSON.stringify(array1),'second_array':JSON.stringify(array2)}
Then in PHP:
$array1 = json_decode($_POST['first_array']);
$array2 = json_decode($_POST['second_array']);
You can add the rest of the inputs as well.
data: {'first_array':JSON.stringify(array1),'second_array':JSON.stringify(array2),'input1':$(input[name="input1"]).val()}
Just repeat with all the inputs you want to send.
'input1':$(input[name="input1"]).val(),'input2':$(input[name="input2"]).val(),... etc

Categories

Resources