How to get information from Javascript to MySQL database using PHP? - javascript

(NEWBIE ALERT)
Hello! I am working on developing a database that stores information that people enter onto these online surveys. I don't have experience with Javascript, but I have worked with PHP and MySQL before. I am currently stuck on how to store the data to the database. Here are a few things about the code:
The person that created the online surveys had the online surveys written in Javascript (saved as HTML files)
Each survey is written in a separate file
Each survey has multiple data to be stored
Every time the user hits the next button, it goes to another page of the survey
I've worked on a project similar to this before, but my forms were only a page, so whenever the user clicks the "Submit" button, I had it go to another webpage written in a separate PHP file (kind of like a "results" page).
WHAT I DON'T UNDERSTAND/NEED HELP ON:
How do I make this so that when the user hits the "Next" button, it not only goes to the next page (what it's doing right now), but also sends the info to be stored in the database?
These surveys should be filled by people on their own computers so the surveys are written in JS (client-side). The storing part should be written in PHP (server-side) and MySQL, correct? Does this mean that I have to create a separate PHP file to create the code for transferring the data to the database or can it all be done in the same file? (I would think that I would need to create a separate file, one for each survey.)
Here's a general structure of how the HTML file:
<!DOCTYPE html>
<html>
<head><link rel="stylesheet" type="text/css" href="survey.css">
<script>
function Q2(){
document.getElementById("Q").innerHTML = "does something...<button type='button' onclick='Q3()'>Next</button>";
function Q3(){
document.getElementById("Q").innerHTML = "does something...<button type='button' onclick='Q4()'>Next</button>";
function Q4(){
document.getElementById("Q").innerHTML = "does something...<button type='button' onclick='Q5()'>Next</button>";
//keeps going until the last question
</script>
</head>
<body>
<h1>Meeting 1</h1>
<p id="Q">Some text...<br><input type="text" name="tweet" style='height: 50px;width: 500px;'><br><br>
<button type="button" onclick="Q2()">Next</button>
</p>
</body>
</html>
I've done a bit of research and looked at a few textbooks. I think AJAX may be something that I need to use? But I'm not too sure. If possible, could someone explain to me what I should be doing? I would like to not only be able to find a solution for this, but understand it as well.
Thank you in advance!!

For sending data to a PHP page using JavaScript, I'd recommend using the jQuery framework, where you can do it in as simple a code as this:
function Q2(){
var tweet = $("input[name='tweet']").val();
$.post("your_receiving_page.php", { data : tweet }, function(response){ //POST to PHP page where $_POST["data"] is the tweet variable
//deal with PHP output here
console.log(response);
if(response=="success"){
//javascript code to go to next page etc.
}
}
}
That way, you make a PHP file called "your_receiving_page.php" (or whatever) and handle the posted data like so:
<?php
$tweet = $_POST["data"];
//do stuff with $tweet, e.g. put it in a database
//...
//then end the code with "success", which is what you're looking for in the JavaScript as a successful callback
exit("success");

Related

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

How to get a DIV element from an external webpage in HTML file?

Apologies in advance if this question has been asked earlier. I did find some similar questions on web but I couldn't figure out the answer still. You can say I have never dealt with anything beyond basic HTML. So any help would be appreciated.
I have a HTML file (Say text.html) only for personal use. In the file, there will be an input box for entering text and a submit button. I want that if I clicks on submit, it opens a particular hyperlink from an external webpage based on the input text. I guess it's like "I am feeling Lucky" of Google.
Example: If the user enters "Test" and clicks on Submit, it should open the second result from the page "https://www.google.com/search?q=test"
Here is my HTML:
<!DOCTYPE html>
<html>
<body style="background-color:beige">
<h1 style="text-align:center"><font size="14">Test</font></h1>
<style type="text/css">
</style>
<form id="form">
<div align="center" style="vertical-align:bottom">
<input type="text"
value="Test"
id="input"
style="height:50px;width:200px;font-size:14pt;">
</div>
</form>
<TABLE BORDER="0">
<TD><button class="button" id="button01">SUBMIT</button></TD>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button01').click(function(e) {
var inputvalue = $("#input").val();
window.open("https://www.google.com/search?q="+inputvalue);
});
</script>
Also, here is the example of the div element from the page on which the hyperlink I want to open is on:
<div id="XYZ" class="contentEditValue" style="float:left;width:180px;">
2nd Result
</div>
I have read that it can be achieved with PHP or Jquery and all but they are not something I have ever worked on. Thank you very much in advance for any help!
Appreciate any other alternatives as well.
You shouldn't be able to do that because of security. If that (reading content from iframes, other browser windows...) would be possible, an attacker could add JS keylogger to your internet banking login or read your messages on Facebook. CORS (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is used to block these requests and if the website doesn't say explicitly that you are allowed to do something with its content, most browsers won't allow you that.
You have are missing a }); to close the ready() function
<script type="text/javascript">
$(document).ready(function(){
$('#button01').click(function(e) {
var inputvalue = $("#input").val();
window.open("https://www.google.com/search?q="+inputvalue);
});
});
</script>
Here's a basic example of how to do this in PHP.
Taking JavaScript/JQuery out of the picture, let's just say you have a basic form:
<form>
<input type="text" value="Test" name="input">
<input type="submit">
</form>
Without specifying action or method attributes on the <form> tag, the form will make an HTTP GET request to the URL of the page it is on, so for this example the PHP code will be on the same page as the form. Here's a more detailed description of sending form data if you're interested.
Now that you have a way to pass the input to the PHP script*, there are three basic parts to this problem.
Make a request to the page you want with a query string including your input
http_build_query is an easy way to construct a properly encoded query string to use with your request. For this example we'll use file_get_contents to make the request. There are other ways to do it, including cURL, but let's keep it simple.
$query = http_build_query(['q' => $_GET['input']]);
$page = file_get_contents('http://www.example.com/?' . $query);
I'm not using Google for this example because it's a bit more complicated to find the right links in the response and follow them. (Partially because they don't really want you to do it that way.)
Find the link you want in the response
Don't try to find the link in the response with regex. You'll have problems with it, come back to Stack Overflow to try to solve them, and people will tell you that you shouldn't be using regex, so just skip that part and use a DOM parser.
$doc = new DomDocument;
$doc->loadHTML($page);
$links = $doc->getElementsByTagName('a');
$url = $links[0]->getAttribute('href');
I used getElementsByTagName() to find links, but if the page is more complex an xpath query will work better. Also, I used the first link ($links[0]) because example.com only has one link. $links[1] would get you the second link if it existed.
Follow the link
header("Location: $url");
exit;
If everything goes well, you'll end up where you want to be. But there are a lot of things that can go wrong. If you're requesting a resource that you have no control over, it can change at any time without any advance warning to you, so your code that finds the link may stop working. You may get blocked from making requests. Scraping links from sites like this violates the terms of service on many sites, so check that out beforehand. You may find that the site offers a web API, which should be a much better way to access its content than this.
*You don't really need a form for this; you can just pass the input parameter in the URL to your page.

php javascript ajax passing variables from mysql form

I have a form that gets data from a database and displays the results as buttons with the appropriate names. When i add javascript onclick i can diaplay the data_id. This all works but i want to be able to save the data to the main page in a textfield but it doesnt show anything? What code do you need to see or is it because i am loading an external php file to load the data that it isnt posting it past. Its doing my head in, I will post what code you want, i already have but had no joy.
For instance if i have a textfield called 'testField1' in my main page and on the same page i am getting a list of data from forms and mysql and the end is kicking out
<input id="button1" type="button" value="<?php echo $product_name; ?>" onclick="display()">
I want it to diplay that data in the main page 'testfield1' using the script
<script>
function display()
{
document.getElementById("textField1").value = "$product_name";
}
</script>
the code online is www.cheekytransport.co.uk/show.php

jQuery Auto-submit form inside of a <div> loads in new page

I'm developing a project of "prettifying" of a part of an existing web application. There is a need of putting the existing code: search criteria form in one div, and search results in another div (forming a kind of tabs, but that's another story).
Using jQuery I was able to manage that, but right now I am struggling with the results page, which by itself is yet another form that auto-submits to another file (using document.form.submit()), which is the final search results view. This auto-submit causes that the final view quits the destination div and loads as a new page (not new window).
So, the flow is like that:
First file, let's call it "criteria.html" loads the search criteria form (inside of a div) + another div (empty) destined to be filled with search results.:
<div id="criteria">... form with search criteria here...</div>
<div id="results"></div>
On submit, using jQuery's "hide()" method, I hide the first div (surrounding the search criteria form), and make Ajax call to the second file, let's call it "results.php":
<script>
$("#criteria").hide();
$.ajax({
...,
url: "results.php",
success: function(data){
$("#results").html(data);
},
...
});
</script>
results.php searches according to given criteria, and displays an "intermediary form" (which returns as a data result of the ajax query above) with a lot of hidden fields, and at the end executes:
<script>document.form.submit();</script>
which submits to another file, let's call it "resultsView.php"
This line causes that a result page shows outside the div "results", as a new page.
As there is a lot of logic in those files (more than 700 lines each), the idea of rewriting this monster just gives me creeps.
And now the question: is this a normal behavior (opening the result outside div)?
I tried removing the document.form.submit() code and everything works fine (well, without showing the results from "resultsView.php"). It's this line that causes the viewport to reset. I also tried with empty pages (to eliminate the possibility of the interaction with contents of the pages) - still the same result.
I hope there is not too much text and the problem is clearly stated. Every suggestion of how to fix this will be greatly appreciated.
If I understand your question correctly, you need to process the final submit using ajax instead of <script>document.form.submit();</script> so that you can handle the results on-page. Traditional form submits will always reload/open the action page. If you want to avoid that you'll have to control the form submit response via ajax and handle the results accordingly... like you are doing with the first submit.
The only alternative I can think of is to make div id="results" an iframe instead, so that it contains the subsequent form submit. Of course, that unleashes further restrictions that may cause other troubles.
I am not sure if I understood your question, but maybe u can do something like this.
This is my JQuery script: [I just wait for the submission search. When it happens, I use the $.Post method to call a function that should return the Html results (You can include somenthing to hide any field you want using JQuery or css)].
<script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#searchForm").submit(function() {
var theCity = $("select#chooseCity").val();
var theName = $("input#searchInput").val();
$.post("callProvideSearchResults.php", {theCity: theCity, theName: theName}, function(data) {
$("div#searchResults").html(data);
});
return false
});
});
</script>
This is my Body: {it consists of the choice of a city, the a form to provide the name of the person you are lookng for and the place to provide the results.
<body>
<FORM id="searchForm">
<h2>Select the city: </h2>
<select id="chooseCity">
<?php
$theCitiesOptionsHTML = "cityOptions.html";
require($thePathDataFiles.$theCitiesOptionsHTML); / A large list of cities
?>
</select>
<h2> What is the name of the person </h2>
<P> <INPUT id="searchInput" TYPE="TEXT" SIZE=50></P>
<P><INPUT TYPE="submit" VALUE="search"></P>
</FORM>
<div id="searchResults">
<!-- Here: Search results -->
</div>
</body>
// Function callProvideSearchResults.php // Just call the function that makes all the job and echo the $Html page
<?php
include "provideSearchResults.php";
$theName=$_POST['theName'];
$theCity=$_POST['theCity'];
echo provideSearchResults($theName, $theCity);
?>
// provideSearchResults.php // Database connection and search
<?php
function provideSearchResults($theName, $theCity) {
include "databaseConnection.php";
//database Queries
// Generate $theHtml using strings or ob_start, for instance
return $theHtml;
}
?>

Everytime a page is refreshed i lose data, but i want to keep the last textbox value

i was working on a program that i wrote in php, all is fine, the problem is the html page:
it has 1 textbox and 1 button.
In the textbox i have to write a link
when i load the page it clicks the button automatically, so i can use the php program, then it return back to the html page..
$(document).ready(function(){$('#printbuttoncustomer').trigger('click');});
The links that i need to use are always the same, except the number, example:
http://www.wowhead.com/npc=56843 --- http://www.wowhead.com/npc=56844 etc..
the problem is that everytime the page is loaded, it start to use always the link and can't go on with the next link with the new value
how can i solve this problem?
I think that i could use a txt file to save the last link i used, so in the html i can check the last link in the txt file and set the next value in the textbox.. But don't know how to do.
the code to start is this
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="jquery-2.0.2.js"></script>
</head>
<body>
<form method="POST" action="parser.php">
<input type="text" id="testo" name="testo">
<input type="submit" id="button" >
</form>
<script>
$(document).ready(function(){
$('#button').trigger('click');
});
</script>
</body>
</html>
convert the html page to php. When returning to this page from "parser.php", send back a response with next link and save that in the text field.
You can save the link in a session and not a file :
$_SESSION['URL'] = "Your URL HERE"
next time you read it like this:
var $MyUrl = $_SESSION['URL'];
Please check this link for more on PHP Sessions.
Since you have to persist the information of your last clicked page so that next time you load the page it goes to next page.
You can do this by two ways:-
*Server Side Change:-
You can implement sessions to store the information, where you store the last URL.
*Client Side Change:-
After HTML5 there are a lot of browser storage is available. So you can use local storage, it stores site specific data in browsers persistent memory. Also there is session storage available.Check this page for HTML5 Web Storage.

Categories