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.
Related
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
}
Currently I've been Ajaxing a route that renders a Twig template via a Controller and injecting it into the page - all is well.
return $this->render('MyBundle:Requests:results.html.twig', array('system' => $lc_system));
However, in my JavaScript, I would like to get some extra information returned... Specifically I want a count of the results, so I can check it against a JS variable. I could put it into the twig file and then get it in JS that way, but it feels horrible.
Is there any way to get any variables sent down with the Ajax response, or a best practice way to approach this.
Use echo in your PHP function instead of return.
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function() {
doSomething(data); //Data is output
}
});
In PHP:
<?php
$output = some_function();
echo $output;
?>
It's an argument passed to your success function.
The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation.
If you weren't returning actual page content in your response, I'd say to return a JSON response and call it good. But since you're already using your response body for some HTML, you have to come up with another way to return the info.
One approach I've used in the past is to add a custom HTTP header and return my "meta" values that way. First, set the header in your PHP (make sure this happens before any output):
header('X-MyCustomHeader: ' . $phpVar);
Then, you can get it in your jQuery success method like this:
success: function(result, status, xhr) {
var customHeader = xhr.getResponseHeader('X-MyCustomHeader'));
}
While you can technically name your custom header anything you want, see this post for best practice/naming convention ideas:
Custom HTTP headers : naming conventions
This post by #BenjaminRH (How to change/edit the text of a paragraph/div using jQuery?) provides exactly the sort of functionality I'm trying to build on.
By clicking on a button, a new paragraph is created on the page, which can be edited and saved to the page.
I want to save it to a database. When I look at the page source after editing, I don't see the changes there, which doesn't surprise me... but I don't know where to "capture" the changed text so that I can validate and post to mySQL.
JQuery is a javascript library - which runs client side. If you wanted to save that data into the database - you would have to send it to the server (php/asp/mvc etc) using ajax and then insert the data into the database.
See the jquery Ajax function for details on how to accomplish sending data asynchronously.
Create the data in javascript that you want to show and save in database.
Wrap the data in JSON and use ajax to POST the data to the server side code
Server-side retrieve the posted data and parse it into something usable
Server-side write a script to insert the data into the database.
Handle any errors that may occur.
Pseudo-code:
// step 1
var someData = 'this is my data';
$("#myDiv").html(someData);
// step 2
$.ajax({
type: "POST",
dataType: 'json', // <-- if the data is complex and needs to be object-oriented
url: "some.php", // <-- that is the file that will handle the post server-side.
data: JSON.stringify({ someData }) // <-- just pass someData if your data is not complex
})
.always(function(jqXHR, textStatus) {
if (textStatus != "success") {
// step 5: handle error.
alert("Error: " + jqXHR.statusText); //error is always called .statusText
} else {
alert("Success: " + jqXHR.response); //might not always be named .response
}});
OK, I've managed to solve it for myself, without using ajax. I took the example from (How to change/edit the text of a paragraph/div using jQuery?) and modified it by placing the elements in an (html) form.
The second modification was to use <textarea> elements, not <p> elements, as <p> elements cannot be posted.
As #caspian pointed out (in the comments) those two steps do populate the $_POST array and away we go.
I have a fairly complex PHP script in place, and I need to embed a very small JavaScript prompt inside of this code.
This is my criteria / requirement:
I want this JavaScript code to execute when a certain set of criteria is met.
I do NOT want to execute this code with any kind of submit button.
I currently have the PHP code calling the JavaScript prompt correctly.
The JavaScript comment / variable is being initialized, and stored properly, within the JavaScript code itself.
The parent PHP code is waiting for the JavaScript input, and does not continue until the prompt text has been entered.
But, I have not been able to figure out how to pass the JavaScript variable back to the parent PHP code.
What I have so far is very simple, but it is working exactly as I intended:
function getReprNotes() {
?>
<script>
var REPRNOTES = prompt('Please enter any appropriate reprocessing request notes');
alert(REPRNOTES);
</script>
<?php
}
getReprNotes()
Note that I want to pass the REPRNOTES text / variable back to the parent script.
Can anyone tell me how I need to do this, using the above code?
Keep in mind javascript is client side scripting, and php is server side. The only way for you to send information to PHP is by making a call to the server, the best way to do this from the client using javascript without submitting a form is by is using AJAX.
Take a look at these tutorials: 5 Ways to make AJAX calls with jquery and 24 best practices for AJAX implementations.
This is what AJAX calls are for. Split your PHP into two and have the javascript issue an ajax call which triggers the second. If you can use jQuery then you want to make a $.ajax() call: https://api.jquery.com/jQuery.ajax/
If you can't or don't want to use jQuery you can still make ajax calls through XMLHttpRequest objects: http://www.w3schools.com/Ajax/default.asp
$.ajax({
url: '/to-some-url',
data: 'data=' + value,
type: 'POST',
success: function (response, textStatus, jqXHR) {
if (jqXHR.status > 0) {
// do something here
}
}
});
You can use jquery ajax method to pass javascript variable value to php by post(or get). But I don't understand what you really want to achieve
I'm using thymeleaf and spring 3 mvc.
When I try to perform Ajax POST request I don't understand how can I show a response message from a controller on my html page:
Here's a code snippet:
$.ajax({
type: "POST",
url: "/settings",
data: "request=" + request,
success: function (response) {
$('#msg').replaceWith('<div id="msg" th:text="response"></div>');
},
});
'response' is a i18n message from controller. Now, I want to show this message at using thymeleaf (th:text="response"). Of course, this code does not work, because it thinks that response variable is a plain string.
The question is how to show i18n response message using thymeleaf. Or maybe there are some other methods to show i18n messages on html page (not using jsp) through js?
Thymeleaf attributes (such as th:text) will only be parsed and replaced on the server. Since this ajax response is processed on the browser, th:text will not process. If "settings" is already a Thymeleaf-resolved page, it is likely already i18n'd and you can simply do something like:
$('#msg').html(response);
However, if you are truly looking for client-side javascript processing of Thymeleaf tags, consider Thymol.