Complex javascript object access in PHP POST var - php

I have a complex Javascript object which is sent to PHP server with $.ajax:
the object looks like:
var obj =
{
sellerId:"1234",
buyerId:"5432",
.
.
.
items:[{id:"11",qt:"3"},{id:"22",qt:"5"},{id:"33",qt:"8"}...]
};
jquery code looks something like this:
$.ajax({
type: "POST",
url: "php.php",
data: obj
}).done(function( msg ) {
alert( msg );
});
on PHP side the following code will echo the sellerId
<?php
echo $_POST['id'];
?>
My question is how do I access the items array and its
object properties? Thanks

hi you can retrieve the value using below code at your php file.
foreach($_POST['items'] as $val){
echo $val['id']."==".$val['qt'];
}

According to your question I slightly created some code for you to start(may be not avery good code but yes u can learn something from this) --
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
var path='getdata.php';
var obj = {
sellerId:"1234",
buyerId:"5432",
items:[{id:"11",qt:"3"},{id:"22",qt:"5"},{id:"33",qt:"8"}]
};
jQuery("#test").click(function(){
jQuery.ajax({
type: "GET",
url: path,
data: obj,
success:function(results)
{
jQuery('#venue').html(results);
}
});
});
});
</script>
<div id="test">This is my active div</div>
<div id="venue"></div>
PHP Code in getdata.php
<?php
foreach($_GET['items'] as $myitem )
{
foreach( $myitem as $key => $value )
{
echo "This is my key : ".$key." This is value of key ".$value."<br />";
}
}
?>
RESULT

Related

Wordpress Plugin Ajax get Javascript Array Data into PHP Variable

function my_action_javascript($val1, $val2) {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'email': '<?php echo $val1?>',
'password': '<?php echo $val2?>'
};
jQuery.post({
url: 'dummyurl',
method: "POST",
data: data,
success: function (data) {
console.log(data);
}
})
});
</script>
<?php
}
I got this function in my Wordpress Plugin. I parse in some data in the function and then i do a ajax request in Javascript. That all works just fine and i get the data array as response.
The Question is, how do i get the data from the Array in Javascript into my Variable in PHP so i can put the Data into my Wordpress Options?
Try this.
you need to parse the response.
function my_action_javascript($val1, $val2) {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'email': '<?php echo $val1?>',
'password': '<?php echo $val2?>'
};
jQuery.post({
url: 'dummyurl',
method: "POST",
data: data,
success: function (data) {
console.log(data);
var obj = jQuery.parseJSON( data);
console.log(obj.somedata);
}
})
});
</script>
<?php
}
You need to have a PHP script that gets called by the AJAX request that will write the data into your options table. There's a specific way of doing this with Wordpress: https://codex.wordpress.org/AJAX_in_Plugins
In a nutshell, you need to add an action parameter to your POST data and then hook your PHP callback function to this parameter. In your callback, you can then use update_option().

How to send json to php via ajax?

I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/

How to get the return value of a php function when calling from jQuery?

I have a php function return a string value which will put into html file.
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
So in jQuery, I have a following function
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).text();
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("HIHIHIHI");
$("#directioninfo").append(data);
}
});
})
Now console.log prints the "HIHIHIHIHI", but jQuery does not append the data to html. Anyone know how to get the return value of php function when calling from jQuery?
Instead of return use:
echo json_encode($dirinfo);
die;
It's also good idea to add dataType field to your $.ajax() function params set to json, to make sure, that data in your success function will be properly parsed.
You just need to send the response back using echo
Use var routeNumber = $(this).val(); to get the button value
PHP:
<?php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> routeNumber". $routeNumber." </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
echo getDirectionInfo($_POST['getDirectionInfo']);
}else{
echo "not set";
}
AJAX & HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).val();
console.log("routeNumber = " + routeNumber);
$.ajax({
url: "systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("data = " + data);
$("#directioninfo").append(data);
}
});
})
});
</script>
</head>
<body>
<div id="directioninfo"></div>
<input type="button" value="12346" class="onebtn" />
</body>
</html>
Thank you for everyone. I have just found that I made a very stupid mistake in jQuery. I should use var routeNumber = parseInt($(this).text()); instead of var routeNumber = $(this).text(); So the following code work to get the return value of php function when calling from jQuery.
in php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
echo json_encode($dirinfo);
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
in jQuery
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = parseInt($(this).text());
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
dataType: "JSON",
success: function(data) {
$("#directioninfo").append(data);
}
});
})

How to post an array using AJAX to PHP?

I want to post an array to PHP using AJAX and on success returns the value back to JavaScript. Here's my code.
JavaScript:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "phparray.php",
data: {
array1: phparray
},
success: function(data){
alert("success");
alert(data);
}
});
});
HTML:
<html>
<head>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script>
var phparray = jQuery.makeArray();
for(var i=0; i<10 ; i++){
phparray.push(i);
}
</script>
<script type="text/javascript" src="phparraypost.js"></script>
</head>
<body>
</body>
</html>
PHP:
<?php
$n=$_POST['array1'];
echo $n;
?>
The data I get back says
<br /> <b>Notice</b>: Array to string conversion in <b>C:\xampp\htdocs\php\phparray.php</b> on line <b>4</b><br /> Array
and I don't have an idea what might be wrong with it.
The HTML, PHP and JavaScript code are in different files.
The problem is in your PHP - you are using echo on an array. Instead use var_dump.
<?php
$n=$_POST['array1'];
var_dump($n);
?>
I came up with the solution using $.param. This function is used internally to convert form element values into a serialized string representation. I am not sure if it fulfills your requirement.
<script>
$(document).ready(function(){
var phparray = new Object();
for(var i=0; i<10 ; i++){
phparray['val' + i] = i; //store value in object
}
$.ajax({
type: "POST",
url: "phparray.php",
data: {
array1: $.param(phparray) //serialize data
},
success: function(data){
alert("success");
alert(data);
}
});
});
</script>
PHP
$pieces = explode('&', $_POST['array1']); //explode passed serialized object
$phparray = array();
foreach($pieces as $piece){
list($key, $value) = explode('=', $piece);
$phparray[$key] = $value; //make php array
}
var_dump($phparray);
http://api.jquery.com/serializeArray/ does this for you, since your already using jquery..
use this:
$("#formId").submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
$.ajax({
url : url,
data : $(this).serialize(),
cache : false,
contentType : false,
processData : false,
type : 'POST',
success : function(data) {
$('#result').html('<div class="notes">Done</div>');
}
});
return false;
});

jQuery ajax call issue with GET

I have the following code that works:
<script type="text/javascript">
$(document).ready(function() {
// Initialise the table
$('#table_1').tableDnD({
onDrop: function(table, row) {
$.tableDnD.serialize();
location.href="test.php?" + $.tableDnD.serialize();
}
});
});
</script>
And it sends through a refresh location.href all the data to the following script:
<?php
$table_1[] = $_GET['table_1'];
$i = 0;
if(!empty($table_1[0])){
foreach($table_1 as $value) {
foreach($value as $row){
$i++;
mysql_query("UPDATE mytable SET tableOrder='$i' WHERE id = '$row'");
}
}
}
?>
What I'd like to do is send the data using ajax, and this is what I have so far, but it's not working:
<script type="text/javascript">
$(document).ready(function() {
// Initialise the table
$('#table_1').tableDnD({
onDrop: function(table, row) {
$.tableDnD.serialize();
$.ajax({
type: "GET",
url: "test.php",
data: "?"+$.tableDnD.serialize(),
success: function(html){
alert("Eureka!");
}
});
}
});
});
</script>
change type to "POST" and lose the question mark in data
OR
remove data and concat what you have in data with url
Try changing:
data: "?"+$.tableDnD.serialize(),
with
data: $.tableDnD.serialize(),
No need for the question mark, jquery does it for you.

Categories