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);
}
}
Related
I am currently writing some poll software and, even though it works fine, I am having difficulties getting some of my javascript to work. I have a button labelled "Add New Option" which, when clicked, will call the following javascript function:
function newoption()
{
var option = "";
while((option.length < 1)||(option.length > 150))
{
var option = prompt("Please enter the option value... ").trim();
}
var add = confirm("You entered " + option + ", are you sure?");
if(add==1)
{
var code = window.location.href.length;
var poll = prompt("Which poll are you adding this to?", window.location.href.substring(code - 5, code));
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{this.responsetext = option;}};
xhttp.open("POST", "../special/new.php", true);
xhttp.send("poll=" + poll + "&opt=" + option);
}
else
{
alert("OK... try again");
}
}
The page it posts to simply has a function to add the option to the poll which the user supplies the code for (it automatically gets this from the end of the URL) but the problem is that, when I refresh the page, the list of options is not updated which makes me think it isn't being added to the database but the function to add new options works on when the poll is created. Is there something I'm doing wrong?
The code for new.php is:
<?php require("internal/index.php");
$option = string_format($conection, $_POST["opt"], 1)
$poll =(int) $_POST["poll"];
if($poll&&$option)
{
new_poll_option($connection, $poll, $option);
}
?>
From what you wrote I understand that the code works until you refresh the page. That means that you don't check the Ajax response and just insert some HTML which will last until you refresh the page.
You need to look in your database if the items was created. If it is created then maybe you need to delete the browser cache (you can do that from the Network tab in DevTools in Chrome).
If the items was not insert in the database then you need to debug or just echo the message from the insert function that you used.
You can also use a form and not use Ajax if you will refresh the page anyway in a few moments.
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).
I have an HTML form that contains an AJAX call to get some data for the form, specifically a set of select options. This works fine and in Firefox (50.0.2) the results are selectable after handling the AJAX success response. To prevent the form from submitting, before I hit enter on the data needed for the AJAX jQuery GET, I preventDefault on the form submission and all that works OK.
But in Internet Explorer 11 the select data are not immediately visible after processing the AJAX call response but if I mouse-click (left mouse button) anywhere in the form area, the AJAX response data becomes visible and selectable.
I have tried to use jQuery trigger click to simulate the left mouse click anywhere in the form area but I can't get that to work. Can anyone suggest how to get IE11 to behave like Firefox does? Any suggestions will be most appreciated.
I have attached part of the AJAX response code if that might help - the response is in XML format..
// Now insert the received response(s) into the DOM:
$(data).find('result').each(function()
{
// $(data).find('result') creates an array (which hopefully will not be empty)
var dataToDisplay = $(this).text();
// we now have a pipe-delimited string - convert it into an array
var data_array = dataToDisplay.split('|');
var dog_pk = data_array[0];
var dog_name = data_array[1];
var dog_breed = data_array[2];
var customer = data_array[3];
var the_rest = dog_name + ", " + dog_breed + ", " + customer;
$('#dog_pk').append("<option value=" + dog_pk + ">" + the_rest + "</option>");
});
Here's the AJAX GET request:
$(function()
{ // get dog and owner names function
$('#dogname_start').change(function(event)
{
var params = "params=";
params += String ($('#dogname_start').val());
params = encodeURI(params);
$('#add_appointment').submit(function(event)
{
event.preventDefault();
// alert("In dogname_start change form submit function, params are " + params);
});
$.get(
'./modules/get_dognames.xml.php',
params,
handle_response
); // end AJAX get (note: type defaults to html)
}); // end change function on #dogname_start
}); // end get dog and owner names function
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.
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);
}
});