Passing JS to PHP - javascript

I am trying to pass a string stored in a variable to a mysql table via php.
Currently I am using an <input> with type hidden, I assign the variable that I want as its value and post it through a form submit.
it is working but it's ugly.
I know there is $.post and $.ajax but I don't seem to figure out how to use them in the js side and php side. I have looked for them online and there are a lot of questions of this sort but none of them work for me (probably because I am missing knowledge)
How can I do it?

Here is a very basic example. We start out with a form on an HTML page. When this button is clicked, we are going to activate a javascript function.
<html>
<form>
<input type="email" id="email-field" />
<input id="submitButton" type="submit" value="Submit" />
</form>
</html>
Now, here is the javascript function being activated due to the button click. Inside, we extract any information that might have been filled out in the input field with id of "email-field", then send that off via ajax to a php file that sits on the server.
$('#submitButton').click(function() {
var email = $('#email-field').val();
$.ajax({
type: 'POST',
url: './yourphpfilename.php',
data: {
email: email
}
}).done(function(data) {
console.log(data) // Will send you the result that is echoed in the PHP file
})
})
As long as you put the correct url in your ajax request to your PHP file, you can easily receive the data being sent like so,
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'];
echo 'I have received your request.';
}
To send the data back, I use the echo command to do so here.
Try to read some documentation on the $_POST variable in PHP. Notice how I call for ['email']. The identifier inside the brackets directly correlates to the key inside the data object in the js file. For example, say we decided to name our email key something different in the js file.
data: {
useremail: email
}
You would then just change the PHP code like so,
$email = $_POST['useremail'];
This was very confusing for me starting out, and sometimes it's hard to even pose a quality question on it if you have no idea how it works. In the future though, I would atleast try to post some code showing that you attempted the problem.

There are several things you need to do:
You have a form tag and you need to prevent it from submitting, like this:
$("#myformid").submit(function(event) {
//Do something
event.preventDefault();
});
If your form is no longer submitted, then you are on the right track.
You need to use $.ajax to send the request, like this:
$("#myformid").submit(function(event) {
//Here I assume that all variables have been properly initialized
$.ajax({
url: "yoururl",
method: "POST",
data: yourdata, //yourdata should contain the things you intend to send to the server
}).done(function(response) {
//callback
});
event.preventDefault();
});
You will need a PHP code which will properly handle the POST request you send at yoururl. This is how you can check in PHP whether the request method was POST:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//It is a POST request
} else {
//It is not a POST request
}

Related

Exchange data between HTML page and Java servlet without page refreshing

I would like to create a simple login form with HTML and Java (and maybe JSON). So, I have a login form with several input fields with the following id-s: txtUsername, txtPasswd, btnLogin.
After click on the button (btnLogin) I would like to send data to the servlet, and get back just a true/false value deepends on the user-passwd combination.
I can write the HTML code of this form, and the server side code, but I don't know, how can I send and recive data without page refreshing.
Here is my frontend code:
<script>
function login(){
var user=document.getElementById("txtUsername");
var passwd=document.getElementById("txtPasswd");
//???
}
</script>
Username: <input type="text" id="txtUsername"/> <br/>
Password: <input type="password" id="txtPasswd"/> <br/>
<input type="button" value="Login" id="btnLogin" onclick="login()"/>
You have to use an AJAX request. One way of doing it is to wire up and event handler on a your login button (like onclick), which calls a JS function to use an Ajax request (XmlHttpRequest), just like you have started.
You can do it in vanilla Javascript, but it is easier to use a library like jQuery. The code would look something like this (with jQuery, note the '$'):
function login() {
$.ajax({
type: 'POST',
url: url, //Url of login endpoint
data: DATA, //Now here you would want to send a payload i.e. your username and password data
dataType: 'json',
contentType: 'application/.json',
success: function(data) {
//HERE 'data' would represent your true or false that came back from the server.
//You can do stuff here with the response
},
error: function(jqXHR, textStatus, errorThrown) {
//IF ERROR then this code would be executed.
}
});
}
Hope this gives you a starting point!
You must use jquery AJAX.
Here is a link to the official documentation: http://api.jquery.com/jquery.ajax/
Hope it helps.

Is it possible to prevent the header("location: url") from being sent to AJAX?

I've a html form on a page. The form data is sent via AJAX to a PHP script. Within this PHP script, each of the $_POST's from the inputs are checked conditionally using a variety of if statements. If the condition doesn't meet a specific strlen / other criteria then I echo a message into the AJAX returndata and exit() the PHP script.
Assuming all conditions are met, at the bottom of my PHP script I have applied a url that is built from variables within the PHP script itself and concatenated inside, like so:
header("location: view_topic.php?tid='".$tid."'&page='".$page."'");
The issue:
Since I am generating the url within the PHP script, and am only able to generate it in there, I am having to either use PHP header("location: ...") as a redirect, or having to echo the url, which in turn sends it to the returndata, then use window.location(returndata) in my JavaScript/AJAX.
I've done some homework and have noticed a known issue with the header method, when set is being sent to the AJAX returndata. This means that the entire header location page is being displayed in a tiny invisible div where I display my errors for the above mentioned conditional error messages generated in the PHP script.
The question:
In the below code is my alternative method of setting the window.location(returndata).
Here I am echoing the actual url generated by my PHP variables, which sends it to the returndata. However when submitting the form I am returned to the same page, and the returndata is simply echo'd out from the PHP at the top.
Does anyone know how to prevent the header("location: ..."); from being sent to the AJAX returndata, or have any other solutions on the method below?
Thanks in advance,
Richie.
My AJAX:
$("#topic_form").submit(function(event){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'create_topic_parse.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata.indexOf("view_topic") != true){
$('#message').css("color", "red").html(returndata);
} else {
window.location(returndata);
}
}
});
return false;
});
instead of returning html, return json:
{"action": "display","html":"..."}
or
{"action":"redirect","location":"url"}
and change:
success: function (response) {
if(response.action == "display"){
$('#message').css("color", "red").html(response.html);
} else if (response.action == "redirect") {
window.location(response.location);
}
}
I think that, If I understand correctly. You want to use create_topic_parse.php, to generate a URL which you would then like to be redirected to.
Currently the page you want redirecting to, is displaying in a div on your existing page and not redirecting.
I think that in your PHP file, if you echo a meta refresh instead of a header() then this should get you the results you want.
echo "<meta http-equiv=\"refresh\" content=\"0;URL=view_topic.php?tid=".$tid."&page=".$page."\">";
These have always worked as part of the body for me.

Scripts loaded through ajax don't send the post data to themselves properly?

So the structure is:
index.php
loads /index.php#ajax/landing.php
landing.php has a form, the form data is sent as post request (Tamper data show the POST data being sent), but var_dump($_POST); in landing.php is showing empty. I'm guessing because of the way the script is loaded the post data must be being sent to index.php and must not be accessible to landing.php?
is there a work around for this?
I've considered the possibility of using ajax to send the post data and show the result in a div but i'm not that good with it and don't really understand what i'm doing,
so in my scenario here is what i'm trying to do:
<form name="search_form" id="search_form" method="POST">
<input type="text" name="search" id="search" />
<input type="submit" name="submit_search_form" id="submit_search_form" value="search" />
</form>
<div id="search_results">
</div>
How would I make this send a POST request to /php/search.php then put the results of what the script does with the post data into the search results div?
Any ideas / help would be greatly appreciated.
note i'm asking for POST as GET/query strings can be accessed by the page, but isn't appropriate for other tasks like changing passwords so although in the scenario i've mentioned would be fine as a GET request, I need to figure out a way to get POST working regardless.
I use something like this (which requires jQuery):
$(document).ready(function() { // When the document is completely loaded this function runs
$('form').unbind('submit').bind('submit', function(event) { // catch the pressing of enter and catch submit action. Makes sure the form does not get posted the normal way
if (event.keyCode == 13) { // if enter is pressed
return false;
}
pageRetrieve($(this).attr('action')+"?"+$(this).serialize(), 'POST'); // send this data to the function that sends the post
event.preventDefault();
return false;
});
});
function pageRetrieve(href, sType) { // this function send the data to the server
sType = (typeof sType === "undefined") ? "GET" : sType; // if 'POST' is not set in the previous function, set it to GET
$.ajax({ // function to send the data to the server
url: href, // the url to send it to
type: sType, // the type (post/get)
success: function (data) { // when the server responds successful
$('#search_results').html(data); // put the data in your div
},
error: function () { // if call to server is not correct (eg wrong url)
alert("error");
}
});
}
This just posts data to the specified url in the form.

Only allow access to a php action through form submit, but when using an ajax call

i have a form that deletes the comment its in.
To only allow the page that carries out the php action to be viewed when the form is submitted i do a basic
if (isset($_POST['submit-delete'])) {
// carry out delete
}
this works fine, but i am using ajax to not reload the page.
The response is the same as i have used else where:
$(document).ready(function(){
$(".delrepcomment").submit(function(){
$.ajax({
type: "POST",
url: "process/deletecomment.php",
data: $(".delrepcomment").serialize(),
dataType: "json",
success: function(response){
if (response.commentDeleted === true) {
$('#successdisplay').fadeIn(1000),
$('#successdisplay').delay(2500).fadeOut(400);
}
else {
$('.delrepcomment').after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
});
});
This however doesnt work, unless i remove the check to see if the form has been submitted.
Whats the best way around this? I want to keep the check for the form being submitted incase of js being turned off or any direct access attempts.
Thanks.
You should post the data you require for the script to work. In your case, you have to post a key-value-pair with "submit-delete" as the key and an arbitrary value (unless you check that value later in the code).
On the other hand, PHP stores the used HTTP method in $_SERVER['REQUEST_METHOD'], this would be "POST" in your case.

Passing a (Sinatra) Ruby value to Javascript

So, i'm making a subscribe form.
Jquery
$("<div id='dialog' title='Subscribe!'> <form id='subscribe_form' method='POST' action='/user/subscribe'>" +
"<input type='text' name='subscribe_email' id='email' placeholder='Email Address'> <br/>" +
"<button id='submit_subscribe_form'>Submit</button></p><p id='ruby_bool'></p></form>" +
"</div>").appendTo($("#subscribe"));
When this form is submitted, it sends an ajax call to a Ruby Sinatra listener (sorry if I'm not using the right terminology, haven't really been taught Sinatra, just shown how to use it)
$('form').submit(function(){
$.ajax({
type: "POST",
url: "/user/subscribe",
data: $('form').serialize(),
success: function()
{
Ruby Code
post "/user/subscribe" do
user_Information = EmailList.new
if params[:subscribe_email] =~ /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/
user_Information.email = params[:subscribe_email]
puts user_Information.save
#email_validation_result = "True"
else
#email_validation_result = "False"
end
puts #email_validation_result
(Yes i know i shouldn't use regex, but the engines i could find were for PHP)
I want to use the #email validation result so i can know what to put in my success: call in my ajax. Problem is, JavaScript doesn't allow Ruby Injection (according to my god knows how many hours of research) and i cant update a div on the web page that contains that variable async. I want to do this all async, so there is no refreshing of the entire page whatsoever. (If it's not possible otherwise i will concede, but i highly doubt that). I tried to put the div on another page and use the JQuery .load() function, but .erb files aren't recognizable.
Out of ideas and nearly out of sanity.
Thanks!
JavaScript:
$.post( '/user/subscribe', $('form').serialize(), function(data){
// Do whatever you want with the response from the server here
// data is a JavaScript object.
}, 'json');
Ruby/Sinatra:
require 'json' # just for a convenient way to serialize
post '/user/subscribe' do
# process the params however you want
content_type 'application/json'
{ :ok => #is_ok }.to_json
end
Without the JSON library you could end your method with just some valid JSON markup, like:
%Q[ { "ok":#{#is_ok} } ]
JavaScript/AJAX will post to the server, the matching Sinatra route will process the request, and the string result of that method (not done via puts) will be sent as the response to the method. The jQuery AJAX handler will receive it, parse it as JSON and invoke your callback function, passing the JavaScript object it created as the parameter. And then you can modify your HTML DOM as desired, client side.

Categories

Resources