How to receive AJAX data in php [duplicate] - javascript

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 2 years ago.
I am trying to build a small form in my website which will use ajax to save the form details to the database with php. I can do it with jquery, since I am a student, I don't want to use any external libraries.
I was able to use ajax "get method" and even manage to create a post method but I have no idea how to receive this data in the php script and process it.
This is the ajax code i used to send json data
subForm.addEventListener('click',()=>{
var forms = {
"name": document.getElementById('name').value,
"phone": document.getElementById('phone').value,
"email": document.getElementById('email').value,
"message": document.getElementById('message').value,
"exe" : true
}
var jString = JSON.stringify(forms);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "recieve.php");
xhttp.setRequestHeader("Content-Type" , "application/json")
xhttp.send(jString);
});

If you've managed to process a GET. You'll manage the POST just in the same way. By peeking in the global variable $_POST['myJson'] in your "recieve.php".
On the client side, you'd need then to stringify like so:
var jString = JSON.stringify({"myJson": forms});
Therefore, on the server side, $_POST['myJson'] will contain the object 'forms', which you constructed on the client side. And if you want to access let's say, the name property value, you do like so:
var nameValue = $_POST['myJson']['name'];

Related

Passing Javascript Variable to Python Flask [duplicate]

This question already has answers here:
jQuery posting JSON
(3 answers)
Submit a form using jQuery [closed]
(22 answers)
Closed 5 years ago.
I have read several postings on different examples for passing a javascript variable to flask through post/get forms. I still don't understand how to do this. From my understanding, the form creates a post/get that can then be called and received by the python flask script. Can someone write up a very simple example on what this should look like?
Starting from creating a variable with any value in javascript and then making the post/get. Lastly what should the receiving end on python should look like and finally print the variable from python.
How I did this was using an ajax request from the javascript which would look something like this. I think the easiest way would be using JQuery as well since it might be a bit more verbose with pure javascript.
// some movie data
var movies = {
'title': movie_title,
'release_date': movie_release_date
}
$.ajax({
url: Flask.url_for('my_function'),
type: 'POST',
data: JSON.stringify(movies), // converts js value to JSON string
})
.done(function(result){ // on success get the return object from server
console.log(result) // do whatever with it. In this case see it in console
})
Flask.url requires JSGlue which basically let's you use Flask's
url_for but with javascript. Look it up, easy install and usage. Otherwise I think you could just replace it with the url e.g '/function_url'
Then on the server side you might have something like this:
from flask import request, jsonify, render_template
import sys
#app.route("/function_route", methods=["GET", "POST"])
def my_function():
if request.method == "POST":
data = {} // empty dict to store data
data['title'] = request.json['title']
data['release_date'] = request.json['movie_release_date']
// do whatever you want with the data here e.g look up in database or something
// if you want to print to console
print(data, file=sys.stderr)
// then return something back to frontend on success
// this returns back received data and you should see it in browser console
// because of the console.log() in the script.
return jsonify(data)
else:
return render_template('the_page_i_was_on.html')
I think the main points are to look up ajax requests in jquery, flask's request.json() and jsonify() functions.
Edit: Corrected syntax

How to connect to mysql database and retrieve data from a javascript function? [duplicate]

This question already has an answer here:
Connect to MySQL in javascript server side without node.js
(1 answer)
Closed 6 years ago.
I am trying to connect to MySQL Db in the below javascript function.The funcion however does not execute.Can someone please tell me how to connect to MySQL DB and retrieve data through a JS function?
function jsfunction(projectSelected){
alert("hi");
document.getElementById("total").value = projectSelected;
a="hi";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/service", "root", "root");
Statement st4=con.createStatement();
ResultSet rs4=st4.executeQuery("SELECT * FROM project WHERE project= '"+project_selected+"' " );
String total_amount=rs.getString("total_amount");
}
You should not use js for sql query. I would do it through a request with AJAX which will execute a php document.
Read this article and get to know how:
http://www.w3schools.com/ajax/default.asp
PS: Sorry for my barely available english skills
PPS: I have made a function some time ago that maybe can be usefull for you:
function request(url,value,output_id,output){
$.post(url,
{
value: value,
output_id:output_id,
},
function(data,status){
if(status==="success"){
if(output===1){
alert(data);
alert("||value"+value)
}
if(output_id!=0){
document.getElementById(output_id).innerHTML =data;
}
}
});}
Usage
You have to hand over the id of a httml element(output_id)where you want the result to be shown, a value which will be sent to the php file and the name of the file(url).
The PhP file
To use the value in the php file of your choise, you just have to add this little line somewhere:
$php_value = strtoupper($_POST['value']);

Send json object using POST pure javascript [duplicate]

This question already has answers here:
Reading JSON POST using PHP
(3 answers)
Closed 7 years ago.
I want to send a JSON object to PHP server but I get an empty array there. Why is this happening?
var obj = {
username: username,
password: password
};
var ajax = new XMLHttpRequest();
ajax.open('post', 'ajax/login_register.php');
ajax.setRequestHeader("Content-type", "application/json;charset=UTF-8");
ajax.send(JSON.stringify(obj));
You need to give it a name that you can reference on the server side.
ajax.send('user=' + encodeURIComponent(JSON.stringify(obj)));
$_POST['user'] // <-- your JSON string

passing and retrieving variables in cakephp from javascript using GET METHOD

i know how to construct url parameters in javascript and i know how to extract it if im going to pass it to a php file.
However, here's the scenario, i am going to pass variables from javascript to a function. I have 2 textboxes and i can already get the values of these textboxes and store it to javascript variables:
var fname;
name = document.getElementById('fname');
var lname;
lname=document.getElementById('name');
now im stucked up on how i am going to construct it in a way that cakephp post method will be able to understand it. is it just the same with php like the code below?
var vars = "fname="+fname+"&lname="+lname;
here's my code:
if(window.XMLHttpRequest){
xmlVariable = new XMLHttpRequest();
}
else{
xmlVariable = new ActiveXObject("Microsoft","XMLHTTP");
}
xmlVariable.open("POST","save",true);
xmlVariable.send(vars);
"save" is actually a function in my cakephp where i wanna process the saving of "fname" and "lname" variables.
i need to do it in cakephp. Would there be any way?
Try with Params or data
Params variable is used to provide access to information about the current request.
public function save()
{
this->params['form']['lname'];
this->params['form']['fname'];
}
OR
Used to handle POST data sent from the FormHelper forms to the controller.
public function save()
{
this->data['lname'];
this->data['fname'];
}

Send JS object to JSP page [duplicate]

This question already has answers here:
Call Servlet and invoke Java code from JavaScript along with parameters
(3 answers)
Closed 6 years ago.
I have a JS object in a JavaScript file. I have to pass this object to a JSP page. The page picks up this object and processes it. How can I do it?
The same way you get any other data from a web browser to an HTTP server.
Encode it in an HTTP request by submitting a form / setting the window location / using XMLHttpRequest / etc.
There are a couple of issues you need to resolve first, are you doing this in an AJAX style of request? is this a form submission? is there going to be on-going interaction within the page-session between the client/server passing JSON objects back-and-forth?
Lets tackle the simple case of a form submission, once you get that you should be able to get the remaining cases going as they are just "extensions" of this base case. Say you have some form that will submit the data in some field:
<form name='my_form' id='my_ford_id'>
<input type='hidden' name='my_input_field' />
</form>
then at some point in time you have a piece of code that executes and you have your JSON object
function myFunction() {
var json_data = getJsonData();
document.forms['my_form']['my_input_field'].value = json_data;
document.forms['my_form'].submit();
}
You will then on the JSP side receive this data as a JSON string inside of a form field, at which point you need to process it, lets assume you have some kind of a JSON library available to you, the code might look something like this:
<%
String myInputField = request.getParameter("my_input_field");
if(myInputField != null) {
try {
JSONObject myObject = new JSONObject(myInputField);
}
catch(JSONException e) {
}
}
%>
If you need an "AJAX" style of interaction, you will be making a number of such requests in the page, but fundamentally it falls back to the original problem of submitting the data. Since you are using forms in this example, and JSP, you don't have to worry at any point about encoding, the browser/server will take care of things for you.
When you send json object the servlet receive it in the same way of receiving data sent by submitting the form, for example, if you send a variable "action" with value="getCountries"
var option = {
"action": "getCountries"
};
$.getJSON('YourServlet', option, function() {
//hadle the result returned by servlet
});
The defualt method is GET, in the servlet you handle the request as you handle a normal request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action != null) {
if (action.equals("getCountries")) {
List coutries = getAllICountries(request); //get the countries
String json = new Gson().toJson(coutries);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(json);
return;
}
}
}
Notice how we return the result from servlet to javascript, we return a json object.
"JSON" Site helps you to manage Json Objects in JSp/java.
You have to convert the string obtained from javascript to a json object.Then manage it easily.

Categories

Resources