Using AJAX, I'm able to extract a data value from a button click, but is it possible to ensure this value is passed on to an argument within another button on the same page?
test.html:
Activate
Fader
test.js:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
}
});
}
The php file connects to the database and extracts the most recent image number - it works fine and the alert box displays the correct value. So what would be the next step to ensure the "image_number" argument is updated with this 'data' value?
Cheers.
make a global variable like
windows.image_number = 0;
for AJAX function.
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
//update the global variable
windows.image_number = data;
}
});
}
Assuming that the image_number variable that you are passing to the function is a globally defined variable, you simply need to set the variable in your success callback:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
// Assuming data holds the image number you want to use for next click
image_number = data;
}
});
}
Related
I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});
i want to get a var from a php script and use it in a function .. so if i call the var simply with $.get (and document.write) i got an result but how can i integrate this into a function ?
$.get( 'http://www.domain.de/content/entwicklung/verdienst.php', function(verdienst_php) {
//document.write(verdienst_php);
});
function sendview () {
var datastring = {uid : uid_clear, verdienst : verdienst_php};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}
only put the function into the $.get part didnt work
if i didnt use $.get and write in datastring like
verdienst: 1000
it works
any suggestions ?
kind regards Dave
Assuming you are returning exactly what you want from the server, store it in a variable and reference the variable in the other Ajax call.
var verdienst_php;
$.get( 'http://www.domain.de/content/entwicklung/verdienst.php',
function(response) {
verdienst_php = response;
});
function sendview () {
var datastring = {uid : uid_clear, verdienst : verdienst_php};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}
If you want the GET call to happen when the click happens, than you just need to put the post code inside of the GET success callback.
You have to make an extra ajax call to get php variable, you can do it this way :-
function sendview () {
var datastring = {uid : uid_clear, verdienst : getPHPVar('verdienst_php')};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}
function getPHPVar(varname){
var returnValue = null;
$.ajax({
url: 'yourphpurl.php',
async: false,
type: 'post',
data:{
task:'getvar',
varname: varname
},
success: function(response){
returnValue = response;
}
});
return returnValue;
}
and in PHP it will look like:
<?php
if($_POST['task'] == 'getvar'){
echo $$_POST['varname'];
}
Also, I think it's actually not needed cause you are getting php variable using ajax, and again using it in another ajax call. so Why don't you just do it in php ?
I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});
I am getting data to global variables in the most dummy way. At the moment:
var tranlationJson =
$.ajax({
type: "GET",
url: "translation.xml",
contentType: "text/xml",
dataType: "xml",
success: function (dataSource) {
tranlationJson=ToJasonParser(dataSource);
}
});
And i want to modify it to use promisses. The issue is that the code which follows is using third party js files so my code is like
<script
<script
var tranlationJson = $.ajax({ ...
<script 111
<script 222
and script 111 and 222 contain custom libraties which will be using the translationJson in it. So how can i ensure that the translationJson will be filled before loading the scripts?
There is global variable that you can reach from any of your scripts: window. Instead of your var translationJson = $.ajax({... you can do window.translationJson = $.ajax({.... But there are two important things here:
First is you don't know what will come first: ajax request finished or some of your script already ask for your variable. The solution is to bind all depending of your variable scripts running to $.ajax({ success: callback. Like this:
$.ajax({
type: "GET",
url: "translation.xml",
contentType: "text/xml",
dataType: "xml",
success: function (dataSource) {
tranlationJson=ToJasonParser(dataSource);
someScriptRun(); /* here you run some depending on your variable script */
}
});
Another way is to check for variable in all of dependant scripts like this:
var periodicalAttemptToRunScriptDependant = setInterval( function(){
if( 'object' == typeof window.translationJson ){
someScriptRun(); /* here you run some depending on your variable script */
clearInterval( periodicalAttemptToRunScriptDependant );
}
}, 1000 );
Second: in your example any request for a variable will cause ajax request, because it is not a variable actually but function. Try to change your code to:
var tranlationJson;
$.ajax({
type: "GET",
url: "translation.xml",
contentType: "text/xml",
dataType: "xml",
success: function (dataSource) {
tranlationJson = ToJasonParser(dataSource);
}
});
I have this code below which is called by running the getGrades function.
function getGrades(grading_company) {
// Set file to get results from..
var loadUrl = "ajax_files/get_grades.php";
// Set data string
var dataString = 'gc_id=' + grading_company;
// Set the callback function to run on success
var callback = showGradesBox;
// Run the AJAX request
runAjax(loadUrl, dataString, callback);
}
function showGradesBox(response) {
// Load data into grade field
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
function runAjax(loadUrl, dataString, callback) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: dataString,
dataType: 'html',
error: ajaxError,
success: function(response) {
callback(response);
}
});
}
Now as you can see I am passing the AJAX response data to the showGradesBox function; however I'm now not sure how to load it into the field.
I have seen example using .load() but it seems you have to use this with the URL all at once; the only other function I have come across that I could possibly use is .html(); but the description of it doesn't sound right!?
.html() should work ...
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
function showGradesBox(response) {
// Load data into grade field
jQuery('#yourgradefieldID').html(response);
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
Assuming a field with ID grade_text and a return of a string from the PHP:
function showGradesBox(response) {
// Load data into grade field
jQuery('#grade_text').val(response);
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
This assigns a value of 'undefined' to your callback.
// Set the callback function to run on success
var callback = showGradesBox;
Try assigning the function to a variable named showGradesBox before your functions like this
var showGradesBox = function(response) {
// Load data into grade field
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
function getGrades(grading_company) {
// Set file to get results from..
var loadUrl = "ajax_files/get_grades.php";
// Set data string
var dataString = 'gc_id=' + grading_company;
// Set the callback function to run on success
var callback = showGradesBox;
// Run the AJAX request
runAjax(loadUrl, dataString, callback);
}
function runAjax(loadUrl, dataString, callback) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: dataString,
dataType: 'html',
error: ajaxError,
success: function(response) {
callback(response);
}
});
}