Jquery ajax add variable with serialize [duplicate] - javascript

I want to add extra data after i use $('#myForm').serialize() + extra data
$.ajax({
type: 'POST',
url: $('#myForm').attr('action'),
data: $('#myForm').serialize(), // I WANT TO ADD EXTRA DATA + SERIALIZE DATA
success: function(data){
alert(data);
$('.tampil_vr').text(data);
}
});

What kind of data?
data: $('#myForm').serialize() + "&moredata=" + morevalue
The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.

Personally, I'd append the element to the form instead of hacking the serialized data, e.g.
moredata = 'your custom data here';
// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);
// append to the form
$('#myForm').append($input);
// then..
data: $('#myForm').serialize()
That way, you don't have to worry about ? or &

You can do it like this:
postData[postData.length] = { name: "variable_name", value: variable_value };

Related

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

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.

Making Key Value pair for the form elements in 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/

How to fetch JSON object though JavaScript or jQuery and generate dynamically content for multiple record through JavaScript or jQuery?

Understand already done process for single object and single data, which is working pretty cool.
1) output from the PHP Server encoded into JSON format.
JSON OUTPUT:
{"product_id":"1","sku":"FGDGE43","set":"4","type":"simple","categories":["2"],"websites":["1"],"type_id":"simple","name":"Honey","description":"Where sweetness belong.","short_description":"Sweetness.","weight":"100.0000","old_id":null,"news_from_date":null,"news_to_date":null,"status":"1","url_key":"hgjjhgjh","url_path":"hgjjhgjh.html","visibility":"4","category_ids":["2"],"required_options":"0","has_options":"0","image_label":"Honey","small_image_label":"Honey","thumbnail_label":"Honey","created_at":"2014-02-10 14:36:54","updated_at":"2014-02-19 11:37:07","country_of_manufacture":null,"price":"43.0000","group_price":[],"special_price":null,"special_from_date":null,"special_to_date":null,"tier_price":[],"minimal_price":null,"msrp_enabled":"2","msrp_display_actual_price_type":"4","msrp":null,"enable_googlecheckout":"1","tax_class_id":"0","meta_title":null,"meta_keyword":null,"meta_description":null,"is_recurring":"0","recurring_profile":null,"custom_design":null,"custom_design_from":null,"custom_design_to":null,"custom_layout_update":null,"page_layout":null,"options_container":"container2","gift_message_available":null,"0":{"file":"\/h\/o\/honey.jpg","label":"Honey","position":"1","exclude":"0","url":"http:\/\/127.0.0.1\/magento\/media\/catalog\/product\/h\/o\/honey.jpg","types":["image","small_image","thumbnail"]}}
2) Now
I can fetch above mentioned SINGLE JSON object through jQuery and dynamically change the content of the page.
$(document).ready( function() {
alert('bhoom : oh yea its coming');
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/midserver.php',
data: 'id=testdata',
dataType: 'text',
cache: false,
success: function(data) {
var json = $.parseJSON(data);
$('#pname').html(json.name);
$('#pdesc').html(json.description);
$('#pprice').html(json.price);
$('#pweight').html(json.weight);
},
});
});
This is working fine.
Here come my Question
How can i fetch two or more object through JS or JQ and create dynamic elements though JS/JQ or any other mechanism and then put this data in dynamically generated elements.
i.e : for below mentioned JSON object ?
[{"product_id":"1","sku":"FGDGE43","set":"4","type":"simple","categories":["2"],"websites":["1"],"type_id":"simple","name":"Honey","description":"Where sweetness belong.","short_description":"Sweetness.","weight":"100.0000","old_id":null,"news_from_date":null,"news_to_date":null,"status":"1","url_key":"hgjjhgjh","url_path":"hgjjhgjh.html","visibility":"4","category_ids":["2"],"required_options":"0","has_options":"0","image_label":"Honey","small_image_label":"Honey","thumbnail_label":"Honey","created_at":"2014-02-10 14:36:54","updated_at":"2014-02-19 11:37:07","country_of_manufacture":null,"price":"43.0000","group_price":[],"special_price":null,"special_from_date":null,"special_to_date":null,"tier_price":[],"minimal_price":null,"msrp_enabled":"2","msrp_display_actual_price_type":"4","msrp":null,"enable_googlecheckout":"1","tax_class_id":"0","meta_title":null,"meta_keyword":null,"meta_description":null,"is_recurring":"0","recurring_profile":null,"custom_design":null,"custom_design_from":null,"custom_design_to":null,"custom_layout_update":null,"page_layout":null,"options_container":"container2","gift_message_available":null},[{"file":"\/h\/o\/honey.jpg","label":"Honey","position":"1","exclude":"0","url":"http:\/\/127.0.0.1\/magento\/media\/catalog\/product\/h\/o\/honey.jpg","types":["image","small_image","thumbnail"]}],{"product_id":"2","sku":"asdf654a6sd5f4","set":"4","type":"simple","categories":[],"websites":["1"],"type_id":"simple","name":"Butter","description":"Buttery Buttery Buttery","short_description":"Buttery Buttery ","weight":"100.0000","old_id":null,"news_from_date":null,"news_to_date":null,"status":"1","url_key":"butter","url_path":"butter.html","visibility":"4","category_ids":[],"required_options":"0","has_options":"0","image_label":"butter","small_image_label":"butter","thumbnail_label":"butter","created_at":"2014-02-25 11:35:49","updated_at":"2014-02-25 11:53:10","country_of_manufacture":null,"price":"100.0000","group_price":[],"special_price":null,"special_from_date":null,"special_to_date":null,"tier_price":[],"minimal_price":null,"msrp_enabled":"2","msrp_display_actual_price_type":"4","msrp":null,"enable_googlecheckout":"1","tax_class_id":"0","meta_title":null,"meta_keyword":null,"meta_description":null,"is_recurring":"0","recurring_profile":null,"custom_design":null,"custom_design_from":null,"custom_design_to":null,"custom_layout_update":null,"page_layout":null,"options_container":"container2","gift_message_available":null},[{"file":"\/b\/u\/butter.jpg","label":"butter","position":"1","exclude":"0","url":"http:\/\/127.0.0.1\/magento\/media\/catalog\/product\/b\/u\/butter.jpg","types":["image","small_image","thumbnail"]}]]
So,
what i've tried to create 'dynamic content and putting data in that' is here.
$(document).ready( function() {
alert('bhoom : oh yea its coming');
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/test2.php',
data: 'id=testdata',
dataType: 'text',
cache: false,
success: function(data) {
// asumming that server returns more than one products
// in JSON Object.
// So iterate over this JSON Object through .each JQuery
// function.
var divHtml;
var productDiv = $("#productDetailsDiv");
//its reference
$(data).each(function(index, value) {
// Take Html of productTemplate Div in divHtml variable.
divHtml = $('#productsTemplate').html();
// Fill divHtml with values
divHtml.find('#pname').html(value['name']);
divHtml.find('#pdesc').html(value['description']);
divHtml.find('#pimage').html(value['url']);
divHtml.find('#pprice').html(value['price']);
divHtml.find('#pweight').html(value['weight']);
// Add divHtml to productDiv
$("#productDetailsDiv").children().add(divHtml);
// Loop for next value in data
});
},
});
});
So, Am I making mistake to fetching complicated JSON object or there is a code went wrong with jQuery?
Any help or suggestion will be appreciated.
Regards.
try the block with query $.each
$.each(data, function(index, item) {
$('#pname').html(item.name);
$('#pdesc').html(item.description);
$('#pprice').html(item.price);
$('#pweight').html(item.weight);
});
here pname, pdesc... etc,. you need to update with dynamic elements
You can user jquery each function to achieve this:
$(document).ready( function() {
alert('bhoom : oh yea its coming');
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/midserver.php',
data: 'id=testdata',
dataType: 'text',
cache: false,
success: function(data) {
var json = $.parseJSON(data);
$.each(json, function(index, element){
$('#pname').html(element.name);
$('#pdesc').html(element.description);
$('#pprice').html(element.price);
$('#pweight').html(element.weight);
});
},
});
});
Thanks for your suggestion.
I find out that the JSON object i'm getting through PHP server as an output, is in multi-dimensional array. So for the shake of the simplicity, at server side, we have to generate one-dimensional array of JSON object as an output to be fetched and manipulated at client-side.
Now We can do stuff like generating dynamic content on through JS/JQ on HTML page and render(fill-in) the data with the same.
Regards.

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