Form Information to Appear On Another Page - javascript

I am trying to create a form that, once submitted, will be sent to my index.html page for other users to view. I want it so multiple users anywhere in the world can submit information and so the website displays all their information at once.
Here is my submit page's PHP code:
<form action="submit_a_message.php" method="post">
<textarea name="message" cols="60" rows="10" maxlength="500"></textarea><br>
<input type="submit">
</form>
I am trying to figure out how to make the information submited via that form appear on my index.html page. This is the code I found online, but it doesn't work. Why?
<?php>
string file_get_contents ( string $submit_a_message.php [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
<?>
Any help would be greatly appreciated.

To make submitted text avaliable on your index page, you need a place where you would store it. You can use MySQL base to do that, or (if you can't or you really don't want) you can use text file with your texts/posts (that is not really good way, i warned you).
To do that with MySQL you can use a code like this on your submit_a_message.php:
<?php
//connection to database and stuff
...
if $_POST['message'] {
$message = $_POST['message'];
$sql = "insert into `mytable` values $message"; //that is SQL request that inserts message into database
mysql_query($sql) or die(mysql_error()); // run that SQL or show an error
}
?>
In order to show desired vaues from table use above-like idea, your SQL request would be like select * from mytable where id = 123

if your not married to the idea of using php and learning how to manage and access a database you could use jquery and a trird party backend like parse.com
If your new to storing and retrieving data, I would definately reccomend the services that https://parse.com/ offeres. It makes storing and retrieving data trivial. Best of all, the service is free unless your app makes more than 30 API requests per second. I have an app that 61 users use daily and we have never come close to the 30 req per second limit.
To save your info, you could write:
$('document').ready(function(){
$('#submit_btn').on('click',function(){ // detect button click, need to add "submit_btn" as the id for your button
var Message = Parse.Object.extend("Message"); //create a reference to your class
var newObject = new EventInfo(); //create a new instance of your class
newObject.set("messageText", $("#myMessage").val()); //set some properties on the object, your input will need the id "myMessage"
newObject.save(null, { //save the new object
success: function(returnedObject) {
console.log('New object created with objectId: ' + returnedObject.id);
},
error: function(returnedObject, error) {
console.log('Failed to create new object, with error code: ' + error.message);
}
});
});
});
Retrieving that info later would be as easy as:
var Message = Parse.Object.extend("Message"); //create a reference to your class
var query = new Parse.Query(Message); //create a query to get stored objects with this class
query.find({
success: function(results) { //"results" is an array, you can fine tune your queries to retrieve specific saved objects too
for (var i = 0; i < results.length; i++) {
var object = results[i];
$(body).append("Message #" + (i+1) + object.get("messageText");
}
},
error: function(error) {
console.log("Failed to complete Query - Error: " + error.code + " " + error.message);
}
});

Related

AJAX jQuery not working when querying to the database

In my code, I get the first_name, last_name, email and password from the user. Then, I get the location of the user with his/her consent in the second page. So, I save all the information of the first page as session variables. Then, I have a button that looks like this:
<button onclick="signUp()" class="btn btn-primary"> Let's go! </button>
And, the signUp function looks like this:
function signUp(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post("/sign-up-user",
{
user_latitude: latitude,
user_longitude: longitude
}, function(data){
alert(data);
});
}
And, I have the route for the request as:
Route::post("/sign-up-user", "PagesController#signUpFinalUser");
And, my PagesController function signUpFinalUser looks like this:
// Finally acquire the user with location and store him/her in the database
public function signUpFinalUser(Request $request){
// Get all required variables
$final_first_name = Session::get("user_first_name");
$final_last_name = Session::get("user_last_name");
$final_email = Session::get("user_email");
$final_password = Session::get("user_password");
$final_latitude = (float) $request->user_latitude;
$final_longitude = (float) $request->user_longitude;
// Create a new instance of the User model
$user = new User;
// Fill all the required columns of the database of the user
$user->first_name = $final_first_name;
$user->last_name = $final_last_name;
$user->email = $final_email;
$user->password = $final_password;
$user->latitude = $final_latitude;
$user->longitude = $final_longitude;
// Save the user i.e store the user in the database
$user->save();
// Get the id of the user
$user_id = $user->id;
// Destroy all the sessions variable
Session::destroy();
// Create a session variable named 'user_id'
Session::put("user_id", $user_id);
// Return a response back
return 1;
}
But, the problem is, it shows an error that looks like this:
jquery.min.js:2 POST http://localhost:8000/sign-up-user 500 (Internal Server Error)
But, the surprising thing is, when I comment out the database query and run it again, the response data i.e "1" gets alerted. So, what am I doin wrong?
You destroed session before put user_id
// Destroy all the sessions variable
Session::destroy();
// Create a session variable named 'user_id'
Session::put("user_id", $user_id);

Can't show data in javascript console

I have a registration form in my Laravel project. I submit that registration form data to laravel controller using ajax from javascript. After successfully stored those registration data in database I return the insertedID from controller to javascript and use console.log() function to show that id. In my javascript, console.log() shows that id and auto disappear after half mili second. But I don't want it to disappear.
Here is my js code
var name = $('#reg_name').val(); //reg_name is the id of the input field
var email = $('#reg_email').val(); //reg_email is the id of the input field
$.get( 'signup', {'name': name, 'email': email,'_token':$('input[name=_token]').val()}, function( data )
{
//Here 'signup' is my route name
console.log(data);
});
Here is my controller function
public function signup(RegistrationFormValidation $request)
{
$data = new User();
$data->name = $request->name;
$data->email = $request->email;
$data->save();
$lastInsertedId = $data->id;
if($lastInsertedId > 0)
{
return $lastInsertedId;
}
else
{
return 0;
}
}
Here I concise my code.
What's the problem in my javascript ?
If you are loading a new page, the default behaviour of the Chrome Dev Tools is to clear the logs. You can enable the Preserve log checkbox at the top of the console to prevent this behaviour.
In other situations, the data emitted to the console is modified after the logging to reflect subsequent updates. To prevent this, one can log a JSON serialized version of the data:
console.log(JSON.stringify(data))
(but probably this is not your case).

How to load a php file correctly using jquery

So allow me to first say I have looked at previous questions, and none of them have helped me out. My problem is as follows, I have an html file with a form which calls a javascript function to load a php file.
The form looks as following:
<form method="GET" id="submission" >
<div class="form-group">
<label for="q">Search Term:</label>
<input type="text" class="form-control" id="q" name="q" placeholder="enter a keyword">
</div>
<div class="form-group">
<label for="location">location</label>
<input type="text" class="form-control" id="location" name="location" placeholder="lat,long">
</div>
<div class="form-group">
<label for="locationRadius">Location Radius:</label>
<input type="text" class="form-control" id="locationRadius" name="locationRadius" placeholder="25km">
</div>
<div class="form-group">
<label for="maxResults">Max Results:</label>
<input type="number" class="form-control" id="maxResults" name="maxResults" placeholder="0 to 50">
</div>
<button type="submit" id="submitButton" >Submit</button>
</form>
The JS function responsible for sending is the following:
function sendData() {
var keyword = document.getElementById("q").value;
var location = $('#location').value;
var locationRadius = $('#locationRadius').value;
var maxResult = $('#maxResults').value;
alert("keyword is: " + locationRadius);
$.get(
{
type: 'GET',
url: '../php/geolocation.php',
data : {q: keyword, location: location, locationRadius: locationRadius, maxResults: maxResult}
},
function (data) {
//alert("Data loaded " + data);
document.getElementById("geolocation-results").innerHTML = data;
}
);
}
$(document).ready(function() {
$("#submission").submit(function() {
sendData();
return false;
});
});
SO my problem is two fold, how to call it in an ajax like manner as the above format worked for my old code, but for some reason refuses to function correctly for this one. And how should I fetch the php data? The php code is below:
It is a modified version of youtube's geolocation example code.
<?php
/**
* This sample lists videos that are associated with a particular keyword and are in the radius of
* particular geographic coordinates by:
*
* 1. Searching videos with "youtube.search.list" method and setting "type", "q", "location" and
* "locationRadius" parameters.
* 2. Retrieving location details for each video with "youtube.videos.list" method and setting
* "id" parameter to comma separated list of video IDs in search result.
*
* #author Ibrahim Ulukaya
*/
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
$htmlBody = null;
// This code executes if the user enters a search query in the form
// and submits the form. Otherwise, the page displays the form above.
if (isset($_GET['q'])
&& isset($_GET['maxResults'])
&& isset($_GET['locationRadius'])
&& isset($_GET['location'])) {
/*
* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$DEVELOPER_KEY = 'AIzaSyC6q-84bJv9HWCUDT4_SQ5Bp9WFJW2Z-e4';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
try {
// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'type' => 'video',
'q' => $_GET['q'],
'location' => $_GET['location'],
'locationRadius' => $_GET['locationRadius'],
'maxResults' => $_GET['maxResults'],
));
$videoResults = array();
# Merge video ids
foreach ($searchResponse['items'] as $searchResult) {
array_push($videoResults, $searchResult['id']['videoId']);
}
$videoIds = join(',', $videoResults);
# Call the videos.list method to retrieve location details for each video.
$videosResponse = $youtube->videos->listVideos('snippet, recordingDetails', array(
'id' => $videoIds,
));
$videos = '';
// Display the list of matching videos.
foreach ($videosResponse['items'] as $videoResult) {
$videos .= sprintf('<li>%s,%s (%s,%s)</li>',
$videoResult['id'],
$videoResult['snippet']['title'],
$videoResult['recordingDetails']['location']['latitude'],
$videoResult['recordingDetails']['location']['longitude']);
echo $videos;
}
//$htmlBody = <<<END
// <h3>Videos</h3>
// <ul>$videos</ul>
//END;
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
}
?>
It appears that the problem is your attempt to specify an non asynchronous request. I believe these are blocked by current/modern browsers. If you check your javascript console, you will probably see an error like this:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
If you remove that, I believe it will work as before (if it worked earlier, as you indicated). jQuery ajax requests are asynchronous by default, so if you remove that line, it will operate asynchronously.
(This wasn't part of your question, but you might consider leaving your input field's value="" blank, and put your helper text in placeholder="" attributes instead. These will provide the clue to your users without the risk of having that information passed in your request.)
As for displaying the result of the call, having your call return HTML and simply displaying that HTML on your calling page should work. Since you're using jQuery you could simplify your code like so: $('#geolocation-results').html(data); You may need/want to specify dataType: 'html' in your call as well. (https://api.jquery.com/jquery.get/)
Oh my. So obvious now. I believe your structure of the .get call is wrong. Should be like this:
$.get(
"../php/geolocation.php",
{
q: keyword,
location: location,
locationRadius: r,
maxResults: maxResult
},
function (data) {
$('#geolocation-results').html(data);
}
);
Checking that now... Okay, after rushing a bit too much I can confirm that the $.get() call was just structured wrong. Correct it as shown above and it will call the PHP file correctly and display the output in the geolocation-results element.
I think there are some mistakes in your code. You don't need to put async (and not asynch) as false because it's blocking the client browser for nothing. Be also careful to your url parameter which should not contains any quotes. Finally, you should put your trigger on the submit event more than on the onclick event because you can submit the form just by pressing Enter without clicking on your button.
You can try with this javascript :
function sendData() {
var keyword = document.getElementById("q").value;
var location = $('#location').value;
var locationRadius = $('#locationRadius').value;
var maxResult = $('#maxResults').value;
alert("keyword is: " + keyword);
$.get(
'../php/geolocation.php',
{q: keyword, location: location, locationRadius: locationRadius, maxResults: maxResult},
function (data) {
alert("Data loaded " + data);
document.getElementById("geolocation-results").innerHTML = data;
}
);
}
$(document).ready(function() {
$("#submission").submit(function() {
sendData();
return false;
}
});

change the connector type from javascript to Database Reader in javascript mode mirth?

When change the connector type from javascript to Database Reader in javascript mode, I recivied an error
Received invalid list entry in channel expected Map
how to use List<Map<String, Object>> or ResultSet instead of java.util.ArrayList() .
var dbConn = globalMap.get('tes55');
if (dbConn == null || !dbConn.getConnection().isValid(1))
{
var dbConn = DatabaseConnectionFactory.createDatabaseConnection('oracle.jdbc.driver.OracleDriver','jdbc:oracle:thin:#10.123.117.203:1521/UAT','intg','intg');
dbConn.getConnection().setNetworkTimeout(java.util.concurrent.Executors.newFixedThreadPool(1), 30000);
globalMap.put('tes55',dbConn);
}
dbConn.setAutoCommit(false);
try{
var x="select IH_HL7_OUM_ID, MESSAGE_ID, frame_text from ideal.EHS_Acks_MESSAGES s WHERE (message_type = 'S12' or message_type = 'S15' or message_type = 'A04' or message_type = 'A11') and rownum<=2";
var rs=dbConn.getConnection().createStatement().executeQuery(x);
var msgs=new java.util.ArrayList();
while(rs.next()){
var IH_HL7_OUM_ID=rs.getString("IH_HL7_OUM_ID");
var MESSAGE_ID =rs.getString("MESSAGE_ID");
var frame_text =rs.getString("frame_text");
// logger.info(MESSAGE_ID);
//logger.info(IH_HL7_OUM_ID);
// logger.info(frame_text);
msgs.add(frame_text);
//map.set(frame_text);
var query="update ih_hl7_outbound_messages set IS_SENT= 2 where MESSAGE_ID ="+MESSAGE_ID+" and id<="+IH_HL7_OUM_ID;
var update=dbConn.executeUpdate(query);
//logger.info(update);
dbConn.commit();
//logger.info(query);
}
rs.close();
return msgs;
}
catch(exp)
{
returned_response = ResponseFactory.getQueuedResponse("Failed to execute the query " + "\nReason: " + exp.message);
logger.error(exp.message);
alerts.sendAlert("\n\nMessage ID: " +$('msgID') + "\nMessage type: " +$('msgtype')+"\nException: "+exp.message +"\nMessage :\n"+msgs.add(frame_text));
try{dbConn.close();}catch(ignore){logger.info("Close Connection: "+ignore.message);}
}
finally
{
try{rs.close();}catch(ignore){logger.info("Close Cursor: "+ignore.message);}
}
return returned_response;
Mirth Database Reader will ease you data fetching process. We need not write many codes and complicate in the source listener
You can see URL specified you can select the DB type you want, in your case it's oracle, automatically the URL will be filled. provide your username and password to access the DB.
click on "select" button over the SQL text area this will open a pop-up displaying all the tables to be selected. once you click tick on the tables you want. The code will be generated automatically.
If you want to do join or perform any query operation you can do that there in the generated code on the text area content.

Firebug doesn't show JSON tab in console

I am debugging my javascript code (below).
The webgrid is populated after a user has clicked the search button. I have added a button to the webgrid which opens a dialog that has to be populated with values from a JSON object.
This is where the problem is - when I debug using firebug the JSON tab in the console is not shown.
Below is the part of my code:
$('.edit-recipients').live('click', function ()
{
$.getJSON('/Methods/GetRecipients/' + $(this).attr('id'), function (data)
{
var recipient = data;
console.log(recipient);
$('#edit-opno').val(recipient.OpNo);
Console.log(recipient) shows the values from my GetRecipients method.
This code $('#edit-opno').val(recipient.OpNo); is meant to show the value in my input text where I have this code below.
<input type="text" name="opno" id="edit-opno" size="15" />
However at first I thought the GetRecipients was not executed but from firebug realized it is executed with console.log(recipients) showing the values but no JSON tab, hence failing to populate my dialog input box.
Below is my server side code:
#{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
if(UrlData[0].IsInt()){
var db = Database.Open("sb_cpd");
var sql = "SELECT * FROM cpd_recipients WHERE ID = #0";
var recipients = db.QuerySingle(sql,UrlData[0]);
Json.Write(recipients, Response.Output);
}
}
I have inserted an image of whats happening. Notice my dialog is not populated with values from GetRecipients method.
You should set the header content-type to application/json. Firebug will then recognize the response as JSON:
#{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
if(UrlData[0].IsInt()){
var db = Database.Open("sb_cpd");
var sql = "SELECT * FROM cpd_recipients WHERE ID = #0";
var recipients = db.QuerySingle(sql,UrlData[0]);
Response.Headers.Add("Content-type", "application/json");
Json.Write(recipients, Response.Output);
}
}

Categories

Resources