I have this weird issue which i'm absolutely don't even know how to address...
i have this little AJAX call:
$('#toexcel').live("click",function() {
var sql = grid.data().sql;
$.ajax({
url: "toExcel.php",
data: "sql="+sql,
success: function(response){
window.location.href = response.url;
}
});
alert(sql);
});
});
which passes sql query from grid object to toExcel. toExcel uses PHPExcel object to output excel file.
now:
when alert pops up it has normally looking query ...LIKE '%cdviled%'...
but when i access this query in toExcel.php it looks like ...LIKE 'Íviled04%'....
and query obviously fails.
why????? how??
PHP is interpreting %cd as a URL-encoded entity. You will want to run your parameters through encodeURIComponent() before sending off the ajax request.
Although, you might get better (and more secure) results by simply sending the search term via ajax and letting PHP assemble the SQL on the server side!
%cd is a valid URL-encoded representation of Í and PHP handles it as such.
The solution is simple. Change:
data: "sql="+sql,
to:
data: "sql="+encodeURIComponent(sql),
Related
Hey guys I am building an application in which I send input value from a text box via AJAX to a controller function and then return what I send back to the user (I am developing an instant search, this is a first step).
The AJAX links to the method fine however I am having problems returning the information. I receive no error messages, the problem is that the return string is BLANK.
I receive [you wrote ] rather than [you wrote WHATEVER I IN PUTTED ]
Any help greatly appreciated.
view_index.php
function search(){
var term = document.getElementById("mainsearch").value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: term,
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
controller_site.php
function search(){
$gotcha = $this->input->post('term');
return $gotcha;
}
The data: parameter accept a key : value json to pass to the POST, as the json array key will be your $_POST key
Try with this:
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: {'term': term }
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
You didn't send your data correctly, so PHP has nothing to process, and you end up sending back nothing:
data: term,
POST/GET requests MUST be in key=value format, and you're sending only the value portion. Try
data: {foo: term},
and then
$gotcha = $this->input->post('foo');
You need to change return to echo as AJAX response works on whatever echo from called function.
So, you can code like :
function search(){
$gotcha = $this->input->post('term');
echo $gotcha;
}
or
function search(){
echo = $this->input->post('term');
}
The responseText property returns the response as a string, and you can use it accordingly
It is generally a bad idea to return HTML from your controllers. Instead try to just manage data server-side wise and do all the frontend on the client side.
Now, for the error:
The success callback takes 3 parameters
You need to pass key-value pair in the data argument of the .ajax call
Make sure you handle errors on your controller appropriately because if something goes wrong you'll get an html document as a response from CodeIgniter and you'll spend a lot of time debugging javascript to find out that the error was actually server-side
1 the callback:
Your success callback function should look like this:
function (data, status, response) {
}
Where:
data is whatever you are echoing from your controller's method. You'll probably want JSON.
status Will tell you if the HTTP response message (e.g. "Not Found" is the status for a 404 code, "success" for a 200 code)
response is the jquery wrapped XmlHttpRequest object that gives you a handful information of the transaction, for example response.responseText would give you whatever you outputed from PHP, response.responseJSON would give you a JSON object if you echoed a json encoded object, etc.
Why should you care? Because those extra parameters will let you decide if something went wrong on your backend so you can handle the situation client-side not leaving the user wondering if you app just don't work. Worse, giving the infamous red cross on the status bar of the browser.
If you set the dataType parameter of the jQuery.ajax function then you can explicitly tell jQuery what kind of data you are expecting to be retrieved from the server on data parameter from your callback.
2 the sent data
As said, you need to either pass value-pairs or a URL encoded string. If you intend to use GET then you can pass the URL encoded string, but that means you have to have arguments on your CI function like:
function search($term)
And then CI automatically routes the incoming parameters. But since you want to do POST then you'll want to effectively get the values with $this->input->post("name")
If you have your input inside a form, or several fields that you need to send, then its easier to just serialize the form:
$.ajax("url", {
type : 'POST',
data : $('#form').serialize(),
dataType : 'json',
success : function(data, status, response) {} error : function(response, status error) {}});
3 handle errors
If you are relying on AJAX then make sure that you return some sort of error or warning so you can catch it client side:
function search() {
$term = $this->input->post("term")
if($term == FALSE) {
//return a 404 so that you can catch .error on jquery
} else {
echo $term;
}
}
Do a research on RESTFul apps. It'll help you a lot understanding that. this is a good starting point and although your question was not exactly related to this, it is a good practice to have separate layers on your application so that you just consume data from your backend, handle situations and then just react accordingly on the frontend, that is, you just use javascript to either send, receive and list data. If you are using CI or any other MVC framework then you should not really be generating HTML on your controllers, thats what the views are for.
Absolutely new to PHP and so far it isn't pretty.
Anyway, I'm trying to pass a variable over to a PHP script, do a couple things with it, and pass it back to my Javascipt code.
Here's where I pass it off to PHP:
var src=encodeURIComponent("http://www.someonlinesite.com/file.swf");
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response)
}
});
and here's the script:
<?php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I'm trying to pass the URL of a .SWF video file over to a small PHP script that will use getImagesize() to figure it's dimensions and pass them back.... but I'm not seeing anything in the response and the alert isn't firing.
What's going wrong?
UPDATE:
I've updated the code with the most recent - according to the advice from some nice SO members. When I hardcode the $src variable and navigate directly to the test.php it echoes everything perfectly. So, it looks like the PHP is working. However, it appears like either the callback is never firing or the PHP file isn't returning the data. In the console there still isn't anything in the response.
You need to concatenate your url string parameter in get():
$.get('test.php?src=' + src, function(data){
alert(data);
});
And also, your src variable begins with a double quote and is closed with a single quote. That will cause issues.
var src="http://www.someonelinesite.com/file.swf";
Also, it's probably a bad idea to do this via $_GET since you are passing a URL. $_POST would be better or encode the URL before you pass it. The current url you are passing right now would look like this in a browser:
http://www.mysite.com/test.php?src=http://www.someonelinesite.com/file.swf
That's not pretty. Using encodeURIComponent(), your whole URL will end up looking like this:
http://www.mysite.com/test.php?src=http%3A%2F%2Fwww.someonelinesite.com%2Ffile.swf
Edit to $.ajax
$.get above would work just fine, but going with the implementation of $.ajax works too:
$.ajax({
url:'test.php',
type: 'GET', //Add the type
dataType:'json',
data: {'src': src}, //Add the data, leave it out the url
success:function(data){
alert(data)
}
});
Try this :
In Jquery :
var src="http://www.someonelinesite.com/file.swf";
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response.size);
}
});
In php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I'm using the ajax function in Jquery to return some values from a PHP script with the json_encode function. The returned data seems to be full of slashes, quotes and \r\n. I understand that there must be something going wrong with stripslashes or magic_quotes (which is turned on) but can't seem to manage to get a clean output
Make sure on your ajax call from jQuery, you tell it to expect a json response. It sounds like you're returning plaintext and trying to parse it manually.
$.ajax({
url: "myscript.php",
dataType: "json",
success: function(data){
console.log( data ); //this line only works with chrome (stock) or FireFox (with FireBug plugin)
}
});
That code will echo in your console (if you don't have chrome or FF with FireBug, go get one of them :P) the json encoded output. Remember when you output from PHP, all you should be doing is this:
header('Content-type: application/json');
echo json_encode( $myAssociativeArrayOfData );
exit; //make sure nothing else happens to output something
You don't need to use any special formatting or slashes. Just make sure the json code gets output as json code with the proper headers and jQuery's ajax function should convert it for you. The result will be the data variable in the success function being your json object (php array). So if you pass in an array like this: array('foo'=>'bar') in PHP, then in your success function in jquery, you could type: alert( data.foo ); and get a dialog box that says "bar".
I'm looking to display data from a table in a mysql database using PHP, however, I want the data to automatically update itself and retrieve current values every 5 seconds.. WITHOUT having to refresh the page. Is this possible? Maybe with JQuery/ AJAX? If so, please explain how it can be done / point me to a resource where I can find such information
Thanks
If you use window.setInterval() and jQuery's .load() you should be able to do what you want. The PHP script should return the HTML that needs to replace the previous one.
Javascript:
function refreshData()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#container').load('path/to/script.php');
}
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
A really basic example:
function poll(){
$.ajax({
type: "GET",
url: "your/php/script/",
success: function(data){
// do something with data
}
});
};
setInterval(poll, 5000);
jQuery is a good option. Here are the docs for ajax.
You will want to make this call with setInterval
Something like this might get your started.
setIntervla(updateFromDb,5000);
function updateFromDb(){
$.ajax({
url: "getUpdates.php",
success: function(){
$(this).addClass("done");
}
});
};
What you are describing is exactly the type of the AJAX is used for, AJAX allows for asynchronous requests to be made to your server.
For learning I would suggest using a framework like Jquery and look into the AJAX api.
Basicly you will need a PHP script that query the database and responds the results the way you want them. A suggestion would be to JSON encode them.
In JavaScript on the client you will need to you things like:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "yourpage.php",
success: function(data){
//HANDLE DATA
// use JSON.parse(data); if your JSON encoding your data
}
});
},5000)
Just go to the documentation of jQuery:
http://api.jquery.com/category/ajax/
Use the command "jQuery.get()" or better "jQuery.getJson()" to make a http request to the server. Use JSON to get a better communication between server and client. Return from server side a json string and convert this on the client to an javascript object. (the function jQuery.getJson already do this for you) so you can easily access the key and values in the data array.
Just an example:
SERVER Part with PHP:
<?
$data = array('key'=>'value');
return json_encode($data, true);
CLIENT Part:
$.getJSON('myurl.php', function(data) {
// THIS ONE IS CALLED with your PHP data
alert(data.key);
});
$(function(){
window.setInterval(function(){
$.post("filename.php",{'field1':field1,'field2':field2,'field3':field3},function(data){
//callbackfunction(data)
})
},30000);//millisecs
});
And have your php file do all your sql
I am sending a custom XML data from jQuery to Drupal/PHP as follows:
$.ajax({
type: 'POST',
url: this.href,
success: function(data){
alert('Form is successfully saved');
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
},
data: 'myxml='+ mydata
});
My XML tags contains URLs, so I encode them, and before making an AJAX call, data looks somewhat like this:
mydata="<txtLinkLocation>http%3A%2F%2Fportal.cubewerx.com%2Fcubewerx%2Fcubeserv%2Fcubeserv.cgi%3FCONFIG%3Dhaiti%26SERVICE%3DWFS%26DATASTORE%3DOSM%26request%3DGetCapabilities</txtLinkLocation>";
And, in PHP I get the received data, and I store it as follows:
$receivedXML = $_POST['myxml'];
Now, contains of $receivedXML looks like this:
<txtLinkLocation>http://portal.cubewerx.com/cubewerx/cubeserv/cubeserv.cgi?CONFIG=haiti&SERVICE=WFS&DATASTORE=OSM&request=GetCapabilities</txtLinkLocation>
My question is why URL inside this string is being been automatically decoded? Why is this happening? I do not want any automatic operation to be performed on data that is being sent through AJAX call. How to stop this behavior? I feel like I am missing some fundamental concepts here...
$_POST data is sent to the server in the same way as $_GET. It has to be sent urlencoded else it may break. This means that by default, PHP will decode urlencodes because it expects the data to be urlencoded.
PHP decodes $_GET and $_REQUEST data it by default, see the note in urldecoding on auto-encoding server variables. Turns out that $_POST does too.
Solution: urlencode() your data again if you want it to be encoded.