Get javascript variable with ajax - php

I'm trying to get a javascript variable with ajax (and eventually get it to php).
I've tried several things. I'm trying to get the values of a Jquery range slider as soon as the user changes it (to save the values later on). This is the javascript:
$("#slider").bind("userValuesChanged", function(e, data){
console.log( + data.values.min );
});
The log is outputting the right values as soon as I change the minimum slider.
Now I'm trying to get this userValuesChanged with ajax:
$.ajax({
type: "GET",
dataType: "json",
url: "test.php",
data: "{userValuesChanged}",
async: false,
success: function(data){
alert(data);
return true;
}
});
Well as this is my first time using ajax, this is not working. I'm not sure how to write the right value at the data tag. How to get the userValuesChanged? Or the specific + data.values.minv value?

In your ajax call, you're just sending the string "{userValuesChanged}".
If you want to send new values, you specify those in an object:
$("#slider").bind("userValuesChanged", function (e, data) {
$.ajax({
type: "GET",
dataType: "json",
url: "test.php",
data: { minValue: data.values.min },
async: false,
success: function (data) {
alert(data);
return true;
}
});
});
The key bit above is:
data: { minValue: data.values.min },
...which creates an object with a property called minValue which is set to the value of the data.values.min you receive from the scroller. Your server-side script would look for a field called minValue. (Naturally if you also want other values from data.values, you can include them as well.)
Doing that every time the slider changes may be a bit much, though. If the userValuesChanged event only fires once, when the values have stopped changing, then the above is absolutely fine. If it fires continually when the user is moving the scroller, that wouldn't be good, because you'd be triggering a lot of ajax calls.
If that's the case (that it fires repeatedly as the user changes the value), see if it offers a different event when the user stops making changes.
If it doesn't, you can rate-limit instead. Here's how to do that if necessary:
$("#slider").bind("userValuesChanged", function (e, data) {
saveNewValues(data.values.min);
});
var pendingSaveTimer = 0;
function saveNewValues(minValue) {
// cancel any previous save we have pending
clearTimeout(pendingSaveTimer);
pendingSaveTimer = 0;
// Schedule saving the new value in half a second
pendingTimer = setTimeout(function() {
// Clear our timer var
pendingTimer = 0;
// Do it
$.ajax({
type: "GET",
dataType: "json",
url: "test.php",
data: { minValue: minValue },
async: false,
success: function (data) {
// Do something here if needed
}
});
}, 500); // 500 = 500 milliseconds = half a second
}
That waits half a second before saving a value, and cancels that save if a new value comes in within that half a second.

Try like
$.ajax({
type: "GET",
dataType: "json",
url: "test.php",
data: {userValuesChanged:userValuesChanged},
async: false,
success: function(data){
alert(data);
return true;
}
});
The data should be like {key : value} format while you sending the data through ajax

Related

Prevent AJAX calls from firing twice everytime

I am building a web application using JQuery 3.3.1. It would seem that everytime I make ajax call, the request is sent twice. I can tell because I tried logging the requests on server side. I tried solutions from similar questions but they do not seem to help.
I separated the ajax call from click events, so it does not happen because of click event being registered twice.
$(function() {
console.log("hi");
var request = {};
request["user_id"] = 1;
request["date"] = new Date();
request["assignments"] = [{
"point_count" : 1,
"skill_mnemo" : "SKILL_FARM"
}];
$.ajax({
type: "POST",
dataType: "json",
mimeType: "application/json",
url: "./api/update_skill_point.php",
enctype: 'multipart/form-data',
data: request,
async: false,
cache: false,
success: function(result) {
console.log(result);
}
});
});
You have to debug this code by the following ways:
Check how many times hii is printing into console.
Add break point at start of $.ajax. Then check the call stack.
Check into network tab and analyse the call stack at initiator column for the corresponding ajax call.(for Chrome)
Hope it will help for you.
There is a chance that the submit button in your form is NOT set to type="button".
So, on-clicking the button, your ajax function runs and the browser also attempts to submit the form (default behavior of submit buttons) to your current URL. This might give the appearance that ajax is being called twice.
don't use
(function(){})
if we use (function(){}), it will call itself when DOM is getting ready and then again when required.
Try
function ajaxCall()
{
console.log("hi");
var request = {};
request["user_id"] = 1;
request["date"] = new Date();
request["assignments"] = [{
"point_count" : 1,
"skill_mnemo" : "SKILL_FARM"
}];
$.ajax({
type: "POST",
dataType: "json",
mimeType: "application/json",
url: "./api/update_skill_point.php",
enctype: 'multipart/form-data',
data: request,
async: false,
cache: false,
success: function(result) {
console.log(result);
}
});
}
$(document).ready(){
ajaxCall();
}
In this way you can control your ajax call,
Now you might have some idea how to deal, if not let me know, I'll try to explain more.

Ajax store response json in variables

The response of success ajax call is in the form of json like this one:
{"prize_name":"Keys 4","prize_image":"http:\/\/localhost\/web-game-w\/wp-content\/uploads\/2017\/09\/4rare.jpg"}
How I can store "prize_name" & "prize_image" in variables for later use?
Here is the ajax code:
$("#ajax").click(function(e){
e.preventDefault();
var data = {
'action': 'getprize_data',
dataType: "json",
async: false
};
$.post(ajaxurl, data, function(response) {
console.log(response);
// Store vars
});
});
Also I have an issue. This response.prize_name will return error response.prize_name is undefined.
declare those variables without using var before the ajax call starts and assign the values to those variables in the success function
prize_name = prize_image = "";
$("#ajax").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxurl, // give url over here
data: {action: 'getprize_data'},
dataType: 'json',
async: false // always avoid false if you can
success: function(response) {
console.log(response);
response = JSON.parse(reponse);
// Store vars
// assign the values over here
// maybe you will need to decode the json
// if you are encoding it so use JSON.parse
// for decoding the json
},
});
});
Now the reason why I'm saying to declare variable without using var is because
If you don't use var , the variable bubbles up through the layers of
scope until it encounters a variable by the given name or the global
object (window, if you are doing it in the browser), where it then
attaches.
Your post call is wrong. I'd suggest to avoid async to false. But, if you need at all cost such a behavious you can rewrite your post as:
$.ajax({
type: "POST",
url: ajaxurl,
data: {action: 'getprize_data'},
success: function(response) {
......
},
dataType: 'json',
async: false
});
Instead to create global variables you can take advantage of data attributes.
You can store the values in this way:
$('#ajax').data('prizeName', response.prize_name);
And, in future, when you need such a value you can simply get the value with:
$('#ajax').data('prizeName');
Remember that ajax is asynchronous so the value will be available only when the succes callback will be executed. Hence, I suggest to use a callback function in your ajax success function.

Div contents flickers between ajax calls

I have an ajax call that passes a parameter to a request for data. The data is based on a view from a web service that provides me with XML. The web service sometimes lags in returning the view and during that time the contents of the div flickers with the current and new data.
I've tried emptying/hiding the div and setting headers to not cache the php page but still the same.
Here is my code:
$('#getCourses').change(function() {
var courseGroup = $('#courseGroup:selected').val();
$('#showGroupCourses').html('<img src="images/loading.gif">Processing');
$.ajax({
cache: false,
type: 'POST',
url: 'getGroupCourses.php',
data: { passCourseGroup:courseGroup },
success: function(groupCourses) {
$('#showGroupCourses').html(groupCourses).show('fast').css({'height':'auto'});
}
})
});
Any thoughts on how to prevent this?
Thanks!
Try this:
$('#getCourses').change(function() {
var courseGroup = $('#courseGroup:selected').val();
$.ajax({
cache: false,
type: 'POST',
url: 'getGroupCourses.php',
data: { passCourseGroup:courseGroup },
beforeSend: function( xhr ) {
$('#showGroupCourses').html('');
$('#showGroupCourses').html('<img src="images/loading.gif">Processing');
}
})
.done(function(groupCourses) {
$('#showGroupCourses').html(groupCourses).show('fast').css({'height':'auto'});
});
});

Why jquery design script is not working for the products returned by ajax script

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal.
I'm working with Magento CE 1.7.0.2.
Here you can see my goal..
for category products i wrote one custom design script in JQuery & its working perfectly.
Design Script :
<script>
$(document).ready(function(){
$("li.item").each(function(){
// my design script.
});
});
</script>
I have one ajax script from that i'm displaying the some of products in this page at last this one also working fine but the script for design is not working for the products what are all the products got from ajax script.
ajax script :
$.ajax({
url: url1,
cache: false ,
type : 'POST',
// dataType: "json",
data: data1,
success: function(response){
if (response) {
var string = $('.ajaxproducts', response);
$('.displayproductsfromajax').html(string);
}
}
});
I want make that same design script for ajax script products also.
Any thing wrong i did here ?
Any ideas ?
Problem is, you called the design script only on dom ready function. You need to call it again after ajax succeeded in order to apply the style or something.
function applyScript()
{
$("li.item").each(function(){
// my design script.
});
}
$.ajax({
url: url1,
cache: false ,
type : 'POST',
// dataType: "json",
data: data1,
success: function(response){
if (response) {
var string = $('.ajaxproducts', response);
$('.displayproductsfromajax').html(string);
applyScript()
}
}
});
You have to be able to call your design algo on seperate collection so wrap it inside a function like this
var myDesign = function(i,el){
// this will be a reference to the current li.item in "each"
};
$(document).ready(function(){
$("li.item").each(myDesign);
});
...
$.ajax({
url: url1,
cache: false ,
type : 'POST',
// dataType: "json",
data: data1,
success: function(response){
if (response) {
var string = $('.ajaxproducts', response);
$('.displayproductsfromajax').html(string).find('li.item').each(myDesign);
}
}
});

Waiting for AJAX request, then finishing the jQuery

I have a piece of jQuery code:
var newData = checkCP(somedata);
if(newData=="hi"){
alert("Welcom");
}
function checkCP(jsData){
$.ajax({
type: "POST",
url: "Process.php",
data: jsData,
dataType: "json",
success: function(data){
if(data.match==1)
return "hi";
else
return "bye";
}
});
}
I don't know why the welcome alert never shows up. I checked everything; the PHP file returns 1, but apparently before it waits on the AJAX response it passes the
if(new=="hi"){
alert("Welcom");
}
Is there any way to wait for the AJAX response, then read the rest of codes in jQuery?
Yes, you can set the 'async' option in $.ajax() to false.
$.ajax({
type: "POST",
async: false,
url: "Process.php",
data: jsData,
dataType: "json",
success: function(data){
if(data.match==1)
return "hi";
else
return "bye";
}
Firstly, please don't use 'new' as a variable name. 'new' already means something.
Now onto the actual question...
when you call checkCP jquery does the ajax post successfully and automatically waits for a response before execuiting the success function. the thing is that the success function is a stand-alone function and returning a value from that does not return anything from checkCP. checkCP is returning null.
As proof try sticking an alert in your success function.
Something like this should do the trick:
function deal_with_checkCP_result(result)
{
if(result=="hi"){
alert("Welcom");
}
}
function checkCP(jsData,callback){
$.ajax({
type: "POST",
url: "Process.php",
data: jsData,
dataType: "json",
success: function(data){
if(data.match==1)
callback( "hi");
else
callback( "bye");
}
});
}
Pass deal_with_checkCP_result as callback

Categories