Getting Variables in PHP by JavaScript - javascript

I'm adding a new record in my MySql DB with javascript and I have to elaborate this function in PHP.
$(document).on('submit', '#product_form', function(event){
event.preventDefault();
//btn_action="add_pricelvl"; //Set variable to call the add new item
var valdata = $(this).serialize(); //Array with field value
var tax = $('#item_tax').val(); //checkbox tax
var taxvalue = $('#item_taxvalue').val(); //inputbox tax
var tabledets = it_det //Read the detail table
.rows()
.data();
var arr1=[];//Declare the array
var i=0;
//Put the datatable(item_details) rows in the array
for (i=0; i<tabledets.length; i++){
arr1[i]=tabledets.rows(i).data();
}
//call ajax function and send variable to php file.
$.ajax({
processData: false,
url:'item_action.php',
method:"POST",
data:{
//btn_action:btn_action,
valdata:valdata,
tax:tax,
taxvalue:taxvalue,
arr1:arr1
},
success : function(data)
{
....
}
error : function () {
....
}
})
});
<?php
if ($_POST['btn_action']=='add_pricelvl'){
$query="....."
//Getting variables by JavaScript
}
?>
I can't get any variable in my PHP file... how is that possible?
Trying to check any $_POST[variable] in the PHP File they are NULL... why?

Try removing processData: false,. That command is telling jQuery to not turn the object into a query string. If you want to use $_POST[] in your script, it will expect it to be sent over as a query string.
http://api.jquery.com/jQuery.ajax/
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

To get the body from a POST call you should use something like this
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, true);
Then you can manipulate $obj variable as a regular php array.

Related

how do i send javascript variables to PHP and return the results

I have a form with inputs (each with ID param,param1,param3 respectively) and an external php file with a function called getform() that takes three parameters from the form (param, param1, param3 respectively).
A text feild with id results to display the response from php file.
I have placed onclick function on param3.
I need whenever a user types something in param3 it should be sent to php file and the results displayed in the text filed of id results.
here is my code
<script>
function post(){
var param = $('#param').val();
var param2 = $('#param2').val();
var param3 = $('#param3').val();
$.post('curencyconvert.php', {
postparam: param,
postparam2: param2,
postparam3:param3
}, function(data){
$('#results').html(data);
});
}
</script>
my php function in the php file
function Conv($param,$param2,$param3){
//my code here
return $output;
}
if(isset($_POST)){
//Calling the defined function here
Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}
Add these line below your function code.. and better echo the output in your function instead of returning it.
jQuery(document).ready(function($) {
$('#param3').change(function() {
// put here the code //
} );
})
What errors you get in Console(firbug)?
As stated by other answers $_POST should be used.
What your php code returns if it returns an array or returns an object It can not be put into the Input. Return value must be a
string
PHP code must be :
function Conv($param,$param2,$param3){
//my code here
// take particular field of the DB results or resultset that you want to show in the input.
return $output['name'];
}
I know answer is incomplete because your question is incomplete.
Please let me know errors from the console so that i can help you further
echo instead of return.
if(isset($_POST)){
echo Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}
Do something like this, it is more clean:
Conv($param, $param2, $param3){
// your code here
return $output;
}
As for the javascript part, jquery ajax is your friend
function post(){
var param = $('#param').val();
var param2 = $('#param2').val();
var param3 = $('#param3').val();
$.ajax({
url: '/path/to/file',
type: 'POST',
data : { postparam: param, postparam2: param2, postparam3: param3 },
}).done(function(data) {
$('#results').html(data);
});
}

Display data from an array

In index.php page i have a script that fetches data from demo.php and displays the result in a div.
<div class="leftbox">
<?php
echo "<div id='proddisplay'>";
echo "</div>";
?>
</div>
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'demo.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
in demo.php script i get the result from
print_r($result);
the result that i get in the div is
Array ( [0] => 1st value [1] => 2nd value [2] => 3rd value [3] => 4th value )
I wish to get individial data from this array so that i can use each data seperately and wherever i want in the index.php page, but i am not able to do so. can anyone tell how can i fetch individual values from array for index page
P.S:
i have an option to display the format in demo page in the form of result[0] and so on for every index value and call it as it is in the index page but that bounds me with the css. I wish to use any css in index page and just call the values in index page.
I tried using result[0] in index page but it displayed no result i tried assigning the values of an array to a variable and then call these variables to index page but that also didn't displayed any result
The simplest way to loop through values in an array is to use foreach.
foreach
foreach($result as $value){
print($value);
}
http://php.net/manual/en/control-structures.foreach.php
http://www.w3schools.com/php/php_looping_for.asp
Either access each value individually - for example $result[0]. Or if you want to loop over the entire array you can use foreach
Example:
foreach($result as $val){
//do something with $val
}
PHP Arrays
Simply assign values of indexes to variables like below:
$first_value = $result[0];
$second_value = $result[1];
$third_value = $result[2];
$fourth_value = $result[3];
and so on in same sequence.
As you're using Ajax to get the data, you need to pass the array back as a JSON string. Add another parameter, dataType: 'JSON' to your Ajax call, this tells jQuery you're expecting a JSON string as a response and it'll automatically convert the JSON into an array for you when passing the result to the success function.
Then in your data.php value you need to run echo json_encode($result); to pass result back to the Ajax success function as a JSON string. jQuery converts it back from a JSON string to an array for us (that's why we add the dataType). Then in your Ajax success function you console.log(resultdata.0) you'll get value1, and console.log(resultdata.1) will give you value2.
convert your array to json
echo json_encode($result);
in your script
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#first').html(returndata[0]);
$('#second').html(returndata[1]);
$('#third').html(returndata[2]);
$('#fourth').html(returndata[3]);
console.log(returndata[0]);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
first,second,third,fourth will be the id of the div or the area where you wish to display the result

How to access AJAX returned data with PHP?

I hava data structure like this which is then returned to another file with AJAX:
$data = array();
$data['message'] = "You are searching: $domain!";
$data['domain:name'] = "domain.tld";
$data['domain:registrar'] = "Registrar Ltd.";
$data['domain:creation'] = "2015-26-05";
$data['domain:expiry'] = "2016-26-05";
$data['ns'] = "ns1.somedns.tld";
$data['owner']['name'] = "Owner Name";
$data['owner']['type'] = "Org";
echo json_encode($data);
That data is then append to html with AJAX like this:
$.ajax({
type: 'POST',
url: 'carnetEpp.php',
data: $(this).serialize(),
success: function (data) {
dataType: 'json',
//console.log(data);
$('#response').html(data);
$("#myModal").modal();
}
});
Now I want to pass that returned JSON object to PHP variable, so I can easy manipulate date with PHP. How do I do that? Or is best practice to do it with JS? Basically I want to print every key:pair value, so maybe for in is good choice.
And, I am not sure, should, or must I echo data in my script so AJAX can pick it up, or can I just pass data to variable and then fetch it in AJAX?
You need to add this code in success.
var obj = jQuery.parseJSON(data);
alert(obj.message);
OR
var obj = $.parseJSON(data);
alert(obj.message);
You will get the message sent from PHP.
before sending data in php, setup header for response:
$data = [
'key' => 'value',
'key2' => 'vlue2'
];
header('Content-Type: application/json');
echo json_encode($data);
then if u use jquery, $.getJson() it really cool solution for handle input json data.

Loop Through json_encoded PHP Array in JavaScript

I am having an issue with looping through an array that was passed from PHP through an Ajax request.
For some reason my javascript thinks that either every character is a part of the array or my response variable is just being passed as a string.
Here is my javascript:
<script>
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
success: function(response) {
console.log(response);
}
});
});
</script>
And here is my PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
echo json_encode($names);
?>
The response that I get looks like this:
["Test Person","Test2 Person"]
However, if I loop through this using javascript or just print out response[0] I get each character as part of the array. The first element would be [, next would be ", etc.
I would like Test Person to be one element and Test2 Person to be another.
Does anybody know what I am doing wrong? Thanks!
You need to use JSON.parse on the response. Wihtout calling that function you are just getting the index of characters in the JavaScript string.
var resultArray = JSON.parse(response);
resultArray[0]; //Should Be "test Person"
The result of the .ajax method is interpreted according to the Content-Type header of the response. If it is incorrect or not specified, the response variable will contain the raw json code as a string.
So one solution is change the PHP code by adding this line:
header("Content-Type: text/json");
Docs:
The type of pre-processing depends by default upon the Content-Type of
the response, but can be set explicitly using the dataType option. If
the dataType option is provided, the Content-Type header of the
response will be disregarded.
You can parse that text to an object, or you can let JQuery do that for you by specifying a datatype in the call. The response parameter will then hold the object instead of the raw json string.
Docs:
If json is specified, the response is parsed using jQuery.parseJSON
before being passed, as an object, to the success handler. The parsed
JSON object is made available through the responseJSON property of the
jqXHR object.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: "json",
success: function(response) {
console.log(response);
}
});
});
In this particular situation, you can use
success: function(response) {
response = eval(response);
console.log(response);
}
But this is bad practice.
Really the best solution here is to modify your ajax call as follow:
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: 'json',
success: function(response) {
console.log(response);
}
});
});
The specified datatype, will request the returned data to be json, and the jquery will automatically parse it to a javascript object.
You must parse JSON to array. You can do this using the following code:
var arr = $.parseJSON(response);
Now arr[0] should be "Test Person".
You can do it the hard way, or this way:
First, you need to specify the return type for AJAX.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Alternatively, you could do it this way:
$(function() {
$.getJSON("/dev/editButton/get_names.php", function(response) {
console.log(response);
});
});
For this to work, you will need to specify the HTML headers accordingly in PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
header("Content-Type: application/json");
echo json_encode($names);
exit();
?>
The exit(); is just for safety so you wouldn't ruin the valid JSON format.
JSON stands for JavaScript Object Notation, so you should not have to do anything complicated there. Here is a simple loop you could use for example:
for(var i in response) {
console.log(response[i]);
}
Alternatively, if the response is not an array but an object with properties, you could loop through the object properties by getting the right keys first:
var objKeys = Object.keys(response);
for(var i in objKeys) {
var key = objKeys[i];
console.log(response[key]);
}
I hope this helps!

Post JSON to PHP in AJAX for MongoDB Querying

I am constructing a Javascript object. I am using the id of user who is logged in (from a session variable) and storing it as an attribute with AJAX.
I wanted to post the resulting object as JSON via AJAX to a PHP file which then inserts the document into a MongoDB database:
var numpages=$('.page').length;
var book=new Object();
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(data){
var user=JSON.parse(data);
book.user=data.username;
}
});
book.title=title;
book.pages=new Array();
var page;
var link;
for (var i=0;i<numpages;i++){
var numlinks=$('#p'+i+' .link').length;
page=new Object();
page.text=$('#p'+i+' .textarea').text();
page.links=new Array();
for (var j=0;j<numlinks;j++){
link=new Object();
link.text=$('#p'+i+'l'+j+' .linktext').text();
link.locale=$('#p'+i+'l'+j+' .locale').text();
page.links.push(link);
}
book.pages.push(page);
}
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
success: function(msg) {
//var story=JSON.parse(msg);
console.log(msg);
//alert(msg);
}
});
}
Here is the PHP:
<?php
$dbhost = 'localhost';
$dbname = 'story';
$m = new MongoClient("mongodb://$dbhost");
$db = $m->$dbname;
$collection = $db->stories;
$story=$_POST['json'];
if (isset($story)){
$collection->save($story);
}
?>
The document is being inserted into the database but I get this:
Notice: Undefined index: json
You have two problem, first being that ajax is async unless you specify the async flag to false which you probably don't want to do so:
book.owner=data.username;
Is likely to actually be empty when you come to JSON encode in the second ajax call.
To solve this you can use JQuery promises like so:
$.get().done(function(data){
/// extra processing
}).then(function(){ $.get() // etc });
This will ensure that one Ajax calls runs after the other.
As for the missing index you don't actually need to stringify your data at all instead you can just do:
$.get('some_url', {book: book})
And JQuery will actually serialize it for you ready for PHP.
This
JSON.stringify(book),
creates an object something like:
{"title":"East of Eden","author":"John Steinbeck"}
better completely remove the JSON.stringify() bit and just pass the book variable
And it in the ajax call it should be type: "POST", not method: "POST"
So in your php script you can do
$_POST['title'];
$_POST['author'];
Hope that helps
If you want to work exclusively with JSON, you should set your content-type header to application/json and then read that content from PHP raw input:
The javascript:
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
contentType: 'application/json',
success: function(msg) {
alert(msg);
}
});
The PHP:
$story = file_get_contents('php://input');
So really you just need to add one line of code and change another.
The reason $_POST['json'] was not being populated is that nowhere did you define a query string (or let jQuery define for you) that has a key json.
You could have, for example done something like this:
data: {'json': JSON.stringify(book)}
And that would have populated $POST['json'], but again if all you are looking to do is pass around a JSON string and directly insert it into Mongo, there is no reason to use form-encoding for this at all, just work with raw POST data.
Note also the problem mentioned by #Sammaye about needing to properly work with event delegation.

Categories

Resources