Save a string on a server using JavaScript and PHP - javascript

I am trying to use AJAX, but it seems it's not working.
var data = 'foo bar';
$.ajax({
url: 'http://localhost/index.php',
type: 'POST',
data: {data: data},
success: function(result) {
alert('success');
}
});
index.php
<?php
$x = $_POST["data"];
file_put_contents ('data.txt', data);
I get a success alert, but data.txt is empty. I have no idea why is this not working.
I am using XAMPP to test on local server.

No, using only javascript you can not write files on a server, because your javascript runs on the client side (the browser).
You need either Ajax and a server side script (like PHP) to handle the saving, or if you only want to use it with one browser (chat with yourself?), you can store stuff with javascript in the localstorage of the browser, but be aware that this storage does not last forever.

Related

why i cant send data to .json format file by ajax

I'm making a simple server to send data to a .json file and receive that data from another page but I have problem how to store data in .json file
I used following code but it didn't work
<script src="jquery/jquery-3.4.1.min.js"></script>
<script>
var _lname = "x";
var _fname = "y";
var _mname = "x";
$.ajax({
type: "POST",
url: "data.json",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
}
});
</script>
Simply POSTing data to a JSON file won't work, as sending a POST request requires the server to listen for requests and do something with the payload you sent. You could make a simple NodeJS or PHP script (or any other server-side language for that matter) that could handle saving the payload to a JSON-file.
When you make a POST request, you send data to a web server.
The web server can do something with the data in the POST request.
By default, it does nothing. Imagine the problems that would be caused if anybody could make a POST request to anyone else's web server and write a new file to it. Google's homepage would be defaced every other second.
If you want to store the results of a POST request, then you need to write server-side code to do it (and you almost certainly will want to perform authentication and authorisation when you do so).
Note that the value of data: in your example code will never be valid JSON. Don't try to write JSON by mashing strings together. Use a library function like JSON.stringify.

JQuery $.ajax request returns me "Error 404" even if the resource exists

I'm developing an app with TideSDK and I need to send some data to a PHP script that will create a file to store it on the pc. I'm pretty new to AJAX and to send data I do:
var jsonString = JSON.stringify(GW2.items);
$.ajax({
url: "/assets/scripts/save.php",
type: "post",
dataType: "json",
data: { jsonString: jsonString }
}).done(function(data){
console.log(data);
});
Where GW2.items is a JSON object, "save.php" is my script and jsonString is the variable I want to send.
But, when I try to execute the program it returns me:
POST http://127.0.0.1:52432/assets/scripts/save.php 404 Not Found
And the answer is: Cannot POST /assets/scripts/save.php
This is the PHP script:
<?php
$jsonString = $_GET['jsonString'];
return {};
?>
I checked the path and it's correct so why it can't find my file?
Did you try your path with POST or just GET? It could be exist for GET requests (pasting the url on a browser) but probably not for POST or other HTTP verbs.
You can use REST clients like Postman to be sure, which is also a Chrome extension.

POST Request PHP equivalent in AJAX / JQuery

I'm able to send some POST requests to a php file. On this php file, I use this to check if my POST request is what I want:
<?php
if(isset($_POST['message'])) {
// Some stuff here
}
?>
I would like to know if I can do the same thing in AJAX / JQuery ?
Not something like this:
<script>
$.post("page.php", $("form[name=addMessage]").serialize(), function(data) {
//Do something here
}).error(function() {
//error
})
</script>
EDIT:
I don't want to send POST request in AJAX / JQuery. I just want to check if I receive a POST request, send from another page.
Indeed, I send a POST request with a field named "message". And I my question is: Is it possible to check if the field "message" is set, but not in PHP, in AJAX / JQquery.
Thank you so much for your help.
Regards,
Lapinou.
If I understand what you are trying to do: No.
Do you want to just listen for an incoming request in Javascript without calling any Ajax-methods? This is not possible. Javascript needs to be told that "I am sending a request now, and I want a response". It is not possible to say "If any request is sent, deal with it here".
Think about it. How would this work? If Javascript would listen to any request incoming, how would it know the difference between an user submitting a form and you sending a request using Postman?
Also, once you load the website in your browser, this is said to be clientside. Everything that happens after that is bound to your computer and your instance of the website. Any request sent to the site would be sent to the server, not your browser.
An other way of doing a post is this:
$.ajax({
type: "POST",
url: "page.php",
cache: false,
data: "message=" + $(".msgBox").val(), //Or Json format { "message" : $(".msgBox").val() },
success: function(html){
$(dashboard_id).html(html);
}
});
Try this:
$("form[name=addMessage]").submit(function(e) {
e.preventDefault();
$.post("page.php", $(this).serialize(), function(data) {
//Do something here
}).error(function() {
//error
})
});
*Update
As per your comment you want to check POST value using JavaScript / jQuery, I don't think so you can access POST data using JavaScript / jQuery. But you want to mix php then you can do something like this
var post = '<?php json_encode($_POST); ?>';
if (post.message !== undefined) {
}
You have to put var post = '<?php json_encode($_POST); ?>'; in a php file

Get Ajax POST data on php via Javascript call

First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}

Understanding how to use CGI and POST

I'm trying to understand how I can use Python and javascript so that I can use POST/GET commands. I have a button that sends a request to server-side python, and should return a value. I understand how to print out a response, but I want to pass a value to a javascript variable instead of just print thing the response.
For example, my javascript sends a string to the python file using the jquery POST function:
<script>
function send(){
$.ajax({
type: "POST",
url: "pythondb.py",
data:{username: 'william'},
async: false,
success: function(){
alert('response received')
},
dataType:'json'
});
}
</script>
Then using the python cgi module I can print out the value of username:
#!/usr/bin/env python
import cgi
print "Content-Type: text/html"
print
form = cgi.FieldStorage()
print form.getvalue("username")
however I am not receiving the data in the same way that the php echo function works. Is there an equivalent to 'echo' for the python cgi module?
I have read this question which explains the different python frameworks that can be used to communicate between browser and server; for the moment I was hoping to keep things as simple as possible and to use the cgi module, but I don't know if that is the best option.
Your success: function can take a parameter, to which jQuery will pass the contents of the response from the AJAX request. Try this and see what happens:
<script>
function send(){
$.ajax({
type: "POST",
url: "pythondb.py",
data:{username: 'william'},
async: false,
success: function(body){
alert('response received: ' + body);
},
dataType:'json'
});
}
</script>
P.S. Why are you using async: false? That kind of defeats most of the point of AJAX.
Your json is not in proper json format.
According to http://api.jquery.com/jquery.parsejson/,
username needs to be in quotes
you can only use double quotes
It would look like this:
{"username": "william"}
Also, your alert should have a semi colon on the end. I can't guarantee this answer will fix your problem, but it may be that your data isn't getting passed to cgi at all.

Categories

Resources