Basic Qn using AJAX jQuery? - php

I just started learning using AJAX with Codeigniter. On my view, I have a textarea and a button which uses AJAX to submit the text in the textarea to my controller, which retrieves data from the database and returns this data to the view. However I am getting the error "disallowed key characters" in the callback function. This happens even when I simply echo a string. What is happening?
Btw, should I use return $result or echo $result in the controller to pass the data back to the webpage?
AJAX
$(function() {
$("#search_button").click(function(e){
e.preventDefault();
var search_location = $("#search_location").val();
$.get('index.php/main/get_places', search_location, function(data){
$("#result").html(data);
console.log(data);
});
});
});
Controller
function get_places($address) {
$search_latlng = $this->geocode_address($address);
$this->load->model('main_model.php');
$result = $this->main_model->get_places($search_latlng);
echo "test";
}

CodeIgniter has restricted the characters in the url to:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; //Inside config.php
Chances are you are putting in characters that not in this list in the address when you send the AJAX request. My suggestion would be change the $.get to $.post and then get the post data out in the controller. Something like this:
AJAX
$(function() {
$("#search_button").click(function(e){
e.preventDefault();
var search_location = $("#search_location").val();
$.post('index.php/main/get_places', {'search_location': search_location}, function(data){
$("#result").html(data);
console.log(data);
});
});
});
Controller
function get_places() {
$address = $this->input->post('search_location');
$search_latlng = $this->geocode_address($address);
$this->load->model('main_model.php');
$result = $this->main_model->get_places($search_latlng);
echo $result;
}
As for the echo vs return, use echo.

You're probably not allowing querystrings in your URL and the Ajax function adds querystring to the url. Take a look at the following url to learn how to turn querystrings on:
http://www.askaboutphp.com/58/codeigniter-mixing-segment-based-url-with-querystrings.html

Related

Post form and redirect to PHP

I'm using this jQuery code to submit a dynamic form :
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('inc/siteform.php', $(this).serialize());
});
but this method only sends the data to the PHP file. I want also that it redirects me to there, as an ordinary PHP POST submission.
How can I do it?
Here is the full testing site: http://edge-americas.com/control/main.html
UPDATE:
Using the method JQuery redirects me but it doesn't send the formdata at the same time so I can't use $_POST[] variables:
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('inc/siteform.php', $(this).serialize(),function(response){
window.location = "inc/siteform.php";
});
});
Is there any other way to keep using jquery and solve it?
You can also use window.location.replace() and pass in the URL of where you want to be redirected as a paramter.
Location.replace() for more information on the method.
Javascript works perfectly for this:
window.location.href = "URL";
Or as Andy pointed out if you want users to go back without issues simply drop the .
window.location = "URL";
You can redirect or refresh page after succcess or server answer. For example:
$.ajax({
url:"?show=ajax_request&action=add_offer",
type:"POST",
data: {var_to_send : somevar},
dataType: "json",
success: function(answer){
if ( answer.result == 'success' )
{
location.reload(); // refresh the page
}
else if ( answer.result == 'error' )
{
window.location.href = "http://google.com"; // redirect to another page
}
}
});

Ajax/ Jquery in Zend framework

I’m using Zend framework (php) and I’m trying to submit a from using ajax/jquery.
Here’s the .phtml:
<form id="find">
<input type="text" name="name">
<input type="submit" id="submit" value="Submit">
</form>
Here’s the ajax/jquery part:
$(document).ready(function() {
$("#submit").click(function(){
$.ajax({
type:'POST',
url: "<?php echo SITE_URL;?>Training/test",
data:$('#find').val(),
success: function(response) {
alert (response);
}
});
});
});
Here, “Training” is the controller and “test” is the action inside the controller. The action has just 1 line of code which is echo “hello”. After the user types a number in the box and clicks on “submit”, the control has to go to the controller thus displaying “hello” on success. However, nothing happens when I click on it. Please help me. Thanks in advance.
You didn't name parametr in Ajax call
data:$('#find').val(),
change it to
data:{'param': $('#find').val()},
About Zend it doesn't matter if it's zend or not. You can handle request just providing proper URL. You can access param value in Zend via $this->getParam('param') method.
Also you don't prevent default submit action. Change your function to:
$("#submit").click(function(ev){
ev.preventDefault();
or use in the end of function return false;
I did not test your jQuery. But note you need the instruction event.preventDefault to ensure you haven't the normal form submit action.
The main problem is at your zend Controller because you need a
special response. I suppose you have a controller to perform the request logics. I'll name it AjaxController and I'll name the action ajaxrecuestAction to illustrate how to send a proper response.
<?php
// Filename: yourProject/module/ModuleName/src/Controller/AjaxController.php
namespace ModuleName\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AjaxController extends AbstractActionController {
public function ajaxrecuestAction(){
// This function is called by zend to procces your ayax request
// you must test if it's an xmlHttpRequest
$request = $this->getRequest();
$is_xmlHttpRequest = ($request->isXmlHttpRequest()) ? 1 : 0;
if(!$is_xmlHttpRequest){
// If not you must return a normal page, a message page
// perhaps a forgiven message page, etc. It depends on your site
// logics
}else{
// The solution's KEY
// You must disable the zend's normal output
$viewmodel = new ViewModel();
$viewmodel->setTerminal($is_xmlhttprequest);
// Proccess the input and prepare your output
$output = CallTheLogicsToPrepareIt($request->getContent());
// send your response
$response = $this->getResponse();
$response->setContent($output);
return $response;
}
}
**EDIT: Just noted that, in your HTML, you didn't give an ID attribute to the "find" field. Therefore $('#find').val() will give you an error, something like "cannot find method val() of undefined. Add the id=find tag to your and it should work.
** Other Edit: Sorry about the confusion. Your form has id=find but what you want to send to the server (I believe), is the value of the fields. So give an ID=name to your input then use:
var data = {find: $('#name').val()};
You should start by using your console to see if the event is triggered. Something like:
<script>
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log('Hello');
});
});
</script>
(You do use Fire bug or the Chrome dev tools, right) ? If not, look at the end of this post.
If you can see the Hello in your console, you're on the right path. Then try to set your url in a variable and try to check it in your console:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(url);
});
});
</script>
Then you should see the url in the console, meaning you're still doing good.
If that works, try to set the data and check the output in the same way:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(data);
});
});
</script>
Hoping everything still works (you saw the data), then try the actual full code and see if you have an error or something. Also, be sure to include an error function to your ajax call so you will have a response if something went wrong on the server.
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$.ajax({
type:'POST',
url: url,
data: data,
success: function(response) {
alert (response);
},
error: function(resp) {
alert(resp.responseText);
}
});
});
});
</script>
Some tools to help you out:
If you are using FireFox, use FireBug for your debugging: https://addons.mozilla.org/fr/firefox/addon/firebug/
If you are using Chrome (my personal favorite), learn a bit more about Chrome Developer Tools: https://developers.google.com/chrome-developer-tools/?hl=fr
If you are using IE, please switch to something else for development purposes, then try it in IE to make sure you code is compatible (most likely won't be but it will be easier to find out why it doesn't work afterwards).
As for the line e.preventDefault......, look into this SO post for more details: https://stackoverflow.com/a/15913969/1483513
Hope this helps !

php : how to pass database value into a javascript/jquery function

I am implementing tags feature in my project.
In my demo tags i found they are passing names in a javascript function for the autocomple.
This is a function in my demo project,
<script>
$(function()
{
var sampleTags = ['c++', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
..................
.................
So , i want pass values from my php controller to this function ,inorder to get the autocomplete value from my database table
For example i am getting tags values from my db in my Controller like this:
` $data["query"] = $this->ordermodel->fetch_orderlist();`
$this->load->view('tagpage', $data); //loading my page tag page where above function exists
Now how can i pass that $data["query"] values into the above javascript function?
Please help
You could echo the variable onto the page using PHP's json_encode. This function will convert a PHP array or object into a JSON object, which JavaScript can work with:
<script>
$(function() {
var sampleTags = <?php echo json_encode($query); ?>;
})();
</script>
But a better way would be to request these values via Ajax. Say you have a PHP script named values.php:
<?php
#...
#assign $query here
#...
echo json_encode($query);
Then, in JavaScript (on the page where you want to use the sampleTags variable), you can use jQuery's .ajax function to make an easy Ajax request:
<script>
var sampleTags;
$.ajax({
url: 'values.php'
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
</script>
I haven't tested this example. Obviously you'll want to tweak it to fit your environment.
You will have to write an ajax function for this
$.ajax(
url : "<?php echo site_url('controller/method')?>",
type : 'POST',
data : 'para=1',
success : function(data)
{
if(data){
var sampleTags = data;
}
}
);
Just echo your php variable
$(function()
{
var sampleTags = '<?php echo $data["query"]; ?>'

javascript based Jquery ajax function, unable to send post values

Hello this is code snippet which i get from Jquery Ajax based search
I am done with everything, just the problem is the following script may not be sending the POST variable and its values or may be i am not properly fetching it.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {
contentVar: data
}, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
In php file i have the following code:-
if (isset($_POST['cv']))
{
// My Conditions
}
else
{
// Show error
}
And its showing error, This means everything is correct just the post is not working properly, maybe.
Do the var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables will do the needful or we need to do any modifications. I know questions like this really annoy people, but what should i do i am stuck up.. #userD has really helped me a lot just, this part is left.
Since you're using $.post instead of $.ajax, your call should be:
$.post(url, data, function(response) {
/// ...
});
data must be a Javascript object, like this:
data = { "cv" : cv, "cvtwo" : cvtwo };
Check Jquery's documentation for more info:
http://docs.jquery.com/API/1.1/AJAX#.24.post.28_url.2C_params.2C_callback_.29

jQuery Ajax submission problems

Why doesn't the following pick up the form? All it does is just to do a normal PHP post without throwing any errors...
I'm using blockUi on this as well, hence block/unblock.
$(document).ready(function(){
$("input.update").click(function(){
var str = $(this).parent().serialize();
$(this).parent().parent().block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
$.ajax({
type: "POST",
url: "forms/update.php",
data: str,
success: function(){
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
}
});
return false;
});
});
This is my first attempt at using jQuery's Ajax functionality so please bear with me.
("input.update").click(function(){
should be
$("input.update").click(function(){
Since it seems you're only using the 'success' callback of post you could use the .post method, which is a bit easier on the eyes. Also you can put those block calls inside ajaxStart and ajaxStop. To me it's neater.
The $(this).parent().parent().block seemed wrong to me, I changed it to reference the same element that is used for unblocking. I'd also be checking the output of the PHP script, to make sure that whatever you are 'updating' actually is updated (just echo XML from PHP and you'll see it on your console log).
$(function() {
// Apply click handlers to anchors
$("input.update").click(function(e){
// Stop normal link click
e.preventDefault();
var str = $(this).parent().serialize();
// Send request
var action = "forms/update.php";
$.post(action, {data:str}, function(xml) {
console.log(xml);
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
})
});
// Adds a wait indicator to any Ajax requests
$(document.body).ajaxStart(function() {
$("div.edit_box").block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
}).ajaxStop(function() {
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
});
});

Categories