I have a form and an array containing some data. I am trying to post both these objects to my php script. The code I am using to post the form and array is shown below:
var json_data = JSON.stringify(data_vendor); //array to be posted
$.ajax({
url: '/crm/inventory/add_purchase_order.php',
type: 'POST',
data: {data_vendor:json_data,form_data:$("#purchase_orderform").serialize()},
dataType: 'json',
In the PHP script I am able to decode the array using the following :
$vendor_codes = json_decode($_POST["data_vendor"],true);
The form contains several fields/inputs one of which is called "order_quantity" . I am trying to retrieve this value using:
$order_quantity = $_POST["order_quantity"];
The data read shows up as NULL.
(i) Is the method used correct for posting multiple objects/strings correct?
(ii) Is the method used to retrieve the form inputs correct?
Usually when you use serialize() that is all you send because it is a urlencoded string. Then the form control names are available as keys in $_POST
But you currently only have 2 keys available to $_POST ... $_POST["data_vendor"] and $_POST["form_data"]
$_POST["form_data"] is a urlencoded string which you did with serialize() so it also needs to be decoded now manually
Try
$formData = urldecode($_POST["form_data"]);
$order_quantity = $formData ['order_quantity'];
To validate this just do a dump of $_POST["form_data"] and you will see that it is a string...not array
Related
I want to submit a form using Ajax but I want it to be in an array, not serialized.
var form = $(this);
data: {data:form.serialize()};
gives me this in my PHP:
firstname=John&lastname=Doe&phone=123123412345
and I have to run this code in PHP to get it into the format I want:
parse_str($_POST['data'], $data);
Just seems super unnecessary and I would like to remove that step. How can I just pass the form in an array format? Thanks
// var form = $(this);
var form = this;
data: {data: Object.fromEntries(new FormData(form))}
then you will get the $_POST variable like this:
Array
(
[data] => Array
(
[firstname] => John
[lastname] => Doe
[phone] => 123123412345
)
)
You're over-engineering your Javascript.
In this line:
data: {data:form.serialize()};
you're creating an object with data as a key and your serialized data as its value. When you pass that to jQuery for an AJAX call it passes that in that form. Hence you're finding your serialize string in $_POST['data'] and you have to unpack it.
You should send your serialised data to jQuery without packing it in an object:
data: form.serialize()};
jQuery will recognise that and send the daya with the correct keys so that you can read it directly in $_POST['firstname'], $_POST['lastname'], etc.
Here is a script.
It provides some select inputs which allow picking from various types of options. When the submit button is pressed it records the data in mats and pushes the mats array into an array called materialsUsed. Everytime the submit button is clicked a new array is added in materialsUsed.
I want to know how to send the materialsUsed array through a URL to php to extract the data there and insert it into an array created in PHP.
var mats = [name= "", thick= "", size= "", quantity= 0, price= 0];
mats.name = document.getElementById("mat").options[document.getElementById("mat").selectedIndex].value;
mats.thick = document.getElementById("thick").options[document.getElementById("thick").selectedIndex].value;
mats.size = document.getElementById("size").options[document.getElementById("size").selectedIndex].value;
mats.price = parseFloat($('#priceto').val()).toFixed(2);
mats.quantity = parseInt($('#quant').val());
materialsUsed.push(mats);
If you would like to simply load them as GET values into the URL just set them directly in the URL using location.href. Then simply use $__GET (IE: $__GET['mat']) in PHP to grab values.
var baseURL = "http://yourdomain.com";
window.location.href = baseURL + "?mat=" + mats.name + "&thick=" + mats.thick etc...
First you have to properly prepare your mats array and convert materialsUsed array into JSON format. Then you can call an ajax function like below, to send it to the php script.
var jsonString = JSON.stringify(materialsUsed);
$.ajax({
type: "GET",
url: "your_script.php",
data: {data : jsonString},
success: function(){
alert("Successfully sent the data!");
}
});
From the your_script.php file, you can perform this to extract the array.
$data = json_decode(stripslashes($_GET['data']));
Important
When using GET method, the amount of the data (length of url) is
limited. So, if your materialUsed array is too huge, you should use
POST method instead.
I think what you're looking for is making an ajax call to your php script providing your js array as its data.
You should listen for the form submission event in your javascript and launch an AJAX call to your PHP script providing your array. You may send your array via the URL (query string) using a GET or in the request body using a POST (that's an option you specify in your AJAX call). Then you would just retrieve your array in your php script an do whatever you want with it.
I suggest you read more on form submission events and AJAX calls in javaScript.
Quick hint : if you have the possibility to do so, try using jQuery as AJAX is way easier to use with jQuery.
You are trying to use associative array, but it's not possible in Javascript as far as I know.
I'd say the best way to do that is creating a object, parsing to json and sending to php. Does't look that hard.
In my database I have table Person (id, name, last_name, phone_number). I do something like this:
$queryPerson = mysqli_query($con, 'SELECT * FROM Person');
while ($person = mysqli_fetch_array($queryPerson)) {
echo '<option value="'.$person["id"].'">'.$person["name"].' '.$person["last_name"].'</option>';
}
I want to use javascipt function to copy selected value from the select to textboxes:
function copyPerson(data) {
document.getElementById["name"].value = data.value;
}
...but instead of their id I want their names and last names and phone numbers to be displayed in textboxes. Now I came up with this idea to read the value from an option, send query to DB SELECT * FROM Person WHERE id = ID_FROM_SELECT and then recieve the data I want to recieve. I'm not sure if it's a good idea though.
In before: yes, I need to have $person["id"] as a value of an option.
My question is: sending the query to DB is a good idea - if yes, how can I send a value from javascript to MySQL, if no - what is a better solution?
EDIT: Apart from #Thanos Tourikas answer, I found this link to be helpful: http://www.w3schools.com/php/php_ajax_database.asp
Generally it is not a good idea to send the query.
The solution would be to send the id with ajax and have a php page that handles that request.
In that php page, you just need to get the id, which is sent as a parameter to the request, and construct there the db query. Then just echo the result as a json object and handle that response with JavaScript.
First, use jQuery to make a request to the server sending the person id:
$.ajax({
url: 'url_that_handles_request.php',
data: { id: person_id },
dataType: 'json',
success: function(response){
// here you handle the response from server.
// you can access the data returned doing something like:
var id = response.id;
var name = response.name;
}
});
And then, you need to provide a php page to handle the ajax call:
$person_id = $_POST["person_id"];
// here you make the query to the database using the person id
// and then just echo the db response as a json object
echo json_encode($db_response);
Here are some useful links
A quick tutorial for jQuery and how to install it:
http://www.w3schools.com/jquery/default.asp
A quick tutorial for jQuery ajax:
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
Some references in the ajax methods that jQuery provides:
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
A tutorial about json:
http://www.w3schools.com/json/
And finally a documentation about json_encode php function:
http://php.net/manual/en/function.json-encode.php
I have a front-page.php template which lists the 5 latest posts along with some custom post types in between. When one clicks on the more button at the bottom it needs to ajax load more posts.
So I created a loop-home.php file according to this tutorial
I couldn't use this code by default because I have a nested loop on the first load of homepage and this script messes it up.
So I wrote a new query to ajax OLDER posts only. I collected the post ids of the posts already present when the page loads and stored it in an array.
I now need to use this array in the query of loop-home.php
I am using this method because offset does not work with pagination and I need to pass these IDs to post__not_in parameter in the query.
Method 1:
I tried (in loop-home.php)
$exempt = $_REQUEST['exemptArray'];
But it returns NULL.
Method 2:(Using Ajax)
I tried (in front-page.php)-
<script>
var exemptArray = '<?php echo json_encode($exemptions); ?>';
</script>
Then I went to script.js and added-
//create json object from the var array
var jsonArray = JSON.stringify(exemptArray);
var dataToPost = { 'jsonArray':jsonArray };
//send POST data to PHP and handle response
$.ajax({
type: 'POST',
url: loopHome, //stored path in variable. working.
data: dataToPost,
success: function (data) {
console.log('I have already sent it.'); //I am getting this log. Working.
}
});
Then in loop-home.php-
$exempt = json_decode($_POST['jsonArray']);
Still getting NULL on var_dump($exempt)
What am I doing wrong?
Try this
You JS:
$.ajax({
type:'POST',
url:'foo.php',
data:{myArr:exemptArray},
dataType:'JSON',
success:function(result){
console.log(result);
},
error:function(data){
console.log(JSON.stringify(result));
}
});
Your php page:
$input=$_POST['myArr'];
$exempt=json_encode($input);
In your console you will get an array. [object object] is a reference to an associative array.So in the above code result is same as exemptArray.Try something like this you will be able to.I could not find your array composition anywhere so i used exemtarray itself.
I want to encrypt some data in a form using jQuery before it's sent to the server, it can be a MD5 hash. It is a small project, so I don't really need to use SSL.
I have the following JavaScript code where I use $.md5 in the password confirmation info:
$(document).ready(function() {
var dataToSend = {};
dataToSend['action'] = 'signup';
dataToSend['name'] = name.val();
dataToSend['email'] = email.val();
dataToSend['confsenha'] = $.md5(pass2.val());
var options = {
target: '#error',
url: 'insert.php',
beforeSubmit: validate,
data: dataToSend,
success: function(resposta) {
$('#message').html(resposta);
}
};
$('#customForm').ajaxForm(options);
});
The problem is that the data is being duplicated. I tought that overwriting the data being sent by using the var dataToSend would make ajaxForm send only data in that map. But besides sending data from dataToSend, it also sends data from the form, so what I wanted to encrypt using MD5 appears both encrypted and clean. This is an example of what goes in the request:
usuario=user&email=user%40email.com&senha=12345&confsenha=12345&send=&action=signup&name=user&email=user%40email.com&confsenha=d41d8cd98f00b204e9800998ecf8427e
I know I have to define the a function beforeSerialize, but I don't know how to manipulate form data. Can anyone tell me how to do that?
As per the documentation on the plugin site:
data
An object containing extra data that should be submitted
along with the form.
The word along is the crux.
So when you pass data as a part of the options object that data is serialized and is sent along with any data/input elements values that are part of a form.
A better approach would be to hash the password value and assign it to the same field or another hidden field in the beforeSubmit handler(in your case the validate function) and remove the dataToSend object totally.
Something like:
Without any hidden element:
function validate(){
//Other Code
pass2.val($.md5(pass2.val()));
}
With a hidden element in the form:
function validate(){
//Other Code
$("#hdnPass").val($.md5(pass2.val()));
pass2.val("");
}