Trying to be able to have my website so that I can update a JSON file when I edit a cell using BackgridJS (backgridjs.com). In order to save the file to the server, this is the code I am using:
var MyModel = Backbone.Model.extend({
initialize: function () {
Backbone.Model.prototype.initialize.apply(this, arguments);
this.on("change", function (model, options) {
if (options && options.save === false) return;
model.save();
});
}
});
I want it to apply the change to the JSON file, but I figured it would be easier to use PHP. I read about how to do this on this StackOverflow Question but since I am just beginning to learn PHP, I'm very confused. I keep trying to implement that code into my file, but nothing happens when I save the cell. I'm using MAMP as a localhost.
Any and all help is appreciated.
Thanks to the help of #Ingro, this is the solution. In the HTML with Backbone embedded:
var data1 = JSON.stringify(this);
obj = JSON.parse(data1);
$.ajax({url:"update.php",type:"POST",data:{
"data3":obj
}});
and in the PHP file:
<?php $jsonString = file_get_contents('examples/olympics.json');
$data = json_decode($jsonString,true);
$data3 = $_REQUEST ["data3"];
$data = $data3;
$newJsonString = json_encode($data);
file_put_contents('examples/olympics.json', $newJsonString);
?>
Related
I tried to ask this question yesterday but my question was of bad quality.
I have a wordpress Site that I have integrated with react. I am sending a post request from a react form to the wp api.
The request from react Looks Like this.
axios.post('/wp-admin/admin-ajax.php', new URLSearchParams({
action: 'report',
report: JSON.stringify(props.data),
nonce : document.getElementById("my-react-app").getAttribute("data_id")
}), config)
.then(response => console.log(response))
.catch((err) => {
let message = typeof err.response !== "undefined" ? err.response.data.message : err.message;
console.log("error", message);
});
}
I am Able to receive the request on the server but I cannot target the json string of data in php.
$data
{"success":true,"data":{"action":"report","report":"{\\\"firstName\\\":\\\"rrt\\\",\\\"lastName\\\":\\\"trtr\\\",\\\"phone\\\":\\\"rt\\\",\\\"email\\\":\\\"rtrt\\\",\\\"placedata\\\":{\\\"Street\\\":\\\"tr\\\",\\\"City\\\":\\\"tr\\\",\\\"State\\\":\\\"tr\\\",\\\"zip\\\":\\\"tr\\\"},\\\"dateData\\\":{\\\"Start\\\":\\\"00:21\\\",\\\"End\\\":\\\"00:12\\\",\\\"Date\\\":\\\"2022-08-31\\\"},\\\"foodData\\\":{\\\"Food\\\":\\\"df\\\"},\\\"peopleData\\\":{\\\"People\\\":\\\"32\\\"}}","nonce":"f2331f42d4"}}
I have Tried ($data is an Array)
function report() {
global $wpdb;
$data = $_POST;
$test_One = json_decode($data['report']->firstName; //Response Nothing. Not even Null
$Test_two = json_decode($data['report']); //Response (The Json String)--- {\\\"firstName\\\":\\\"rrt\\\",\\\"lastName\\\":\\\"trtr\\\",\\\"phone\\\":\\\"rt\\\",\\\"email\\\":\\\"rtrt\\\",\\\"placedata\\\":{\\\"Street\\\":\\\"tr\\\",\\\"City\\\":\\\"tr\\\",\\\"State\\\":\\\"tr\\\",\\\"zip\\\":\\\"tr\\\"},\\\"dateData\\\":{\\\"Start\\\":\\\"00:21\\\",\\\"End\\\":\\\"00:12\\\",\\\"Date\\\":\\\"2022-08-31\\\"},\\\"foodData\\\":{\\\"Food\\\":\\\"df\\\"},\\\"peopleData\\\":{\\\"People\\\":\\\"32\\\"}
//The above examples have all been placed in print_r
echo "<xmp>";
(Test 3) print_r(json_decode($data['report'])['lastName']); // Response --- {
echo "</xmp>";
}
I am new to PHP and have looked at many Answers On Here. Have yet to find a similar Issue. That tells me it's probably not much of an issue, yet I cant seem to figure it out. Any Help Would be Appreciated. Thank you!
try this solution
function report() {
global $wpdb;
$data = $_POST;
$test_One = json_decode($data);
$test_One = $test_One->data->report->first_name;
echo $test_One;
}
I have actually read all related answers to my question but I need a clear and simple example on how to properly implement my code below.
myHome.php
jquery
var url = "computeArea.php";
var data = $('thisForm').serialize();
$.post(url,data,function(response)); // how do i get the area being returned from
computeArea function? i need to save the
return value to a javascript variable
computeArea.php
function computeArea ($data){ // do i need to parse $data to make it an array?
return $area;
}
im new to jquery and your help is very helpful. thank you!
You can do:
$.post(url,data,function(response){
alert(response)
});
ps: you are missing the . between $ and post.
In your php code you could do that:
echo json_encode($area);
Do a simple teste.
jQuery:
$.post("url/to/file.php",{variable_name: "hello"/*(we'll give this value to variable_name*/)},
function(response){
if(response>0)
alert('Something went wrong');
else
alert(response);
});
Now, on server side:
<?php
if(isset($_POST['variable_name']) && $_POST['variable_name']!=="")
echo $_POST['variable_name'];
else
echo 1;
?>
You are misunderstanding the use of post requests. This will not call the computeArea function in computeArea.php and pass data as its parameter:
var data = $('thisForm').serialize();
$.post(url,data,function(response));
You can do this instead for computeArea.php:
$data = $_POST['watever_you_are_serializing'];
// Do computations, etc.
$area = 123; // Contains computed area
echo $area; // Or json_encode($area);
If you need to call that function from computeArea.php, then you can create a new file for $.post request (eg. computeArea2.php) and include computeArea.php from there. It would be something like this:
include 'computeArea.php';
$data = $_POST['watever_you_are_serializing'];
echo computeArea($data);
Something along the lines of:
var url = "computeArea.php",
data = $('thisForm').serialize(),
new_variable;
$.post(url, data, function(response) {
new_variable = response;
});
Though I presume there's a bit more to your PHP script, as otherwise $area isn't defined anywhere.
I was wondering if i could get som suggestions on what the best approach to do the following would be...
I am currently calling a Flash AS3 function from Javascript (using jQuery) this function uploads a file which has already been selected in this flash file. Flash then uploads the file and calls a php file (upload.php) which handles the processed file. This all works fine. However there are other details that are filled out that pertain to the file uploaded (entered by the user in textboxes) All this data including the file path to where it has been uploaded must then be saved to a DB. Which can be done through an ajax call to another php file (processData.php). My issue is that when i upload the file i cant send the other details along with the file through flash (atleast not that i know of) which causes 2 different php scripts to execute. Secondly the other php script called through ajax doesnt have the file information to add to the DB. I can store this info in a session if i want but it just doesnt seem to convince me as the best way to go about this. Any other ideas or suggestions?
There is quite a bit of code I have so to avoid making this a HUGE question ill post the JS part that i think is important and some snippets of flash so you can have an idea of whats going on... If theres anyhting else youd like to see of the code feel free to ask and ill post it...
JS:
$("#uploadAudio").submit(function(event) {
event.preventDefault();
var form = $(this);
var title = form.find("#title").val();
var desc = form.find("#desc").val();
var flash = $("#flash");
var flashFileSet = flash.get(0).jsIsFileSelected();
if(flashFileSet)
{
$.ajax({
type: "POST",
url: "processData.php",
dataType: "text",
data: "title=" + title + "&desc=" + desc,
async: false,
success: function() {
audFile.get(0).jsUploadFile();
}
});
}
});
Flash
public function fUploader(){
req = new URLRequest();
req.url = ( stage.loaderInfo.parameters.f )? stage.loaderInfo.parameters.f : 'http://virtualmanagementonline.com/ajax/audUpload.php';
pFilterType = ( stage.loaderInfo.parameters.filterType )? stage.loaderInfo.parameters.filterType : 'Images';
pFileFilters = ( stage.loaderInfo.parameters.fileFilters )? stage.loaderInfo.parameters.fileFilters : '*.jpg;*.jpeg;*.gif;*.png';
file = new FileReference();
setup( file );
select_btn.addEventListener( MouseEvent.CLICK, browse );
progress_mc.bar.scaleX = 0;
tm = new Timer( 1000 );
tm.addEventListener( TimerEvent.TIMER, updateSpeed );
cancel_btn.addEventListener( MouseEvent.CLICK, cancelUpload );
cancel_btn.visible = false;
ExternalInterface.addCallback("jsUploadFile", uploadFile);
ExternalInterface.addCallback("jsIsFileSelected", IsFileSelected);
}
public function browse( e:MouseEvent ){
filefilters = [ new FileFilter(pFilterType, pFileFilters) ]; file.browse( filefilters );
}
private function selectHandler( e:Event ){
var tf = new TextFormat();
tf.color = 0x000000;
label_txt.defaultTextFormat = tf;
label_txt.text = file.name;
//file.upload( req );
}
public function IsFileSelected():Boolean{
if(label_txt.text != "")
{
return true;
}
else
{
return false;
}
}
public function uploadFile():void{
file.upload(req);
}
**Note: NOT all the flash code is shown since there is alot. I put up what i thought was needed to get an understanding of what exactly is going on.
If there is anything i can add for further details please let me know. Thanks in advance!
You can send as many data as you want to flash, since ExternalInterface is available.
ActionScript 3 Reference states the following about ExternalInterface:
From JavaScript on the HTML page, you can:
- Call an ActionScript function.
- Pass arguments using standard function call notation.
- Return a value to the JavaScript function.
All you have to do is register an ActionScript function/method as callable from the container:
ActionScript
...
ExternalInterface.addCallback("jsUploadFile", uploadFile);
...
public function uploadFile (title:String, desc:String):void
{
var infos:URLVariables = new URLVariables();
infos.desc = desc;
infos.title = title;
/* When you pass the URLVariables to data property of URLRequest,
all variables associated with the URLVariables object will be
sent to the server along with the image uploaded. */
req.data = infos;
file.upload(req);
}
Then, call it from the container (HTML) passing the additional information as parameters.
JavaScript
$("#uploadAudio").submit(function(event) {
event.preventDefault();
var form = $(this);
var title = form.find("#title").val();
var desc = form.find("#desc").val();
var flash = $("#flash");
var flashFileSet = flash.get(0).jsIsFileSelected();
if(flashFileSet)
{
/* Instead of sending title and desc to the server via ajax, pass
them as parameters to the jsUploadFile method. So
you can handle everything in one place */
audFile.get(0).jsUploadFile(title, desc);
}
});
Hope it helps.
i'm a little stuck with a jQuery. At the moment my function looks like this.
$(function(){
$(".url2").keyup(validNum).blur(validNum);
function validNum() {
var initVal = $(this).val();
outputVal = initVal.replace(/(https?:\/\/)?(www.)?[0-9A-Za-z-]{2,50}\.[a-zA-Z]{2,4}([\/\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#]){0,250}(\s){1}$/
,"http://my.site/ref.php?id=<?php $code = unqiue-ref-id(); echo $unqiue-ref-id;?>");
if (initVal != outputVal) {
$(this).val(outputVal);
return false;
}}
});
So right now it rewrites a user typed url (in a textarea) to a redirection link with my own url (e.g. my.site?ref.php?id=unique12. What I need exactly is a POST Request to a php file (code below) where the valid user-url is given to the php file as a var and then the php file should give back a var with the generated unique unique-ref-id. I do of course know that the code above isn't working like that, it only shows how the final result should look like. The php file wich generates the unique-ref-id looks like this.
function unqiue-ref-id() {
$unqiue-ref-id = "";
$lenght=4;
$string="abcdefghijklmnopqrstuvwxyz123456789";
mt_srand((double)microtime()*1000000);
for ($i=1; $i <= $lenght; $i++) {
$shorturl .= substr($string, mt_rand(0,strlen($string)-1), 1);
}
return $unqiue-ref-id;
}
$user-url = // var send from jquery
do{
$unqiue-ref-id = unqiue-ref-id();
} while(in_array($unqiue-ref-id, $result));
// var send back to jquery function => final results of do function above
// Here i add the $user-url and $unique-ref-id to datebase (Dont need code for that)
?>
Would be so great if someone can help me out with that. Thanks a lot :)
Use the POST jQuery's method. Here's an example
$.post('URL-TO-POST-DATA', {'parameter1': 'value', 'parameter2': 'value'}, function(data_received){
/** Here goes your callback function **/ alert(data_received);
});
More information about POST method
Don't forget one thing. jQuery will not receive nothing if you don't use echo on PHP (instead of return). You MUST use echo in PHP, don't forget it.
First off, I am very bad at flash/actionscript, it is not my main programming language.
I have created my own file upload flash app that has been working great for me up until this point. It uses PHP to upload the files and sends back a status message which gets displayed in a status box to the user.
Now I have run into a situation where I need the HTML to pass a parameter to the Actionscript, and then to the PHP file using POST. I have tried to set this up just like adobe has it on http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_7.html without success.
Here is my Actionscript code
import fl.controls.TextArea;
//Set filters
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
var textTypes:FileFilter = new FileFilter("Documents (*.txt, *.rtf, *.pdf, *.doc)", "*.txt; *.rtf; *.pdf; *.doc");
var allTypes:Array = new Array(textTypes, imageTypes);
var fileRefList:FileReferenceList = new FileReferenceList();
//Add event listeners for its various fileRefList functions below
upload_buttn.addEventListener(MouseEvent.CLICK, browseBox);
fileRefList.addEventListener(Event.SELECT, selectHandler);
function browseBox(event:MouseEvent):void {
fileRefList.browse(allTypes);
}
function selectHandler(event:Event):void {
var phpRequest:URLRequest = new URLRequest("ajax/upload.ajax.php");
var flashVars:URLVariables = objectToURLVariables(this.root.loaderInfo);
phpRequest.method = URLRequestMethod.POST;
phpRequest.data = flashVars;
var file:FileReference;
var files:FileReferenceList = FileReferenceList(event.target);
var selectedFileArray:Array = files.fileList;
var listener:Object = new Object();
for (var i:uint = 0; i < selectedFileArray.length; i++) {
file = FileReference(selectedFileArray[i]);
try {
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, phpResponse);
file.upload(phpRequest);
}
catch (error:Error) {
status_txt.text = file.name + " Was not uploaded correctly (" + error.message + ")";
}
}
}
function phpResponse(event:DataEvent):void {
var file:FileReference = FileReference(event.target);
status_txt.htmlText += event.data;
}
function objectToURLVariables(parameters:Object):URLVariables {
var paramsToSend:URLVariables = new URLVariables();
for(var i:String in parameters) {
if(i!=null) {
if(parameters[i] is Array) paramsToSend[i] = parameters[i];
else paramsToSend[i] = parameters[i].toString();
}
}
return paramsToSend;
}
The flashVars variable is the one that should contain the values from the HTML file. But whenever I run the program and output the variables in the PHP file I receive the following.
//Using this command on the PHP page
print_r($_POST);
//I get this for output
Array
(
[Filename] => testfile.txt
[Upload] => Submit Query
)
Its almost like the parameters are getting over written or are just not working at all.
Thanks for any help,
Metropolis
Try...
print_r($_FILES);
Like I said in my comment: Do you successfully receive the variable in Flash from the flashvars?
I haven't done Flash in a while but maybe, instead of your objectToURLVariables function, just referencing each variable directly is a better way. At least to figure out if you have those variables from your HTML page. So maybe do something like this:
var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myVar;
var flashVars:URLVariables = objectToURLVariables(myVar);
Ok, I have fixed the issue somehow.....I kept changing things back and forth and realized that the cache had not been cleared in awhile. I cleared the cache and it started working for some reason.
I did change one line back to the way I had it before.
I changed
var flashVars:URLVariables = objectToURLVariables(this.root.loaderInfo);
To
var flashVars:URLVariables = objectToURLVariables(root.loaderInfo.parameters);
Im not positive that this was causing the problem. It may have been that I just needed to clear the cache the whole time. Anyway, thanks for your help guys.