jQuery AJAX with Multiple Array data Parameters - javascript

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

Related

How can I refresh a PHP file with itself using Ajax?

Alright guys I'm trying to make a filter system for posts using ajax and a select box. I am able to get the value from the select box no problem. But my issue is that when I try to include the selected value in my PHP file it doesn't do anything. I have a file called public_wall.php. This file contains PHP, Javascript, and HTML. How can I refresh this div whenever a user selects a different filter option? Basically I need the selected value to be passed onto my public_wall.php file and then I want to plug it into the PHP function that fetches the posts thats's in the same file and then I want to refresh that same file to display the filtered results. Here is my Javascript code.
$("#postRatings").on("click", function(e) {
selectedRatingFilter = $("#postRatings option:selected").val();
var dataString = "timeFilter="+selectedRatingFilter;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response){
hideSpinner();
jQuery('#postsPagingDiv').remove();
jQuery('#wsc_midbox').html(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
jQuery('#paging_in_process').val(0);
}
});
});
When the dataType is set to "json" nothing happens. But when it is set to html it prints some javascript code. Please help. The PHP file is too large to include here, but it basically contains PHP, HTML, and Javascript and some PHP functions that do sql queries. What is the best way to achieve a filter mechanism for my setup?
And on the public_wall.php file I want to get the value like so:
$ratingFilter = isset($_REQUEST['timeFilter']) ? intval($_REQUEST['timeFilter']) : 0;
And then plug it into the PHP function that fetches the posts which is in the public_wall.php file also so that I can filter the posts based on the selected value. And then finally I want to refresh the public_wall.php file with the new results. I hope that makes sense. Please help.
This is the output when I set my dataType to "html"
<script>
function refreshPosts() {/* only posts comments likes and count updated. */
var posts = jQuery("#all_post_id").val();
var arrays = posts.split(',');
var dataString = "postids="+posts;
jQuery.ajax({
type: "POST",
url: site_url+"includes/update_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
var x = response;
//############ skip posts whose comments are being read by users
var ExemptedPostsIDs = jQuery("#exemptedPostsID").val();
var ExemptedArray = ExemptedPostsIDs.split(',');
ExemptedArray = ExemptedArray.sort();
//////////////
for (i=0; i<arrays.length; i++) {
var val = 'row'+arrays[i];
if(x[val]) {
if(!inArray(arrays[i], ExemptedArray))
jQuery("#ajax_wall_"+arrays[i]).html(x[val]);
} else {
jQuery('#PostBoxID'+arrays[i]).parent().fadeOut(500);
}
}
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function refreshWall() {/* loads new posts real time */
var posts = jQuery("#all_post_id").val();
var pageUsing = jQuery('#pageUsing').val();
var dataString = "update_posts=1&postids="+posts+'&pagex='+pageUsing;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
if(response.all_post_id) {
jQuery('#wsc_midbox').prepend(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
}
}
});
}
</script>
I suggest you keep the form with select element and any JavaScript on the outer frame.
Via ajax, only load the results to a seperate DIVision below that.
When you put an Ajax response to a div, any JavaScript inside it will not be executed.
For the best throughput with Ajax, you should consider loading a json response via Ajax and create HTML elements on the client side. That way it becomes much easier to pull additional variables to front-end JS from server side along with the same request/response.
But that becomes bit difficult when you have a template engine in the back-end. You can still send the HTML content in a json value, so you can easily pass the "all_post_id" as well..

Submit form data as JSON

I have to recreate a form that was originally created using Jotform - it is here. I am struggling in one area. It is a pretty simple form, the only caveat being the ability to duplicate a form field form multiple entries. That part can be seen here. When the form is duplicated, I need to submit the form data as a JSON array. In the fiddle, I didn't put the regular form fields, here is how they and the cloned field need to submit the data.
q2_fullName[first]:test
q2_fullName[last]:test
q1_currentCommission1:[{"Instruments":"a","Commissions":"1","Margins":"a"},{"Instruments":"b","Commissions":"2","Margins":"b"},{"Instruments":"c","Commissions":"3","Margins":"c"}]
normally in my $.ajax handler, I just serialize the data, but that doesn't work in creating the json array for the cloned fields. Normally like so:
submitHandler: function(form) {
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url: form.action,
data: dataString,
dataType: "json",
beforeSend: function(data){
//before send
},
success: function(data){
//success function
}
});
return false;
},
I need to somehow serialize the non cloned fields (I think) and create a json array out of the cloned values and assign them a key name
You can build the post data and the json string like this :
var data = {
// get/set the firstname etc
"q2_fullName":{
"first":"", // get firstname ie $("#first_2").val(),
"last":""
},
"q1_currentCommission1" :""
},
commisions = [];
$('.InsContain').each(function() {
var $inputs = $(this).find('input');
commisions.push({
"Instruments" : $inputs.eq(0).val(),
"Commissions" : $inputs.eq(1).val(),
"Margins" : $inputs.eq(2).val()
});
});
data.q1_currentCommission1 = JSON.stringify(commisions);
Posted data :
q2_fullName[first]:aaa
q2_fullName[last]:123
q1_currentCommission1:[{"Instruments":"1","Commissions":"1","Margins":"1"}]
Update fiddle here

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/

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.

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.

Categories

Resources