Im so noob at this, been working with PHP and Js for like 4 months, sorry if im making a noob question, also, im a spanish speaker, sorry for english grammar fails you are going to read =[
Basically, this is my problem:
In this Php File i have some Vars and VarArrays, i need to send them to another one
//First PHP File - This one Search on DataBase, at the end, i have 5 vars, 2 of them are arrays
<?php
$var1 = '1';
$var2 = '2';
$var3 = '3';
$arr1 = array();
$arr2 = array();
//¿How to json_encode the 5 vars above?//
?>
In this one i need to catch the previus values
//Second PHP File
<?php
$newVar1 = $_POST['var1'];
$newVar2 = $_POST['var2'];
$newVar3 = $_POST['var3'];
$newArr1 = $_POST['arr1'];
$newArr2 = $_POST['arr2'];
?>
I think i have to do something like this, but how should i do it?:
$.ajax({
type: "POST",
url: "php/FIRSTFILE.php",
data: ????,
dataType: "json",
success:
function(respuesta)
{
$('#MainDiv').load('php/SECONDFILE.php', function(data) {
$(this).html(data);
});
$('#MainDivLabelVar1').val(respuesta.¿¿EncodeStuff??);
}
});
maybe you can encode your data like this
json_encode(array(
'var1' => '1',
'var2' => '2',
'var3' => '3',
'arr1' => array(),
'arr2' => array()
));
In this line you are sending values in POST to your php file:
data: {id: id, CAT: CAT},
So, if you need to receive data like (in file "second.php")
<?php
$newVar1 = $_POST['var1'];
$newVar2 = $_POST['var2'];
?>
You should send it by this:
$.ajax({
type: "POST",
url: "php/second.php",
data: {var1: 'value1', var2: 'value2'}
});
you could deocde the json string into object or array
$js_array = json_encode(array(
'var1' => '1',
'var2' => '2',
'var3' => '3',
'arr1' => array('a' => 'mobile', 'b' => 'PC'),
'arr2' => array('price' => 600, 'day' => 7)
));
$decode = json_decode($js_array, true); //decode into array
//you could use or seperate something you get back from json decode like this
foreach($decode as $key => $value) {
if(is_array($value)) {
foreach ($value as $k => $v) {
echo "$k => $v <br />";
}
} else {
echo "$key: $value <br />";
}
}
and the output:
var1: 1
var2: 2
var3: 3
a: mobile
b: PC
price: 600
day: 7
Related
I am posting an array to my wordpress database. The array is generated in Javascript and I am using JSON to pass it to php. Problem is when I view the user_meta table row I am presented with the following:
Meta_Key \"test\"
Meta_Value [\"1\",\"2\",\"3\",\"4\",\"2\",\"3\",\"4\",\"5\"]
This is how it appears in the database. Here is the rest of the code.
$.ajax({
url:"readJsonSave.php",
method: "post",
data: { array: JSON.stringify( array ), buildName:
JSON.stringify(buildName) },
success: function(res){
console.log(res);
}
})
});
ReadJsonSave.php
require_once("../../../../wp-load.php");
$buildName = $_POST['buildName'];
$myBuild = $_POST['array'];
$myBuild2 = json_decode('array');
echo $myBuild2;
print_r($myBuild);
$wpdb->insert('wp_usermeta', array(
'meta_key' => $buildName,
'meta_value' => $myBuild2
),
array(
)
);
There are several issues with your code. The wp_usermeta table requires a user_id for the associated meta, which it doesn't look like you're providing.
Also, instead of using $wpdb->insert you should be using update_user_meta( $user_id, $meta_key, $meta_value ).
EDIT: You have another issue in your code. $myBuild2 = json_decode('array'); should be $myBuild2 = json_decode( $myBuild );. You're not currently decoding the post var and that is why you're getting an unserialized string in the database.
This should work. readJsonSave.php:
<?php
require_once("../../../../wp-load.php");
$myBuild = wp_unslash( $_POST['array'] );
$myBuild2 = json_decode( $myBuild );
update_user_meta( $user_id, 'test', $myBuild2 ); // Update $user_id
array: JSON.stringify(array) => it could be because your array was already converted to a string and you are trying to convert it again. Check the value of the array you are passing. Try :
$.ajax({
url:"readJsonSave.php",
method: "post",
data: { array: array , buildName: buildName },
success: function(res){
console.log(res);
}
})
I have an AJAX call that makes my JSON look this in my JSON file:
{
"main_object": {
"id": "new",
"formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
}
}
But I would like to have it like this (and this was before I changed my AJAX call with: id: getUrlParameter('id'):
{
"main_object": {
"language": "nl_NL",
"getExerciseTitle": "asd",
"question_takeAudio_exerciseWord": ["asd"],
"Syllablescounter": ["ASDasd", ""]
}
}
The only thing I want to add is the "id": "new", but when I do so (with id: getUrlParameter('id') it gets the id, but it messes up my code.
This is my AJAX call (my JSON starts looking like the first piece of code when I use this)
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: $('#my_form').serialize()
},
dataType: 'json',
}).done(function(response) {
});
});
}
How could this be achieved? I know it isn't my saveJson.php that's the problem. I know it's my AJAX call since it starts showing like the first JSON piece of code when I add the id: getUrlParameter('id').
edit: Since someone said it could be my php code.. here is my php code:
<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} // ending database['data'] count 0.
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
} // ending the max ID else statement.
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} // } op regel 34 lijkt verdwaald...?
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $data['id'],
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
} // closing off the else statement
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
?>
you can use parse_str($str, $output); it will help you achieve what you need.
Note that parse_str takes two parameters, the first one is the string (get Parameters), second one is the array to return the result on. you can use the below code
parse_str($str, $output);
echo json_encode($output);
The issue is how you process formData parameter. serialize() is building url encoded string, however you want key-value pairs. Try this:
$("#my_form").on("submit", function(event) {
event.preventDefault();
var myData = {id: getUrlParameter('id')};
for (var pair of formData.entries()) {
myData[pair[0]] = pair[1];
}
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: myData,
dataType: 'json',
}).done(function(response) {
window.location = 'index.php';
});
});
}
I have tried searching around for a solution to my problem and I can't find any.
I wondered if anyone could help me out.
Basically I'm trying to let a user type in a variable so that they can see a google chart with the data they specifically request.
The chart is set up to do a ajax json request to another php script, though.
Here is my code. (I've deliberately left out the irrelevant code.)
HTML FORM,
<form id="form" action="http://localhost/query/CHART.php" method="POST">
<div><label for="VARIABLE">Enter Variable or % For All Variables:
<input type="text" name="VARIABLE" id="VARIABLE"/>
</label>
</div>
<br />
<div class="submit-button"><input type="submit" value="Get Data"/></div>
</form>
Google Chart PHP Page
include "C:\wamp\www\includes\header.php";
<div id="content">
<br>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
PHP JSON QUERY (MEAS.PHP)
<?php
$conn = mysqli_connect('***', '***', '***');
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysqli_select_db($conn, "TRACK")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$result = $conn->query("SELECT VARIABLE, var1, var2, var3, var4 FROM MEASTEST WHERE VARIABLE LIKE '$VARIABLE'
");
// creates column nsmes, nothing to do with query //
$table = array();
$table['cols'] = array(
array('id' => "", 'label' => 'VARIABLE', 'pattern' => "", 'type' => 'string'),
array('id' => "", 'label' => 'VAR1', 'pattern' => "", 'type' => 'number'),
array('id' => "", 'label' => 'VAR2', 'pattern' => "", 'type' => 'number'),
array('id' => "", 'label' => 'VAR3', 'pattern' => "", 'type' => 'number'),
array('id' => "", 'label' => 'VAR4', 'pattern' => "", 'type' => 'number'),
);
$rows = array();
while ($nt = $result->fetch_assoc())
{
$temp = array();
$temp[] = array('v' => $nt['VARIABLE'], 'f' =>NULL);
$temp[] = array('v' => $nt['VAR1'], 'f' =>NULL);
$temp[] = array('v' => $nt['VAR2'], 'f' =>NULL);
$temp[] = array('v' => $nt['VAR3'], 'f' =>NULL);
$temp[] = array('v' => $nt['VAR4'], 'f' =>NULL);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysqli_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
?>
The result is that the google chart page doesn't load the chart up, due to the variable not being passed to the query and no json data coming back into the page.
Hope this makes sense!
EDIT: I did delibrately leave code out when posting but its confused people, the full php page is there now.
Thanks
edited:
Your Code Is Not Light, You send Ajax request To "MEAS.php" ??
which Is "MEAS.php"'s Code ??
if "MEAS.php" is:
<?php
$VARIABLE = $_POST['VARIABLE'];
$conn = blah,blah
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysqli_select_db($conn, "TRACK")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$result = $conn->query("SELECT VARIABLE FROM MEASTEST WHERE VARIABLE LIKE '$VARIABLE'
");
You Must Set Response "Content-type" with header function:
header("Content-Type: application/json")
and return a json:
echo json_encode(" your Response Data ")
Your AJAX request is not sending any parameters:
var jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
dataType:"json",
async: false
}).responseText;
you need to add the parameter to the request:
var jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
data: {
myParameterName: parameterValue
},
dataType:"json",
async: false
}).responseText;
If this is happening in response to user input, then the drawing should happen inside an event handler in response to whatever needs to trigger the redraw. As an example:
function drawChart() {
var jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
data: {
myParameterName: 'default value'
},
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// create and draw the chart
// ...
/* assumes you have:
* a chart object called "chart"
* an options object called "options"
* a button with the id "myButton" that should trigger a redraw on click
* an input field "myInput" that has the value you want to send to your server
*/
function updateChart () {
jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
data: {
myParameterName: document.querySelector('#myInput').value
},
dataType:"json",
async: false
}).responseText;
data = new google.visualization.DataTable(jsonData);
chart.draw(data, options);
}
var btn = document.querySelector('#myButton');
if (document.addEventListener) {
btn.addEventListener('click', updateChart);
}
else if (document.attachEvent) {
btn.attachEvent('onclick', updateChart);
}
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
I'm trying to use the $.map in ajax and I don't success with getting the data from json array. I'll show you the json file, the ajax code and the json output i get. Hope you can help me, thank you very much :) and sorry for my english! Here is the ajax:
$.ajax({
url: 'searchapi.php',
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map(data.table, function( item ) { //dont get this line!
return {
label: item.trid,
value: item.trid
}
}));
}
});
And here is the json file:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "mydb";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$data = ("select * from table;");
$json = array();
$result = mysql_query($data);
while($row = mysql_fetch_array ($result))
{
$array = array(
'trid' => $row['name'],
);
array_push($json, $array);
}
$jsonstring = json_encode($json);
echo $jsonstring;
die();
?>
Here is the json output:
[{"name":"Emma"},{"name":"Eric"},{"name":"Peter"},{"name":"Sam"},{"name":"Roger"},{"name":"Sven"},{"name":"Julia"}]
You are referring to the wrong key, try it like this
$.map(data, function( item ) { //dont get this line!
return {
label: item.name,
value: item.name
}
})
drupal 6: here is the code:
http://pastebin.com/GGVFfAGS
//getcity.js:
$(document).ready(function() {
$("#edit-field-house-geo-area-value").bind('change', function(){
selected_loc=$("#edit-field-house-geo-area-value option:selected").val();
var myURL="http://whatever.com/getajax/citys/"+selected_loc+"/";
$.ajax({
type: "GET",
url: myURL,
dataType: "json",
success: function(data){
console.log(data);
}
});
});
});
drupal module:
function sf_menu()
{
cache_clear_all();
$items = array ();
$items ['getajax/citys/%'] = array ('title' => 'This is my custom page', 'page callback' => 'sf_get_cities_ajax', 'access arguments' => array ('access content' ), 'access callback' => 'user_access', // TRUE will give access to everyone
'page arguments' => array (2 ), 'type' => MENU_CALLBACK );
return $items;
}
function sf_get_cities_ajax($cityid)
{
$termsarray = array ();
$terms = array ();
$cityid_safe = (int)$cityid;
$cityid_safe = check_plain($cityid_safe);
if (is_number($cityid_safe)) {
$terms = taxonomy_get_children($cityid_safe, 143, 'tid');
if (count($terms)) {
foreach ($termsarray as $k => $v) {
$termsarray [check_plain($k)] = t($v [tid]);
}
$f= array('status' => 1, 'data' => $termsarray,'moo'=>'sadasdsd');
print drupal_json($f);
exit();
}
}
}
its not return me somthing even i print the 'moo' data
its my function its working fine i get array at the final but its dont pass it
That looks like it should work except one thing... PHP doesn't have a function 'is_number()' so unless you wrote your own you need to change your IF statement to use PHP built in 'is_numeric':
if (is_numeric($cityid_safe)) {
Its not a JS issue at all.