Tearing my hair out on this one.... sure it just the structure of my function.
Basically I make a Ajax call within an Ajax loaded tab. The call made within writes a record to the Database and returns a value. I can alert the value fine but when I try to use it as a data parameter in my .load() call it doesn't get passed?
As they are in the same success function I just thought (Stupidly?) that I could easily reference it!
$('#convert-2-booking').click(function(e) {
var quoteid = $(this).attr("title");
$.ajax({
type: "POST",
url: 'tabs/convert-2-booking.asp?Planner_ID='+$('#convert-2-booking').attr("title")+'',
data: quoteid,
cache: false,
dataType: "html",
success: function(responseText){
var ajax_load = "<img class='loading' src='images/load.gif' alt='loading...' />";
var loadUrl = "tabs/booking.asp";
bookingid = responseText;
//above gets correct returned id.
$("#bookingtab").html(ajax_load).load(loadUrl, { 'bookingid': bookingid } ); // not here though :(
alert(bookingid) // alerts the correct id here too!
setTimeout(function() {
// move to bookings tab after 3 seconds
$("#tabs").tabs( "option", "active", 3 );
// load correct record into tab
}, 3000);
},
error: function(responseText){
alert("NOT:"+responseText);
//alert(responseText);
$("#tabs").tabs( "option", "active", 2 ); //load previous tab itself if returns error..
},
});
});
Try passing it via "booking.asp?bookingid=..."
Like this:
.load(loadUrl+"?bookingid="+bookingid)
It's a workaround tho; I'm not sure why load() doesn't do the same thing thru your array... Maybe it's because you only check GET variables on server side and load() gives you POST...?
ended up deciding to store the id in a session for the few seconds i need it. Not ideal, but a workaround for now, and enough to allow me to demo to my client.
Related
This is going to be a strange one if I'm honest so please bare with me.
Im currently working on a project that requires me to call python scripts that are part of a webserver that is running a HTML webpage from the page itself i.e You move a slider on the webpage and it calls the python script and passes the value of the slider and an ID value that the script requires to pass the value to its relevant end point. In this case its a monitor ID and the slider value is the brightness value that the brightness must be set to.
Currently I have achieved this with a form submission action but I don't want the webpage to reset once a new value is sent and so JavaScript is my next best option using Ajax requests and while I have made some progress I am basically a noob with web development and have hit a brick wall.
Here is the script I have attempted and the python script that it calls.
<script>
slider.oninput = function (event, ui)
{
var slider_val=event.target.id;
console.log(slider_val);
$( "#"+slider_val ).val( ui.value );
$( "#amount_"+slider_val ).val( $( "#"+slider_val ).slider( "value" ) );
changeBrilliance();
}
function changeBrilliance(value, monid)
{
$.ajax({
type: "POST",
url: "/brilliancechange",
data: { mydata: value, mon: monid }
});
}
</script>
Python:
#app.route('/brilliancechange', methods=['POST'])
def brillchange():
userinput = request.form['mydata']
selectedMon = request.form['mon']
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
DATA = "A6" + selectedMon + "0000000401C0"
DATA += hex(int(userinput)).lstrip("0x")
check = checksum(bytes.fromhex(DATA))
DATA += hex(int(check)).lstrip("0x")
dataarray = hextobyte(DATA)
s.sendall(dataarray)
s.close()
What should the javascript look like if i want to call this method with a different ID and value each time without it reloading the webpage everytime?
It looks like changeBrilliance() accepts two parameters but when called nothing is getting passed. I'm not too familiar with the Python framework being used, but as long as it accepts content-type: application/json in POST body you could do:
// not totally sure which value/id combo you need but just pass the necessary ones here
changeBrilliance(slider_val, ui);
function changeBrilliance(value, monid)
{
var myObj = { 'myData': value, 'mon': monid };
$.ajax({
type: "POST",
url: "/brilliancechange",
contentType: "application/json",
data: JSON.stringify(myObj)
});
}
Then if you want something in the browser to change, you'll have to callback on done if successful or fail if something goes wrong, and always callback for some behavior that should always happen:
$.ajax({
type: "POST",
url: "/brilliancechange",
contentType: "application/json",
data: JSON.stringify(myObj)
}).done(function(data) {
// do something
}).fail(function(jqXHR, textStatus, err) {
// handle error
}).always(function(data) {
// always callback
});
I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});
I want to check if my user is updated from another system using javascript.
I need help writing a function which checks a json response. If it is true or false.
The url /user/updatecheck/ has a json response like this: {"updated": "true"} or {"updated": "false"}
<script type="text/javascript">
$(document).ready(function() {
var updated='2013-01-02T10:30:00.000123+02:00'; //user variable from the system, will be empty if the user is not updated
if (!updated){
$('#not-updated').modal('show');
var updatedCheck = window.setInterval(
$.ajax({
url: "/user/updatecheck/", //Returns {"updated": "true"} or {"updated": "false"}
data: dataString,
dataType: "json",
success: function(data){
if (json.updated == 'true') { //not sure if this is the correct method
window.clearInterval(updatedCheck);
//The user is updated - the page needs a reload
}
} //success
})
, 3000); //Hoping this is the function to check the url every 3 seconds until it returns true
}
});
$(document).ajaxStop(function(){
window.location.reload();
});
</script>
It does not seem to work. Not sure if my ajax function is correct, I only get the modal window if the user is not updated at first, and the page does not reload if the url /user/updatecheck/ returns true.
The way you call jQuery ajax function as part of the setInterval is not proper. Please try placing it within a function,
var updatedCheck = window.setInterval(
function(){$.ajax({
url: "/user/updatecheck/", //Returns {"updated": "true"} or {"updated": "false"}
data: dataString,
dataType: "json",
success: function(data){
if (json.updated == 'true') { //not sure if this is the correct method
window.clearInterval(updatedCheck);
//The user is updated - the page needs a reload
}
} //success
})}
, 3000);
The data that you will receive from the ajax request is returned via the data parameter of you success callback function, so you can use that. Try to print the data result to the console (i.e. console.log(data);)or alert it (i.e. alert(data);). For instance you may need to call data.updated. I'm not sure if the json variable you are using in the if condition is initialised.
I'm trying to use a button to perform an API Call to Flickr, like so:
$(document).ready(function (){
$('#goButton').click(function (){
makeAPICall();
});
});
This works as expected, but the communication between the client and the Flickr API takes a while to execute, so the page appears like it is hung. I would like to add a "Working Notice" that is displayed immediately on button click to let the user know that their action is processing.
To do this, I added an H1 tag:
<h1 id="notice"></h1>
and a function that changes the inner HTML to display a notice:
function workingNotice() {
document.getElementById("notice").innerHTML="I am getting your results";
}
But when I try to edit the code for the button to something like this:
$(document).ready(function (){
$('#goButton').click(function (){
workingNotice();
makeAPICall();
});
})
The Working Notice is never displayed until the API Call has completed, which defeats the purpose.
I then tried using:
$(document).ready(function (){
$('#goButton').click(function (){
$.when(
workingNotice()
).then(
makeAPICall()
);
});
})
This gives the exact same results, where the Working Notice is not called until the API Call completes. Is there any alternative that I can try to force the order of these functions to comply?
UPDATE/EDIT:
While I found the solution to the initial problem in another answer, I know there's a reasonable chance the delay in the API Call processing is due to some mistake in this function. Here is the code for makeAPICall:
//call Flickr api and look for tags matching user search term
function makeAPICall(){
//get value tag from team 1 search box
var searchTag1 = escape(document.getElementById("searchTag1").value);
//get value tag from team 2 search box
var searchTag2 = escape(document.getElementById("searchTag2").value);
//build api call url with searchTag1
var url1 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag1 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//build api call url with searchTag1
var url2 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag2 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//make call to flickr api
$.when(
$.ajax({
dataType: "json",
url: url1,
async: false,
success : function(callReturn1) {
callData1 = callReturn1;
numResults1 = parseInt(callData1.photos.total);
}
}),
$.ajax({
dataType: "json",
url: url2,
async: false,
success : function(callReturn2) {
callData2 = callReturn2;
numResults2 = parseInt(callData2.photos.total);
}
})
).then(
drawChart()
);
}
Note "callData1", "callData2", "numResults1" & "numResults2" are all global.
If your makeAPICall is not async - call it out of bounds:
workingNotice();
setTimeout(makeAPICall, 1);
I wrote a little chat plugin that i'll need to use on my site. It works with a simple structure in HTML, like this:
<div id="div_chat">
<ul id="ul_chat">
</ul>
</div>
<div id="div_inputchatline">
<input type="text" id="input_chatline" name="input_chatline" value="">
<span id="span_sendchatline">Send</span>
</div>
There's a 'click' bound event on that Span element, of course. Then, when the user inserts a message and clicks on the "Send" span element, there's a Javascript function with calls an Ajax event that inserts the message into the MySQL database:
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
}
});
}
And, in case the message is successfully inserted into DB, it calls a function to read new lines and put them in HTML structure i posted before:
function function_get_newchatlines()
{
$.ajax
({
type: "POST",
url: "ajax-chat-loadnewlines.php", //1: ok, 0: errore
data: '',
dataType: "text",
cache: false,
success: function(ajax_result) //example of returned string: 'message1>+<message2>+<message3'
{
//explode new chat lines from returned string
var chat_rows = ajax_result.split('>+<');
for (id_row in chat_rows)
{
//insert row into html
$('#ul_chat').prepend('<li>' + chat_rows[id_row] + '</li>');
}
$('#span_sendchatline').html('Send');
}
});
}
Note: 'ajax_result' only contains html entities, not special chars, so even if a message contains '>+<', it is encoded by the php script called with Ajax, before being processed from this JS function.
Now, comes the strange behaviour: when posting new messages Opera, Firefox and even IE8 works well, as intended, like this:
But, when i open Chrome window, i see this:
As you can see, in Chrome the messages are shown multiple times (increasing the number each time, up to 8 lines per message). I checked the internal debug viewer and it doesn't seem that the "read new lines" function is called more than one time, so it should be something related to Jquery events, or something else.
Hope i've been clear in my explanation, should you need anything else, let me know :)
Thanks, Erenor.
EDIT
As pointed out by Shusl, i forgot to mention that the function function_get_newchatlines() is called, periodically, by a setInterval(function_get_newchatlines, 2000) into Javascript.
EDIT2
Here's is a strip of the code from the PHP file called by Ajax to get new chat lines (i don't think things like "session_start()" or mysql connection stuff are needed here)
//check if there's a value for "last_line", otherwise put current time (usually the first time a user logs into chat)
if (!isset($_SESSION['prove_chat']['time_last_line']) || !is_numeric($_SESSION['prove_chat']['time_last_line']) || ($_SESSION['prove_chat']['time_last_line'] <= 0))
{
$_SESSION['prove_chat']['time_last_line'] = microtime(true);
}
//get new chat lines
$result = mysql_query("select * from chat_module_lines where line_senttime > {$_SESSION['prove_chat']['time_last_line']} order by line_senttime asc; ", $conn['user']);
if(!$result || (mysql_num_rows($result) <= 0))
{
mysql_close($conn['user']); die('2-No new lines');
}
//php stuff to create the string
//....
die($string_with_chat_lines_to_be_used_into_Javascript);
Anyway, i think that, if the problem was this PHP script, i would get similar errors in other browsers, too :)
EDIT4
Here's the code that binds the click event to the "Send" span element:
$('#span_sendchatline').on('click', function()
{
//check if there's already a message being sent
if ($('#span_sendchatline').html() == 'Send')
{
//change html content of the span element (will be changed back to "send"
//when the Ajax request completes)
$('#span_sendchatline').html('Wait..');
//write new line
function_write_newchatline();
}
//else do nothing
});
(Thanks to f_puras for adding the missing tag :)
I would do one of the following:
option 1:
stop the timer just before the ajax call in function_write_newchatline() and start the timer when the ajax call returns.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
stop_the_timer();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
},
complete: function() {
start_the_timer();
}
});
}
option 2:
Not call function_get_newchatlines() at all in the success event of the ajax call. Let only the timer retrieve the chat entries.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
// do nothing
}
});
}
I think there is some race condition between the function_get_newchatlines() that is called after a chat entry is added by the user and the periodical call of function_get_newchatlines() by the timer.
option 3:
Use setTimeout instead of setInterval. setInterval can mess things up when the browser is busy. So in the end of the setTimeout function call setTimeout again.