Passing javascript var to php [duplicate] - php

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 8 years ago.
I have a php function that simply get me the value of an array given the key.
Example:
<?=__('mykey')?>
Return the value of my array.
I would to call this function after an ajax jQuery call, with a param.
The POST give me a json array, and I need to use the previous funct like this
$.ajax({
url: myfile.php',
type: 'POST',
data: $('#contact_form').serialize(),
dataType: 'json',
}).done(function(data) {
str = '';
$.each(data, function(index) {
$('#message').html(" <?=__('"+index+"')?> ");
});
})
The problem is that the index value inside the $.each function is not passed to php...there is a way to solve it or i have to do something like this?
$.each(data, function(index) {
switch(index):{
case 1: $('#message').html(" <?=__('1')?> "); break;
case 2: $('#message').html(" <?=__('2')?> "); break;
case 3: $('#message').html(" <?=__('3')?> "); break;
...
}
});

I've had to do something similar and actually used jQuery to set the value on a hidden input for me to grab later.
$('#some-hidden-input').val(yourvalue)
Make sure this hidden field exists and is in the rendered HTML
Then the PHP can simply grab that input value on POST.
$myVar = $_POST['some-hidden-input'];

To pass variables to PHP via Javascript, the only reasonable way is to use AJAX, but you do it only when you are posting something. If not, the best way is to have a hidden input field.
Based on different conditions you define, you can set the hidden input field to carry the value you want to apply it to.
To assign the value to <input name="A" id="B">
$("Input[name='A']").val(data);
or
$('#B').val(data);
Both will assign the value of data to the input field

Related

How to access jQuery variable in PHP and PHP variable in jQuery?

What I want to do:
I want to get a value from a select element
And then I want the specific record from the database on the basis of that value.
Finally, gets the record and displays it in an input field
This is my code:
You can't pass jQuery variable to PHP as such, however you can do same thing through ajax, where just pass selected value through ajax to PHP file and get returned result display in input field
<script>
$("#chooseRoles").change(function(e){
e.preventDefault();
$.ajax({
url: 'getValue.php',
data: 'selectedRole='+$(this).val(),
type: 'POST',
success: function(result){
$("#userRoles").val(result);
}
});
});
PHP CODE (getValue.php);
$roles = Roles::find($_POST['selectedRole']);
echo $capabilities = $roles->capabilities;

Serialized form data via ajax only returns one letter ("r")

I have a form that I am submitting via ajax to a php function like so:
var formData = $(form).serialize();
$.ajax({
type : 'post',
dataType : 'json',
url : myAjax.ajaxurl, //we can use this value because in our php file we used wp_localize_script
context:this,
data : {action: 'tps_save_rental_details', formData:formData },
success: function(response) {
alert (response.testing);
}
});
I thought that by using .serialize() it would pass the form data in json form and then I could use it in my php function like so:
$formData = $_REQUEST['formData'];
$rentalType = $formData['rentalType'];
$result['testing'] = $rentalType;
(rental type is the name/id of the first text input field)
But when I alert the returned value of $results['testing'] in my ajax success function I just get one character, the letter "r" which doesn't even appear in the value of that field (which is "class-education").
Is this the best way to pass form input values via ajax? If so, what might I be doing wrong here.
The serialize method just takes the form elements and puts them in string form. "varname=val&var2=val2"
You can get these values in php like:
$params = array();
parse_str($_GET, $params);
Specific to the OP's case:
$formData = array();
parse_str($_REQUEST['formData'], $formData);
$result['testing'] = $formData['rentalType'];

Getting undefined response from jQuery AJAX form post

$(document).ready(function() {
$('#pricingEngine').change(function() {
var query = $("#pricingEngine").serialize();
$('#price').fadeOut(500).addClass('ajax-loading');
$.ajax({
type: "POST",
url: "index.php/welcome/PricingEngine",
data: query,
dataType: 'json',
success: function(data)
{
$('#price').removeClass('ajax-loading').html('$' + data.F_PRICE).fadeIn(500);
$('#sku').attr('value') = (data.businesscards_id);
}
});
return false;
});
});
Need to set #sku as value of a hidden form field (not sure if i am doing that correctly in the above jQuery code.
<input type="hidden" name="sku" id="sku" value="*/PUT VAR VALUE HERE/*" />
Also need to pass the F_PRICE to the #price div.
Console in Chrome shows the JSON response as:
[
{
"businesscards_id":"12",
"X_SIZE":"1.75x3",
"X_PAPER":"14ptGlossCoatedCoverwithUV(C2S)",
"X_COLOR":"1002",
"X_QTY":"250",
"O_RC":"NO",
"F_PRICE":"12490",
"UPS_GROUND":"12000",
"UPS_TWODAY":"24000",
"UPS_OVERNIGHT":"36000"
}
]
Yet I only get 'undefined' in the price box. What is the reason here?
The structure returned as JSON is an array [] containing one element which is the object {} you are targeting. Access it via its array index [0]
// Access the array-wrapped object via its [0] index:
$('#price').removeClass('ajax-loading').html('$' + data[0].F_PRICE).fadeIn(500);
// Likewise here, and set the value with .val()
$('#sku').val(data[0].businesscards_id);
You could also .shift() the first element off the array and use that as you have it:
// Pull the first element off the array, into the same variable
// WARNING: Use a different variable if the array has multiple elements you need to loop over later.
// You *don't* want to do it this way if the array contains multiple objects.
data = data.shift();
$('#price').removeClass('ajax-loading').html('$' + data.F_PRICE).fadeIn(500);
$('#sku').val(data.businesscards_id);
This the the proper way (best)
$('#sku').val(data.businesscards_id);
If you insist on using attr, this should work
$('#sku').attr('value', data.businesscards_id);

PHP unserialize error when deserializing jQuery serialized form [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What to do with php after jquery .serialize()
I am serializing the following form using jQuery, sending it to the server using ajax and deserializing using PHP.
When I deserializing I get the error:
Error at offset 0 of 39 bytes
<form id="Marriage" style="display: none">
<input type="text" name="city" class="txtt" value="city"/>
<input type='button' value='Apply' id="msendsend" class="sendaf" name="jobforming"/>
</form>
Here is the jquery function to send this form
$(document).ready(function () {
$('#msendsend').click(function () {
var id=getParam('ID');
$.ajax({
type:'POST',
url:"send.php",
data:{option:'apply', sr:$("form").serialize()},
success:function (jd) {
}
});
});
});
This is the server code:
if($_REQUEST['option']=='catapply') {
$sc=$_POST['sr'];
mysql_query("insert into user_data(uid,data) values('$session->userid','$sc')");
}
And here I am unserializing .
$sql = mysql_query("SELECT * from user_data");
while ($row = mysql_fetch_array($sql)) {
$un = unserialize($row['data']);
$city=$un['city'];
echo $city;
}
The data in the database is shown as
to=&select_category=25&msg=&city=laho
jQuery's serialize function is way different from PHP's. It creates a query string, as you can see in your database.
This format may be decoded in PHP with the parse_str function. Use it instead of unserialize.
Instead of parsing it manually, though, you may be better off posting your form data as the query string:
data: $("form").serialize(),
You can add a hidden field to convey the option=apply value.
That way, you don't have to decode anything (it'll already be in $_POST) and you may insert every value in a separate row. It'll save you a lot of trouble in the future, e.g. when there's more data and you need to search through it.

Javascript get form value in URL without jQuery

If data is submitted via POST through the classic HTML form method is it possible to access those values using standard Javascript without libraries? How would this be done?
Edit for clarity: The variables have been posted. I am trying to access those values via javascript.
Thinking outside the box: (A hack that should never see the light of day)
For this example the posted variable is "a":
var val=document.URL;
var start;
start = val.search(/a=/);
var end;
end = val.search(/&/);
var thispos = val.substring(start+2,end);
document.URL returns the url of the current site.
val.search returns the position of the first occurrence of the regular expression in
the parameter field.
substring the two and...
thispos now contains the posted variable.
Brutal but functional. Is this too terrible to be an answer?
use:
var myField = document.getElementById('myFieldId');
then myField.value will contain the value.
If you have submitted the page, then you have to get the form data using PHP.
Here is a tutorial that should help: http://www.phpf1.com/tutorial/php-form.html
But if you decide to test jQuery, you can use this:
jQuery('#submit').live('click', function()
{
var form_data = jQuery("#data_form").serialize();
//Save data
jQuery.ajax({
url: siteURL +"/path/to/php/file/jquery.php",
data: {formData : form_data,
success: (function(data) {
//data is whatever you return from jquery.php
//I use json for return data
alert('Data has been saved');
}),
dataType: 'json'
});
After a post, the data is send to the server, javascript cant do anything with that since its client side. What you can do is pre-check with document.getElementById('formid') and use those values in the form. After validating or doing what you want to do, end with form.submit() to really send it to the server.
function getUrlInfo() {
var data = window.location.search.substring(1).split("&");
//returns an array of strings containing the params and their values
// data = [ "param=value","param=value","param=value"]
var params1Array = data[0].substring(0).split("=");
//Splits the first string element at the "=" symbol and
//returns an array with the param and value
//param1Array = ["param","value"]
var param1Value = param1Array[1].replace("+", " ");
//Gets the value from the second element in the param1Array
//Replaces the spaces, if any, in the second element,
//which is the value of the url param
var param2Array = data[1].substring(0).split("=");
//Repeat steps for the second param element,in the url params data array
var param2Value= param2Array[1].replace("+", " ");
return {
param1Value,
param2Value
}
};
The submitted data (either POST or GET) is proccesed on the server side. Javascript runs on the client-side so you can't access the variables from the page receiving the form request.
But you can access them before the post using the input field id (specially to check the input values before sending them).

Categories