Ajax call to a method that prints javascript - php

Ok,
I have a some javascript code in the database
Table: jsSnippets
Field: snippet
Type: Text
<SCRIPT SRC="https://svc.com/somestuff.js"></SCRIPT>
<script>
var fubar = 'stuf'
send_some_stuf_to_svc(fubar) // sends some data to a service :)
</script>
So i have N number of this JS snippets
will that code work if a server side method was called via Ajax call, for example:
$.ajax({
type: 'GET',
url: path + '/doTheJSStuff/',
)};
where the doTheJSStuff is a method that echo/prints the JS code

Your script must return javascript code (without html tags).
Call eval(text) after receiving text.

That will work, so long as the contents of the <script> tag are being passed into javascript's eval() function. If you're using a framework such as jQuery, its built-in $.ajax() method eval's tags automatically.

Related

Simple jquery ajax php request

I am doing a basic jquery ajax call on a php file and can't seemsto figure out why it isn't working. Any help is appreciated. Fiebug does not seem to show any ajax or XHR action going on. I want to not to refresh the page and just execute the ajax call. Thanks.
JS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script>
<script>
function getData(url_param){
$.ajax({
type: 'get',
url: 'data.php',
data: {url_param:url_param},
success: function(data) {
$('#data').html(data);
}
});
};
$('#clickMe').click(function(e){
e.preventDefault();
getData(2);
});
</script>
HTML:
<div><a id='clickMe' href='data.php?url_param=url_param'>CLICK ME TO RUN PHP</a></div>
<div id="data"></div> <!-- divto show result -->
PHP:
<?php
if($_GET['url_param']){
echo "simple ajax call";
}
?>
You have to bind the event inside an onload function. The most common practice is:
$(document).ready(function(){
$('#clickMe').click(function(e){
...
});
});
You should also add return false; in the last line of your event.
First, you have misspelled your function name (getGata != getData).
Secondly:
data: {url_param:url_param}
Are you setting the javascript variable url_param anywhere? The $.ajax data parameter is formatted as follows:
get/post variable name : get/post variable value
As you have it now, it doesn't seem that you are assigning a value to url_param.
you can simply use jQuery post function.
$.post('data.php',{param1:'your param 1', param2 : 'your param 2'}, function(response){
//do your operation here. response is what you get from data.php. 'json' spicifies that the response is json type
$("#data").html(response);
},'json');
The (amended?) JavaScript prevents your code from working, because you haven't closed the angle brackets on jQuery source, it should be:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
One of the comments states you shouldn't have the href in the anchor, but because you've ignored defaults this isn't triggered (assuming JS is enabled in the user's browser).
Finally, I think that
return false;
should really be inside the function after
getData(2);
but since we're ignoring defaults, the anchor shouldn't make an attempt to go anywhere or reload anyway.

Run ajaxed javascript

I know this has been covered a few times, but I'm completely a noob when it comes to javascript so I have no idea what I'm doing. I am running a javascript that sends variables to a php file and that info is ajaxed into the current page using innerhtml. Here is that part of the code...
function givingHistory(dyear,did)
{
var divname="giving" + dyear;
$.ajax({
url: 'finance/givinghistory.php',
type: 'POST',
data: {
year: dyear,
id: did
},
success: function(givedata) {
document.getElementById(divname).innerHTML = givedata;
}
});
}
</script>
In the givedata function response from the php file there is a call to another javascript function that is already loaded in my common .js file (so both javascript functions are loaded when the page loads). How do I get the onClick that is added via innerhtml to work? Inside the php file, I check to see if id = a php session variable. If it does it spits out the text that includes the onClick.
If you use a specific id/class/identifier when the page loads in the $('*') function then the action will only bind to that. To get the action bind to anything ever try using $(document).on('click', **selector**, function() {});.
Previously there was bind/live that bound to elements as and when but on is the function now.
Also why are you mixing the $.ajax (jQuery) with document.getElementById(divname).innerHTML (regular javascript)? If you are already using jQuery you could just use $('#'+divname).html(blahbahblah);

How to launch PHP file from Javascript without window.open

I'm using Javascript and I need to call a PHP file to execute some stuff, but I'd like not to use window.open("filename.php"); because it usually opens a new tab or new window.
Sometime a PHP file need a few seconds to finish its job and I don't like to see an open tab or open window while it's working.
Thanks
AJAX is the solution, and with jQuery it's so simple.
Just add this line on your head section (to include jquery):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "yourPage.php"
}).done(function( data) {
alert( "Request is done" );
});
</script>
You can use ajax or dynamically create iframe.
If you use extjs library - here is example ajax request
Use Ajax! Here's a solution using JavaScript's jQuery library:
$.post('your_file.php', {parameter : some_value}, function(response){
// now you can use `response` came from your_file.php after execution
});
$.post(), $.get() are shorthand methods for $.ajax() of jQuery.
or simply use .load(),
('#test_div').load('your_file.php'); //load data from server into `#test_div`
will do job, if you want to just execute something on server-side.

Include PHP file inside a DIV using Jquery & AJAX [duplicate]

This question already has answers here:
using php include in jquery
(2 answers)
Closed 9 years ago.
My problem is that I need to include a PHP file inside a DIV when a button is pressed without the page reloading.
There is even more explanation in the 'Jsfiddle' file.
Below is an included Jsfiddle document.
http://jsfiddle.net/jjygp/5/
Thanks for your time. I am more than happy to provide any information upon request.
See here for your updated jsfiddle
You had marked the change button with a name of Change but were trying to select it with an id of change. Also, you had not told jsfiddle to include jQuery.
Try the following:
<button name="Change" id="Change">Change Div</button>
You are specifying a click function on an id, but no id is set on the button.
You can try with load() function in jquery
http://api.jquery.com/load/
PHP is a server-side script language, which will be executed before a JavaScript script did.
Therefore, you cannot use .load() to execute a PHP code, however, you may try .ajax() to create an AJAX request to the server which can implement the PHP code.
Please see http://api.jquery.com/jQuery.ajax/ if you have trouble on using .ajax().
Note: in .ajax() method, there is a setting called beforeSend, which "can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent". Hope this method helps you in any way.
Then, your JavaScript code will be like this:
$(document).ready(function(){
$("#Change").click(function(){
//doing AJAX request
$.ajax({
url:"include/start10.php",
beforeSend:function(){
$('#myDiv').fadeOut('slow');
},
success:function(data){
// do something with the return data if you have
// the return data could be a plain-text, or HTML, or JSON, or JSONP, depends on your needs, if you do ha
$('#myDiv').fadeIn('slow');
}
});
});
});
You cannot include PHP file with AJAX, but instead the response of the AJAX server-side script, which is the PHP (which has the same effect).
Loading...
The JS file (code):
function ajaxalizeDiv()
{
$.ajax({
type: "get",
url: "/path/to/the/php/you/want/to/include",
data: {
// Anything in json format you may want to include
id: myvarwithid, // descriptive example
action: "read" // descriptive example
},
dataType: "json",
success: onAjax
});
}
function onAjax(res)
{
if(!res || !res.text)
return;
$("#mydiv").html(res.text);
}
And here goes the PHP file:
<?php
$id = (int) #$_GET['id']; // same as in data part of ajax query request
$action = #$_GET['action']; // same as in data part of ajax query request
$text = 'click me';
// Note this is short example you may want to echo instead of die
// You may use not JSON, but raw text. However, JSON is more human-friendy (readable)
// and easy to maintain.
// Note also the array keys are used in the onAjax function form res (response).
die(json_encode(array('text' => $text /* and anything else you want */)));
?>

Post form to more URLs

is it there any way to post a form to more URLs?
I need it in javascript..
For example: I've got 2 documents: 1.php and 2.php.. I want the form to post data to the both of these files, but go to the 1.php..
Do you know any way?
You need a form with the action "1.php" and jQuery.
$('#form_id').submit(function(event){
event.preventDefault();
var $th = $(this);
$.ajax({
type: 'post',
url: '2.php', // note: edited by Ryan
data: $th.serialize(),
success: function(){
$th.submit();
}
});
});
Using JavaScript, yes
You'll want to make one call using the XMLHttpRequest function available in JavaScript to make an AJAX call to the php.2 script. The second call can then be done using document.forms["FORMNAME"].submit().
Libraries like jQuery's Ajax functions make it easier to use the XMLHttpRequest function. See the jquery.get(), jquery.post(), and jquery.ajax() (a.k.a $.get(), $.post() and $.ajax()) function documentation
Here are a few guides to doing AJAX calls using jQuery's $.post() and $.ajax() functions.
(http://www.sitepoint.com/ajax-jquery-3/)
(http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/)
(http://www.phpfreaks.com/forums/index.php?topic=256503.0)
(http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form/)
Also here is an example framework of how this can be coded up:
<form id="exampleform" name="exampleform" action="1.php">
...
</form>
<script type="text/javascript">
function submitForm()
{
... // set up vars for $.post() call
// Make the post call for the 2.php
$.post( ... );
// Submit the form for 1.php
document.forms["exampleform"].submit();
}
</script>
All above solution should work, but remember ajax is only alowed in same domain posting. This mean you are on http://example.com, you can only post to example.com/etc or sub.example.com
If you really want to cross domain posting, you should create an empty ifram as target (id="iframeid") then change the target of the form to it:
<form target="_iframeid" action=""/>
After that you can use javascript to post to one page, and then change action url and repost again
the quick and dirty way to do this is to post the form to one script which will in turn post it to a second script.

Categories