Simplify ajax Object - javascript

I have this function to write the inputs from a form to the database and i'm trying to simplify the data being passed by the ajax call to the php. Currently i have this function:
function writeDB(stage){
var userData = $("#cacheDB").find("input").get();
var ajaxData = []
for (var n=0;n < userData.length; n++){
item = {};
item[userData[n].id] = userData[n].value;
ajaxData.push(item);
}
$.ajax({
url: "x.php",
data: {ajaxData},
});
}
Which sends out this object:
http://url.php?ajaxData[0][pageid]=1&ajaxData[1][input1]=John&ajaxData[2][input2]=Doe
I would like to send only the original data key, like:
http://url.php?[pageid]=1&[input1]=John&[input2]=Doe
Or
http://url.php?pageid=1&input1=John&input2=Doe
Is it posible? I've tried several methods and havn't found one suitable yet.

I would try to serialize the form instead of that for loop. It basically sends all input fields from your form as a JSON object to the server.
$.post('server.php', $('#theForm').serialize())
For larger form, HTTP POST method should be prefferd, you can send complicated object.
Check this for more help: jQuery AJAX submit form
Hope its what you need.

Related

How to pass a JavaScript array as parameter to URL and catch it in PHP?

I have an array in JS and I am trying to pass it as parameter to URL and catch it in PHP but I cant get to understand how to do it:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
FYI: I am using windows.fetch for posting.
in PHP:
$trafficFilters = $_GET["trafficFilters"];
$obj = json_decode($trafficFilters);
var_dump($obj);
You are passing the data to php with fetch() intead of ajax, so the alternative of my first answer to do the same with the fetch() is:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var trafficFilterHolderJoin = trafficFilterHolder.join(); // comma-separeted format => "roadworks,snow,blocking"
Now add the trafficFilterHolderJoin variable to the traffic query of the URL of your fetch(), like:
fetch('script.php?traffic=' + trafficFilterHolderJoin)
Then in your php script file you will convert the comma-separeted format to php array format using the explode function:
$traffic = explode(",", $_GET['traffic']);
It's quite simple, you are passing these data to php with ajax, correct?
First of all, you are creating the javascript array incorrectly:
var trafficFilterHolder = [0: "roadworks", 1: "snow", 2: "blocking"];
Don't use brackets to create arrays with keys, use this format instead:
var trafficFilterHolder = {0: "roadworks", 1: "snow", 2: "blocking"};
Now, in the ajax, just add the array in the data:
$.ajax({
data: { trafficFilters: trafficFilterHolder }
});
All demands to the server are executed as an http requests. Ther are two types of HTTP requests - GET and POST.
https://www.w3schools.com/tags/ref_httpmethods.asp
What you're describing is called GET request. With GET request the parameters are passed via the address bar. For making an http request you have two options.
The direct HTTP GET request.
For this you need simply open a new page with
window.location.href = 'http://your_site.com/file.php?name1=value1&name2=value2'
This will open a new page in your browser and pass a request with your parameters.
An Ajax HTTP GET request.
You have a lot of options here:
an old-fashion way with xmlHttpRequest object
a modern fetch API with promises
third-part libraries like jQuery.ajax etc.
AJAX request can send and receive information from the server (either in GET or POST request) without renewing the page. After that the result received can be managed with your javascript application however you want.
Hope, it makes more clear for you. You can search about all this technologies in the google. This is the way how to exchange data from front-end to back-end.
Try using ajax and pass that array and retrieve values at the PHP end.
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
$.ajax({
type: "POST",
url: "test.php",
data: {data : filters},
cache: false,
success: function(){
alert("OK");
}
});

Javascript Associative Array cant post via php

Iam trying to post an Javascript Object via php, but i cant get the value in PHP, iam using laravel framework.
my array,
[type: "sadf", level: "sadfasdf"]
javascript code,
var data_push = Array();
$('form').on('change', 'select, textarea, input', function(t,s){
var key = $(this).attr('id');
var value = $(this).val();
data_push[key] = value;
});
$("#submit").click(function(){
$.post("{!! URL::to('test') !!}", {
_token : tempcsrf,
req_data : data_push
},
function (resp, textStatus, jqXHR) {
alert(resp);
});
});
php code,
public function workbook_save(Request $request_data)
{
$require_data = $request_data->req_data;
print_r($require_data);
}
Tried also JSON.stringfy(data_push) ,json_decode but no luck, i cant get the Javascript object in php, donno what iam doing wrong here, pls advice.
This is what your JS does:
Creates an array
Sets up an event handler to populate the array when things change in the form
Posts the (empty) array to the server
Later on, things will change in the form and data will be put in the array.
The server knows nothing about this because you already sent its contents.
You need to change your logic so you only make the POST request when you are ready to send the data.

populating a form from an ajax call

Im retrieving some json data from an mvc controller and I want to edit it in a form. Imhaving trouble actually populating the form with the returned data. There is only one row of data, with three properites. Ive checked the data being returned and it is there but whenever I try to set the form value to the json data value, it just falls over. My ajax call compltes ok, i get data back, but I just cant seem to put it into the form. heres the bit in my ajax call that im trying to make work
success: function (data) {
var frm = $("#frmAddDisclaimer");
if ("Disclaimer_ID" in frm.elements) {
frm.elements["Disclaimer_ID"].value = data.ID;
}
if ("Disclaimer_DisclaimerRef" in frm.elements) {
frm.elements["Disclaimer_DisclaimerRef"].value = data.DisclaimerRef;
}
if ("htmlEditorDisclaimer_source" in frm.elements) {
frm.elements["htmlEditorDisclaimer_source"].value = data.DisclaimerText;
}
ive checked the form.elements contents at runtime, and those are the correct ID's and data has corresponding data in each 'property' as well
frm is a jquery object, it has no elements property.
What you're looking for is the fom element inside it, you can expose it via square bracket notation $("#frmAddDisclaimer")[0] or just use document.querySelector
var frm = document.querySelector("#frmAddDisclaimer");

Get a form's key value pairs when submitting with ajax [duplicate]

This question already has answers here:
How to post a form with many fields with jQuery?
(7 answers)
Closed 8 years ago.
When a form is submitted I will prevent the default action and instead make an ajax call with the POST data. How can I get all of the data so I can pass it along with my ajax call?
When a form element is submitted normally with the post method, it easily assembles all the name => value pairs in the form. Unfortunately now that I am doing ajax, it looks like I need to assemble this myself. I really don't want to write JS to loop through a form and construct my own hash, I'm assuming there is an easier way with jQuery or some behavior I'm not thinking of.
A JS fiddle example of a form where I would need all values.
http://jsfiddle.net/rm9KD/
Use jQuery serialize()
$.ajax({
url: url,
data: $("form").serialize()
}
);
As you did not provide specific code, this is just an example for you to fill in
jQuery provides a serializeArray function that will serialize the form data into an array. You can then take the resultant array and create a data object out of it.
var arrayData = $('#myForm').serializeArray(),
data = {},
i = 0;
for(; i < arrayData.length; i++) {
data[arrayData[i].name] = arrayData[i].value;
}
Alternatively, jQuery provides as serialize function that provides a serialized string of the form data.
var data = $('#myForm').serialize();
http://jsfiddle.net/WfrM4/
$(document).ready(function () {
$('form').submit(function (e) {
// Dont trigger a page load on submit.
e.preventDefault();
// Get all the values of the form???
var form_data = $('form[name="my_awesome_form"]').serialize()
// Make an ajax call
$.ajax({
url: "/ajax_form_receiver",
data: form_data
});
});
});

how to send and get query parameters in jquery

Hi I am quite new to jquery and web programming in general.
My question is how to send hidden query parameters using a post request in jQuery and Retreive the data from the post request in another. I know that there are a lot of tutorials on .post in jQuery but I cant seem to find any on .get requests (if that is what I need here)
For example in one .js file for one page I have
$.ajax({
type: 'POST',
url: 'url',
data: {
'startDate': this.options.startDate,
'endDate': this.options.endDate,
'selectedReport': this.options.endDate,
},
success: function (msg) {
alert('wow' + msg);
}
});
but in another js file for another page I want to have like a get request that retrieves these parameters.
Could anyone explain how would I write this get request in the js file to retrieve them?
Thank you for the help
It seems to me that POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
.ajax() POST data is send as query string parameters. In the other page you can write javascript to fetch these query string values.Below is sample to read query string values:
(function ($) {
$.QueryString = (function (a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i) {
var p = a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'))
})(jQuery);
You can the above function like below:
var startDate=$.QueryString["startDate"];
https://api.jquery.com/jQuery.ajax/
With your current function you are sending POST data to the otherside.
For example, in PHP, data sent will be in the $_POST array.
To set a GET request you just have to set type from POST to GET
type: 'GET'
Then on the PHP side data sent will be in $_GET array.
I realized that JavaScript post request like a form submit answers my questions because it is more client side although the ajax is server side. thank you for all of the help!

Categories

Resources