Getting data from database to jquery variable - javascript

I'll make this short.
Basically the problem I'm facing right now is that I have a task where data from database is needed to update some texts in browser (I have some sliders that have text under them and depending on the position of the slider the text needs to update according to what's in database). Now I can get the texts to jquery with ajax but I can't seem to get it out to a variable.
This is how the code in jquery looks like:
$.get('ajax.php', getData('send'), function(html) {
console.log(jQuery.parseJSON(html));
});
Before you start merging this question with others, I did look through a ton of them but all I didn't quite see what I was looking for because I actually have to do a lot of different things with that data, not just display it. If there's anyone kind enough to explain how I can get that 'html' to a variable I would be very grateful.
So yeah, end goal is to have something like var data = jQuery.parseJSON(html); and that it behaved like a normal variable with some data in it from there on.
Thanks in advance and have a nice day!

Have a look to Official documentation of AJAX calls in Jquery.
https://api.jquery.com/jquery.get/
Furthermore you can always parse the JSON object in response.
Example:
$.get( "test.php", function( data ) {
$( "body" )
.append( "Name: " + data.name ) // John
.append( "Time: " + data.time ); // 2pm
}, "json" );

Alright, I figured out the answer now thanks to 'kapil yadav'.
$.get('ajax.php', getData('send'), function (html) {
//$('.slider' + value).html(html);
$( "body" ).data( "sliderData", html);
}, "json");
console.log($( "body" ).data());
This is what I used to get what I needed in case anyone else stumbles here.

Related

How do I return variables from serverside back to the clientside script?

I found this article by the plugin author: https://contactform7.com/redirecting-to-another-url-after-submissions/ but the problem is that it redirects to a URL that is known beforehand. I need to know the URL as a response from the server, because the redirect URL will depend on the submitted values.
I can log the event:
document.addEventListener('wpcf7mailsent', function(event) {
console.log(event);
}, false);
But I am not at all sure how much of the data is provided by the server and how much by the client script. I tried altering the submission like this:
add_action('wpcf7_posted_data', 'alter_input');
function alter_input($data) {
$data['your-message'] = 'Something totally different here.';
}
But my alteration seems to have no effect on what data the event object contains. I have trouble finding where exactly the response (if any) is formulated and what filters or actions apply.
EDIT: I reworded the question; too many answers and comments get stuck into the why, which is irrelevant, or try to suggest "other approaches", which isn't what I asked, instead of just sticking to the how.
you may try this :
document.addEventListener( 'wpcf7submit', function( event ) {
var inputs = event.detail.inputs;
for ( var i = 0; i < inputs.length; i++ ) {
if ( 'name-of-the-field' == inputs[i].name ) {
//make your test on inputs[i].value and rediret
}
}
}, false );
They say
The simplest way is utilizing Contact Form 7’s custom DOM event to run
JavaScript. The following is an example of script that redirects you to another
URL when the wpcf7mailsent event occurs:
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
location = 'http://example.com/';
}, false );
</script>
but they don't offer any access to the server response.
The only solution would require you to add in the server response under the onSentOk a javascript string (a serialized object) which will be evaluated line by line.
They say in scripts.js:
if ( data.onSentOk ) {
$.each( data.onSentOk, function( i, n ) { eval( n ) } );
}
so in rest-api.php instead of:
if ( ! empty( $result['scripts_on_sent_ok'] ) ) {
$response['onSentOk'] = $result['scripts_on_sent_ok'];
}
you have to add your url logic, something like:
$response['onSentOk'] = array('top.location.href="' . $cutomUrl .'";');
But again, this plugin wasn't designed to do anything with the server response ;)
Update
Another solution, since you may not have access to plugin files, is to make a second ajax request, this time to one script that is yours:
document.addEventListener('wpcf7mailsent', function(event) {
$.ajax({
url: 'your_scrit.php',
data: sameData,
success: function(response){
// do your redirect
}
});
}, false);
I had the same issue and none of the answers above were helpful. Actually this is feasible, you may follow the below code (add it to functions.php):
add_filter( 'wpcf7_ajax_json_echo', 'filter_wpcf7_ajax_json_echo', 10, 2 );
function filter_wpcf7_ajax_json_echo( $items, $result ) {
$items['foo'] = 'bar';
return $items;
};
You will then be able to access the new element with the below javascript code:
document.addEventListener( 'wpcf7mailsent', function( event ) {
console.log( event.detail.apiResponse.foo );
}, false );
By the way, you may want to use the event wpcf7mailsent over wpcf7submit as suggested in some answers as wpcf7mailsent will fire only if the form is successfully submitted (eg. all required fields are filled properly) which is not the case of wpcf7submit.
Well, I managed to find what I was looking for. The AJAX request to the server returns actually only three variables, eg:
{
into:"#wpcf7-f19-p59-o1",
message:"An error occurred. Please try again later.",
status:"mail_failed"
}
So no luck there. There is no hook or filter to modify the response serverside, to add more variables. And even if there was a way, the clientside javascript is not coded in such a way that it would be easy to overwrite singular methods to achieve the functionality that I want. It would require an ugly copy pasta of hundreds of lines to change just a couple little things.
Thus my verdict is that this is not doable, at least not for now, unless the plugin author decides to make some changes that could accommodate this kind of functionality, wink wink. I'll just implement a form processing action myself. That'll be less work.

how to run an onchange function when page is loaded if the selected box is already selected

Im running into a problem where i have an ajax driven page that is drawn when a user selects something from a simple drop down:
<select id = "selectdepartment">
<option id = "default">Select an option...</option>
....
</select>
and the remainder of the page is drawn using the jquery .change() :
$('#selectdepartment').change(function(){
});
Which then runs some ajax to php script. everything works great, the problem is when i submit a form that was drawn with ajax (using $_SERVER['PHP_SELF'];), the data gets submited, the page reloads, and the page is cleared but the select box is still left where it was. The user has to move to a different option then back to the one the selected originally to re-fire the .change(). that sucks.
I could fix this by passing a php variable in all of my forms, then checking to see the variable set on every page load and if it is draw the page parts then, but this would lead to pretty messy code and it's less than desirable.
There has to be a way to do this with the jquery library, though my knowledge of the javascript language in general is not what i would like it to be. If anyone has any helpful hints please share, dont do it for me though, i wont learn that way :)
edit: code with .trigger
$('#selectdepartment').change(function(){
var department = $('#selectdepartment').val();
var day = $('#data').data('day');
var month = $('#data').data('month');
var year = $('#data').data('year');
//alert (department);
if(department === "Select an option..."){
$('.hiddenuntildepartmentisselected').css({"display":"none"});
}
else{
$('.hiddenuntildepartmentisselected').css({"display":"block"});
}
showpoints(department);
drawpointstable(department, day, month, year);
displaytheuseresforselecteddepartment(department, '');
$('#sendthedepartment').val(''+department+'');
$('#hiddendepartmentidforaddinganewpoint').val(''+department+'');
}).trigger('change');//end run functions
You can use the .trigger() function to immediately trigger the change event handler when the page has loaded:
$('#selectdepartment').change(function() {
// code here
}).trigger('change');
Or if you need to call it elsewhere via JavaScript/jQuery:
$('#selectdepartment').trigger('change'); // or just .change() as a shorthand
Updated
Your button for the form could make use of the onClick attribute, which would invoke a method to parse the form fields and post the data to your php script via .ajax().
In the success event method you then check any flags you need to and modify the element as you desire if needed.
Basic example:
Inside of .ajax():
...
url: 'xxx.xxx.xxx',
async: true,
type: 'POST',
dataType: 'html',
data: JSON.stringify( form_fields ),
beforeSend: function()
{
// Pre send stuff, like starting a loading gif
},
success: function( data, textStatus, xhr )
{
// Be sure you load the page with the content first
$( '#containing-div' ).html( data );
// Do your check here, and modify your element if needed here
if( flagtocheck === 'xxx' )
{
// Modify the element in question...
}
// I call a custom method termed `.ctrls()` here that makes any
// adjustments to the DOM once its loaded/updated.
},
error: function( xhr, textStatus, errorThrown )
{
}
Of course, you'll want to set flagtocheck appropriately in your case.
Hope that helps!
Note regarding edit
This post was edited to be a little more descriptive and more easily understood. Since the person asking the question is already using the .ajax() method, the success event method is the ideal place for doing what the person asking the question is requesting. It is 1 less method invocation to directly modify the element there than using it to call .trigger() or .change() which then also directly modifies the element.

Iterate over the data to show Autocomplete suggestions

This is an API which returns results in an array, for auto suggestions
For Eg. if I query "google" I get the results as follows
["google","google maps","google translate","google earth","google images","google docs","google voice","google scholar","google chrome","google calendar",]
You can try it yourself here
Here's my code that I m using to query this API but it doesnt seem to return results.
Here's the code that I m using for it
$(function() {
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "q.php",
dataType: "json",
data: {
"q" : request.term
},
success: function( data ) {
response(data[1]);
}
});
},
minLength: 2
});
});
I dont understand where am I going wrong in the code
Please correct me ! Because it doesnt seem to be working as I wanted
Edit: Accessing the Data from the same server
You forgot to add jquery-ui library in your fiddle. But if you do code will not work anyway, because you can't access data from another domain via ajax request. Only from same domain on what js code executes.
This might be helpful
$(document).ready(function() {
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) { //get information about the user usejquery from twitter api
$('#twitter_followers').text(json.followers_count); //get the follower_count from the json object and put it in a span
});
});
Look for something called as cross-domain ajax.
http://usejquery.com/posts/the-jquery-cross-domain-ajax-guide
You can read here about using jQuery autocomlete for cross-domain environment: http://1300grams.com/2009/08/17/jquery-autocomplete-with-json-jsonp-support-and-overriding-the-default-search-parameter-q/
Also you need to add jquery.autocomplete.js to your jsFiddle environment.

jQuery / Tumblr - parsing JSON data

I'm trying to read Tumblr informations via the JSON API (and recuperate the total numbers of post for a blog)
My JS code looks like this:
$.getJSON("http://demo.tumblr.com/api/read/json?callback=?", function(json) {
$('.counter').html(json.posts-total);
});
but doesn't work.
Try:
$.getJSON("http://demo.tumblr.com/api/read/json?callback=?", function(json) {
$('.counter').text(json["posts-total"]);
});
Since - is an operator, JavaScript would otherwise try to subtract total from json.posts.
You can see this working in this JSFiddle
not worked with tumblr but an easier way to use jQuery to get json data is
$.get( "http://demo.tumblr.com/api/read/json", {callback:"?"}, function(data){
alert( data.posts-total )
}, "json");
maybe a different approch will help, also the console of firebug is very valiuable in seeing why an ajax request hasn't worked. Maybe check that too firebug->console
if none of this helps shoot back a little more info and will see what else can be a miss..

Value of html from jquery get

I want to retrieve the value of a text field on a another page on my website (prices.html)
Using http://api.jquery.com/jQuery.get/, how can I accomplish this?
How can I do this?
var price = $('input:price').val(); <- the value of price from prices.html (i'm not on this page so i need to request it)
How can I do this?
Thanks in advance.
You could try .load().
.load('price.html input[name="price"]', function(data) {
alert(data);
});
I didn't try it out myself, but it should work.
One of the last examples on the jQuery get page provides you a clue:
$.get("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Assuming that you get your page correctly, you should get a data payload, which you can then parse to get the price information that you're looking for. Using another example, if you have your data processed as JSON, you can extract data like so:
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name ) // John
.append( "Time: " + data.time ); // 2pm
}, "json");
Without more information, it'll be hard to put together a working example.
Before you live prices.html page, will be good to store/transfer (post/get) input:price in hidden textfield in new page and than read hidden textfield with jquery

Categories

Resources