Javascript array conversion to jQuery.post's data - javascript

I am trying to send different values to php script using jQuery.post
The data I want to send are links like this
http://example.com/image1.jpg
http://example.com/image2.jpg
http://example.com/image3.jpg
http://example.com/image4.jpg
I don't have an exact amount of these links they would vary depending on the user interacting with my script
I am storing these links in a javascript array "fileLinks".
what I want to do is to send these links to php using jQuery.post
Can I format these links in this shape?
jQuery.post(MyAjax.ajaxurl,
{ action : 'ajax-rform',
link1: http://example.com/image1.jpg,
link2: http://example.com/image2.jpg,
link3: http://example.com/image3.jpg,
link4: http://example.com/image4.jpg,
},
function(data){
jQuery("#fileupload").after('<h1>Success</h1><p>Your registration has been recieved.</p>');
}
);
In php I just need to use for loop and replace the link1 and http://example.com/image1.jpg with the arrays and php would iterate it for me but what should I do in javascript?
Thanks

Just pass the array. jQuery will encode it with array notation, and PHP will decide it back into an array:
jQuery.post(MyAjax.ajaxurl,
{ action : 'ajax-rform',
link: fileLinks
},
function(data){
jQuery("#fileupload").after('<h1>Success</h1><p>Your registration has been recieved.</p>');
});
In PHP, you can access the array as $_POST['link'].

Why not just create a json array and then use php's json_decode method?

Perhaps you should just make a data object to send, populate it from your array like this
var postData = { action : 'ajax-rform' };
for(var i = 0; i < fileLinks.length; i++){
postData["link"+(i+1)] = fileLinks[i];
}
And then use that in your ajax
jQuery.post(MyAjax.ajaxurl,
postData,
function(data){
jQuery("#fileupload").after('<h1>Success</h1><p>Your registration has been recieved.</p>');
}
);

Related

Store an array to WordPress database

I created an application that's hosted in a WordPress website that allows everything on the page to be customized. How can I store an array with a user-defined ID to the WordPress database when the user clicks Save? The user can then go to their "Customized Pages" page and view all of their customized pages named as the ID they set when initially saving. On clicking on one of their customized pages, it will load the customizable page with the array associated to the ID that they set.
Edit
Gone with the JSON Encode method. Here is where i am at.
var array = [];
$('img').click(function(){
var id = $(this).attr('id');
array.push(id);
});
$('#sendQuote').click(function(e) {
e.preventDefault();
$.ajax({
url:"readJson.php",
method: "post",
data: { myBuild: JSON.stringify( array ) },
success: function(res){
console.log(res);
}
})
});
ReadJson.php
$array = $_POST['myBuild'];
print_r($array);
global $wpdb;
Any ideas in posting this to wp_meta or a custom table?
You have 2 options.
Encode the array as json using json_encode and then decode it for use using json_decode
Serialize the array via serialize and unserialize via unserialize

Store HTML array values into javascript array to be sent via AJAX

I have a form, in which I am able to clone a table row. Each form element is is named as an array with [] after the name. This is no big deal if I am sending the form directly to a PHP script. I do not wish to refresh so I need to store the values in a javascript array then send that array to my php script etc. I am having a difficult time creating a NEW javascript variable that is an array of all the values.
One this is complete I'm sure requesting it in PHP is pretty straight forward.
Here is an example of my HTML form.
<form class="form8" name="formfine">
<table class="tablesorter2" cellspacing="0" id="adddate">
<tbody>
<tr>
<td>Expense:</td>
<td>
<select id="fineexpense" name='fineexpense[]'>
<option value='Mortage/Rent'>Mortage/Rent</option>
<option value='Auto'>Auto</option>
</select>
</td>
</tr>
</tbody>
</table>
</form>
Here is my current AJAX function
function ajax_finesave(){
var hr = new XMLHttpRequest();
var url = "PHP/FFfinesave.php";
var fineexpense = document.formfine.elements['fineexpense[]'];
any help on this would be great, also the correct way to request an ajax sent variable would be helpful.Thank you
There's a simple way using JQuery which is to serialise the form. The function is here.
The usage is ...
$('.form').serialize();
... and the resulting value is a query string that can be sent as a single variable to the server and dissected as required by your php, using a function like parse_str()
Another thing to remember about JavaScript is it's array can't be used like a keyed hash, as you'd see in PHP. You need to use an object for keys. So, you won't be able to create an array in JavaScript that mimics a php $_POST array.
You could build a JSON object out of your form and post that using AJAX (JQuery's version here) then use php's json_decode() to unwrap it server side. Do pay attention to the $assoc argument here as you need that to get an array in php.
A JQuery example follows:
var myJSON = {
formField: $('.form-field').val(),
anotherFormField: $('.another-form-field').val()
}
$.ajax({
url: 'my-url',
method: 'post',
data: {
formJSON: myJSON
},
success: function() {
// success update here
}
});
In the example myJSON is a JavaScript object with named keys which are populated with the form field values (though anything will do). This is how you'd mimic php associative arrays in JavaScript.

Unable to access parameters in PHP, Posted values from jQuery with Serialize

I am sending data from jquery via AJAX Post with all the form fields serialized (In WordPress).
$('#SendEmail').click(function () {
jQuery.post(
the_ajax_script.ajaxurl,
{
'action': 'the_ajax_hook_SendEmailWithCalculatorContent',
'calculatorFormContent': $("#CalculatorForm input").serialize()
},
function (response_from_the_action_function) {
$("#G1").val(response_from_the_action_function);
}
);
});
Here are the post paramters from firebug POST:
action the_ajax_hook_SendEmailWithCalculatorContent
calculatorFormContent ZIPCodeTextBox=01915&G1=PhoneNumber+%3A++ZipCode+%3A+&G2=&G3=&G4=&G5=&G6=&G7=&G8=&G9=&G10=&G11=&G12=&G13=&G14=&G15=&G16=&G17=&G18=&G19=&G20=&G21=&G22=&G23=&G24=&G25=&G26=&G27=&fullname=&email=&phone=7324211531
Need to access these parameters in PHP, when I try to access them
echo "PhoneNumber : ".$_POST['phone']." ZipCode : ".$_POST['ZIPCodeTextBox']." IndexValue : ".$_POST['0'];
I get the output as "PhoneNumber : ZipCode : IndexValue : ", so all the form data is coming as blanks.
When I try:
echo $_POST;
i see value "Array" come across.
How do I access the array value?
Saw multiple posts here that answer by using the parameter name, one can fetch data from $_POST['name']. (Similar link: jQuery AJAX form data serialize using PHP)
But apparently it is not working in my case.
What about 'calculatorFormContent': JSON.stringify($("#CalculatorForm input").serializeArray()) and then in your PHP script use $array = json_decode($_POST['calculatorFormContent'], true);
Later access it with $array['phone'].

In PHP how to use $_REQUEST to retrieve an array of inputs to enter into a database

I am using AJAX to send inputs from a webpage to a PHP file to then be entered into a database. Here is my JavaScript file:
var pageLoaded = function () {
var submitButton = document.getElementById("submit");
if (submitButton) {
submitButton.addEventListener("click", submit, true);
}
};
var submit = function () {
var xhr, changeListener;
var form = document.getElementById('item_form');
var inputs = form.getElementsByTagName('input');
// create a request object
xhr = new XMLHttpRequest();
// initialise a request, specifying the HTTP method
// to be used and the URL to be connected to.
xhr.open("POST", "../php/add_item.php", true);
console.log(inputs[0].value); // debugging
// Sends the inputs to the add_item.php file
xhr.send(inputs);
};
window.onload = pageLoaded;
Here I am trying to send inputs from a form to a PHP file called add_item.php located "../php/add_item.php" in my file system.
I am pretty sure this code works and sends the inputs to the PHP file in an array.
My question is, how do I then use $_REQUEST within that file to be able to use the inputs within the array to send to a database? Or, what is the best way of doing this?
The xhr.send() method only accepts a string. If you want to send an array you have to flatten it into a string before posting. You can do this easily using the JSON.stringify() method in javascript, then use json_decode() function in PHP on receiving it.
Also for PHP to receive the data properly in the $_POST[] variable (or $_REQUEST if you must, but not recommended) you need to set a name for the POST variable and URL-encode your JSON text like this:
var json_array = JSON.stringify(inputs);
xhr.send('myJSONData=' + encodeURIComponent(json_array));
On the PHP side you shouldn't need to use urldecode() because the server stack expects to receive POSTed name-value pairs url-encoded. But you will need to use json_decode on the posted variable to get the array back, e.g.:
php_array = json_decode($_POST["myJSONData"]);
You will see other methods to do this, including setting the xhr POST content-type header to JSON, but in my experience this is the path of least resistance.
Also note whilst it is possible to send an "array" of objects in an HTML form like this:
<input type="text" name="myArray[]" value="val1">
<input type="text" name="myArray[]" value="val2">
<input type="text" name="myArray[]" value="val3">
<input type="text" name="myArray[]" value="val4">
which will result in an array being available within PHP in the variable $_POST["myArray"], there is no easy equivalent of this using the XHR object (AJAX method). JSON.stringify() is IMO the easiest way to go.
The variables inside the $_REQUEST are stored as an array. To access them you would do something similar to this:
echo $_REQUEST['input_1'];
To view all the variables (in a nice format) sent by the JS you could use this code:
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
You can't do it in the way you are doing it. You send "input" array which is incorrect. You should prepare array of input values. Morover, I'd recommend you to use JQuery.
$(function (){
$("#submit").click(function (){
//the way to get input values and names
var arr = [];
$("input").each(function (index,value){});
arr.push([$(value).attr('name'), $(value).val()];
});
// it can be replaced also via serialize() funciton
//ajax
$.post( "../php/add_item.php", arr)
.done(function( data ) {
//data has been send response is in data object
});
});
});
In PHP you can get these values via $_POST. $_REQUEST is not needed here because you use POST method. For example if you have input
<input name="xxx" value="test">
to print value of this input in PHP you need use this code
echo $_POST['xxx'];
If you don't want to use JQuery then you still need loop through inputs and prepare proper array to send it via XHR.

passing JSON data and getting it back

I'm new to passing objects through AJAX, and since I am unsure of both the passing and retrieving, I am having trouble debugging.
Basically, I am making an AJAX request to a PHP controller, and echoing data out to a page. I can't be sure I'm passing my object successfully. I am getting null when printing to my page view.
This is my js:
// creating a js filters object with sub arrays for each kind
var filters = {};
// specify arrays within the object to hold the the list of elements that need filtering
// names match the input name of the checkbox group the element belongs to
filters['countries'] = ["mexico", "usa", "nigeria"];
filters['stations'] = ["station1", "station2"];
filters['subjects'] = ["math", "science"];
// when a checkbox is clicked
$("input[type=checkbox]").click(function() {
// send my object to server
$.ajax({
type: 'POST',
url: '/results/search_filter',
success: function(response) {
// inject the results
$('#search_results').html(response);
},
data: JSON.stringify({filters: filters})
}); // end ajax setup
});
My PHP controller:
public function search_filter() {
// create an instance of the view
$filtered_results = View::instance('v_results_search_filter');
$filtered_results->filters = $_POST['filters'];
echo $filtered_results;
}
My PHP view:
<?php var_dump($filters);?>
Perhaps I need to use a jsondecode PHP function, but I'm not sure that my object is getting passed in the first place.
IIRC the data attribute of the $.ajax jQuery method accepts json data directly, no need to use JSON.stringify here :
data: {filters: filters}
This way, you're receiving your json data as regular key/value pairs suitable for reading in PHP through the $_POST superglobal array, as you would expect.
http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
When you use ajax the page is not reloaded so the php variable isn't of use.
You may want to look for a tutorial to help. I put one at the beginning as I don't see how to format this on my tablet
you will need to json_encode your response as the tutorial shows
you may want to print to a log on the server when you are in the php function and make it world readable so you can access it via a browser
I like to use the developer tools in Chrome to see what is actually returned from the server

Categories

Resources