Using content of a variable for js function calls? - ajax

after a ajax call of a php - file i want to take a part of the feedback-result for add additional javascript code. The php file returns the code. Now i dont know how i can include it in the right way?
For better understanding
the php file returns the $result[script] = 'alert("my functions");'
the file wich controls the ajax calls looks something like that
url: fileurl,
type: "post",
data: formDetails.serialize(),
error: function(jqXHR, textStatus, errorThrown)
{
displayAjaxMessage("Sorry, there was an error");
},
success: function (result) {
var res = $.parseJSON(result);
//Here should be the scriptcode from the variable
$res.script;
}
I want to do it, beacause i think i have to redeclare some function for example plugins like bootstrap-switch, datepicker etc.
They wont work after submit the form, so i think i must inlcude the JS-Code again?

With
eval(res.script);
It works.

Related

get data from ajax as an attribute value for callback function

Im new to ajax. I was trying to find the answer but was not lucky to find the corresponsing one. Basically I need to use an ajax to get some data and after that to put this data to the variable that later will be used as an attribute for the callback function with custom code.
This ajax part is just a method of myObject.
So, in the end I need this kind of functionality:
myObject.getData(url, callback(data) {
//my custom code of what I wanna do after ajax is complete
});
My code
/*
HERE COME SOME PROPERTIES AND OTHER METHODS WICH IS NOT THE CASE
*/
//This is where Im stuck
var getData = function getFromUrl($url) {
$.ajax({
type: 'get',
url: $url,
dataType: 'html',
success: function(html) {
$obj = html;//Im lost on this step!
},
});
};
P.S. Im trying to find an async way (without using async:false). Hope its possible
First I encountered many problems. My first problem was No Access-Control-Allow-Origin, most websites dont allow you to just scrap get their data for security reasons. Luckily someone already made a proxy: http://cors.io/ . Second problem is that you cant embed http on https, so I cant use jsfiddle to show you this working, it works on my local enviroment. After you get the raw html you have to parse it, you can do it with full regex, or you can power yourself with jquery like I'm doing on this example. What we're doing is checking stackoverflow.com and getting the amount of featured questions with .find(".bounty-indicator-tab").first().html(); But once you have the full html you can get any data you need.
var getData = function getFromUrl(url) {
$.ajax({
url: 'http://cors.io/?' + url,
crossDomain: true,
dataType: 'html',
success: function (html) {
var match = $(html).find(".bounty-indicator-tab").first().html();
console.log(match);
return match;
},
error: function(e) {
console.log('Error: '+e);
}
});
};
url = 'http://stackoverflow.com/';
data = getData(url);
//You cant use data yet because its working async

Using form data to dynamically construct url using ajax

I have the following ajax code that takes in 3 variables and passes them to a php file, and this is all fine and dandy. I want to do a redirect using the value stored in one of these variables. I figured I could just do window.location.href = within the success in the ajax call, but for some reason, it doesn't seem to respond to the click, and simply does nothing.
Here is the ajax function, hope y'all can help!
$("#findItem").click(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.ajax({
type: 'get',
url: 'http://plato.cs.virginia.edu/~aam3xd/cabbage/closestBuildingWeb.php',
data: {
foodItemId: $('#foodItem').val(),
sentLongitude: position.coords.longitude,
sentLatitude: position.coords.latitude
},
success: function(data){
//$('#answer').html(data);
//the following line doesn't seem to be executing....
window.location.href = foodItemId+"/"+sentLatitude+"/"+sentLongitude;
}
});
});
I think you should use your url into that window.location
window.location.href = "www.example.com/"+foodItemId+"/"+sentLatitude+"/"+sentLongitude;

load mypage.php via ajax into a div in wordpress

i have an ajax load request working in wordpress, but i would like to load the content from another page into the container div. at the moment it just passes the url in $dataToSend as a string?
jQuery(document).ready(function(){
var $dataToSend = "my-page.php";
var $testBtn = jQuery('#text-ajax-btn');
var $holdingCtn = jQuery('#my-holding-ctn');
$testBtn.click(function(){
jQuery.ajax({
type:'POST',
url: myAjax.ajaxurl,
data:{
action:'myAjax',
dataToSend:$dataToSend,
},
success: function(data,textStatus,XMLHttpRequest){
$holdingCtn.html("");
$holdingCtn.append(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
how can i pass an entire .php page through as the $dataTosend?
I do this all the time for wordpress, give me a sec to access my repository and I will show you example code.
I think problem is your my-page.php! I imagine you custom coded it. So it doesn't have necessary functions loaded.
put following code at the top of your my-page.php (this will help with 500 error you are getting)
require('../../../wp-load.php');
ajax part should look something like this:
//start ajax
$.ajax({
url: "http://localhost/wp-content/themes/theme/my-page.php",
type: "POST",
data: data,
cache: false,
success: function (data) {
console.dir(data);
}
})
If you want to load content from my-page.php file then you can load from the server side using
$data = file_get_contents('path/to/file/my-page.php'); // pass right path/url
Then, just echo the content from your function (registered ajax handler in WordPress using add_action) and in this case it should be
echo $data;
die(); // terminate the further execution
So, it should look something like
add_action( 'wp_ajax_myAjax', 'yourAjaxHandler' );
add_action( 'wp_ajax_nopriv_myAjax', 'yourAjaxHandler' );
function yourAjaxHandler(){
$data = file_get_contents('path/to/file/my-page.php');
die($data); // echo out the string and terminates execution
}
In your success callback, you can use
success: function(data){
jQuery('#my-holding-ctn').html(data);
}
Not sure if this is fully applicable, but the super easy way is just
$("#myDiv").load("myFile.php?foo=1&bar=2...");

jQuery - AJAX request using both native XHR and flXHR (Flash) fallback - how to minimize code duplication?

I need to retrieve data via cross-domain XMLHttpRequest. To make this work in (almost) all browsers, I use native XHR first and, if that fails, flXHR.
The (working) code I currently have for this is as follows:
jQuery.support.cors = true; // must set this for IE to work
$.ajax({
url: 'http://site.com/dataToGet',
transport : 'xhr',
success: function(data) {
console.log('Got data via XHR');
doStuff(data);
},
error: function(xhr, textStatus, error) {
console.log('Error in xhr:', error.message);
console.log('Trying flXHR...');
$.ajax({
url: 'http://site.com/dataToGet',
transport : 'flXHRproxy',
success: function (data) {
console.log('Got data via flXHR');
doStuff(data);
},
error: function (xhr, textStatus, error) {
console.log('Error in flXHR:', error.message);
console.log('Both methods failed, data not retrieved.');
}
});
}
});
This feels like a lot of code duplication to me, especially in the success handlers. Is there a more efficient way to do this? I'd really prefer to make one $.ajax call that would try both transports in turn, instead of having to use the error handler to make the call a second time. It's not too bad in this example, but rapidly gets more complicated if the success handler is longer or if the success handler has to itself issue another $.ajax call.
I've created a jquery-specific and slimmed-down fork of flxhr that simplifies your code sample above. You can see an example of usage in the "Usage" section in the README.
https://github.com/b9chris/flxhr-jquery-packed
In particular, you don't want to waste time waiting for a standard CORS request to fail. It's easy to determine whether flxhr is necessary by testing $.support.cors upfront (no need to override it). Then just use flxhr explicitly where necessary.
Why don't you just wrap this in a function by itself? That's after all, how you end up reusing code. You can even pass functions as arguments to make sure that you don't have to repeat this code more than once.
To me this is pretty straight forward but maybe I've misunderstood.
function xhr(success) {
$.ajax({
success: success,
error: function() {
$.ajax({ success: success })
}
});
}
Then just pass the success handler once
xhr(function(data){/*magic*/});
Or if you wanna basically avoid redundant configuration of the ajax call use the first object as a template, like this:
function xhr(success) {
var ajaxParams = { success: success };
ajaxParams.error = function() {
$.ajax($.extend(ajaxParams, { transport: 'xhr' }));
}
$.ajax(ajaxParams);
}
I simplified the whole thing a bit, but I hope you get the point.
Edit
Reading that last bit, maybe this will give you some ideas... it's a variation of that last snippet.
function xhr(success) {
var ajaxParams = { success: success };
ajaxParams.error = function() {
var newParams = $.extend(ajaxParams, { transport: 'xhr' });
newParams.success = function() {
// do something
// arguments is a special array, even if no parameters were
// defined in any arguments where passed they will be found
// in the order they were passed in the arguments array
// this makes it possible to forward the call to another
// function
success.apply(this, arguments);
}
$.ajax(newParams);
}
$.ajax(ajaxParams);
}

Umbraco - load content with Ajax

I'm new to Umbraco and only started to figure out the ins and outs of it.
Anyway, I've figured out on my own the way document types, macros, templates, xslt files work and am now trying to do some other stuff. Namely I need to load a document content using an AJAX call. It's basically a panel with a menu (dynamic, which I figured out how to load) that loads content depending on the menu item selected (the documents loaded with the menu). What I need to figure out is how to get that content using an AJAX call since I don't want to reload the page.
Is this done using Umbraco BASE extensions or am I off in my thinking here? If so, how exactly? Do I just write a class and then stitch together an HTML string in a method?
Thanks for the help
You can use rest methods. For this you have to edit restExtensions.config on the config folder.
Ajax Call
$.ajax({
type: 'POST',
url: "/base/AliasName/GetData.aspx",
data: {
},
success:
function (data) {
}
});
restExtensions.config
<ext assembly="/DllName" type="Namespace.ClassName" alias="AliasName">
<permission method="GetData" returnXml="false" allowAll="true" />
</ext>
Yup this is exactly the scenario that Base is used for.
You can find documentation on using base here:
http://our.umbraco.org/wiki/reference/umbraco-base/simple-base-samples
For the consumption of base via AJAX then JQuery is the answer.
http://api.jquery.com/jQuery.ajax/
Here's a hacked together example (not tested code):
$(document).ready(function ()
{
$(".buttonListener").click(function ()
{
$.ajax(
{
url: '/Base/TestAlias/Hello.aspx',
success: function (data, textStatus, XMLHttpRequest)
{
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert("Ka pow!");
}
});
return true;
});
Ajax call using umbraco in MVC
$('#TestClick').on('click',function(){
$.ajax({
url: 'umbraco/surface/Home/TestPage',
type: 'POST',
data: { id:10001},
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
})

Resources