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
}
}
});
Related
I'm trying to send a form with AJAX and without submit button. Everything works just fine with submit button, but if I try to submit the form by clicking something else it won't work.
I searched for an answer for quite a while, but didn't find anything useful so far.
function ajaxSubmit(){
var showHideForm = jQuery('#dashboard-hki-subjects-form').serialize();
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: showHideForm,
success:function(data){
$('#formMessage').html(data);
}
});
return false;
}
$('.show-hide-subject-button').click(function(){
var subject = $(this).attr('subject');
$('#hide-subject').attr('value',subject);
});
$('#dashboard-hki-subjects-form').submit(ajaxSubmit);
I'm using Wordpress, so the AJAX is handeled with admin-ajax.php.
What if you just use an enter key handler...
Try this:
<input type="text" name="txt"/>
$('#txt').keydown(function (e){
if(e.keyCode == 13){
console.log('you pressed enter!'); //prints to the browser console...
ajaxSubmit(); //the function you described in your question...
}
})
You have to bind the ajaxSubmit() to whatever there is you're clicking, otherwise there simply will be nothing on your page to trigger it. E.g., if you want your form to be submitted whenever you click on the .show-hide-subject-button element, you have to call ajaxSubmit() explicitly:
$('.show-hide-subject-button').click(function(){
var subject = $(this).attr('subject');
$('#hide-subject').attr('value',subject);
ajaxSubmit();
});
I am working on a login form. The form fields are validated via jQuery . After jQuery validation the control goes to the php page then it fetches the values from the table in the form of array and send it back to the jQuery.
Now the problem is I want to redirect the users to the new page with the values in the array. How can I do that?
Here is my jQuery code:
$.ajax({
type:'POST',
url:baseurl,
data:data1,
success: function (response){
if (response != false)
{
window.location = index.php?u= "+response;
}
}
})
Can I send those values via post method and how do I get those values in index.php page?
EDIT-
Perhaps, its better if you change the approach. what you want is a data array in the page in which you get redirect after ajax complete.
so- better use php session.
Your controller-
class myclass extends CI_Controller {
function myfunction()
{
$data=array(
// set your data array here
);
$this->session->set_userdata($data);
}
}
Now when ajax runs this function gets executed and data array is stored in session.
$.ajax({
type:'POST',
url:'<?php echo site_url() ?>myclass/myfunction',
data:data1,
success: function (response){
if (response != false)
{
window.location = '<?php echo site_url() ?>newcontroller/newfunction';
}
}
})
now, retrieve it in your target view.
print_r($this->session->all_userdata());
/////////////////////////////////////////////////////////////////////
EDIT ENDS
For what you are asking, you cant acheive it directly, but that does'nt means it cant be done.
You can acheive it by this-
var url = 'http://example.com/vote/';
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="api_url" value="' + Response + '" />' +
'</form>');
$('body').append(form);
$(form).submit();
Now , on index.php, use $_POST to retrive the value posted by this form.
You should use absolute URL and put in between quotes :
window.location = "http://domain.com/index.php?u=" + response[0];
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 !
I have an application that I'm writing that, in one aspect of it, you click on a checkmark to complete a task, a popup window is displayed (using bootstrap), you enter your hours, and then that is sent to a PHP page to update the database. I'm using FF (firebug) to view the post. It's coming up red but not giving me an error. The only thing I'm doing is echoing out "sup" on the PHP page, and it's still showing errors, and I can't figure out why.
This is my initial click function:
$('.complete').on('click', function(event) {
var id = $(this).attr('data-id');
var tr = $(this).parent().parent();
var span = $(tr).children('td.task-name');
var r = (confirm('Are you sure you want to complete this task?'));
if (r){
addHours(id);
} else {
return false;
} // end else
});
That works fine, and it fires my next function which actually fires the bootstrap modal:
function addHours(id) {
var url = 'load/hours.php?id='+id;
$.get(url, function(data) {
$('<div class="modal hide fade in" id="completeTask">' + data + '</div>').modal()
.on('shown', function() {
pendingTask(id);
}); // end callback
}).success(function() {
$('input:text:visible:first').focus();
});
} // end function
This is also working, and the modal is displayed just fine. However, whenever I post the form to my logic page, it fails for no reason. This is the function to post the form to the logic page:
function pendingTask(id) {
$('.addHours').on('click', function(event) {
var formData = $('form#CompleteTask').serializeObject();
$.ajax({
url:'logic/complete-with-hours.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
if (data.status == 'error') {
$(this).attr('checked', false);
//location.reload();
} // end if
else {
$(this).attr('checked', true);
//location.reload();
} // end else
},
dataType: 'json'
});
}); // end click
} // end function
When this is fired, I see this in my Firebug console:
I know this is a lot of information, but I wanted to provide as much information as I could. Every other post function in the application is working fine. It's just this one. Any help would be appreciated.
Thanks in advance.
The jQuery.ajax data parameter takes a simple object of key value pairs. The problem could be that the object created by serializeObject() is too complex. If that's the case, you could either process the formData object to simplify it or try data: JSON.stringify(formData)
Does serializeObject() even exist in jQuery? is that a function you wrote yourself? Can you use jQuery functions like serialize() or serializeArray() to serialize the form data and see how it goes.
Usually the red indicates a 404 response error. We can't tell in this screen shot. Check your php code by directly calling the requested page and getting a proper response.
Also make sure your dataType is application/json which is the proper mime type header (though I don't think this is causing the error). You also should only have dataType once (you have it again at the bottom)
I figured it out. I changed the post type from the structure I entered above to a standard post:
$("#CompleteTask").validate({
submitHandler: function(form) {
var hours = $('#hours').val();
$.post('logic/complete-with-hours.php', {'hours': hours, 'id':id},
function(data){
if (data.status == 'success') {
$(checkmark).attr('checked', false);
$('.message').html(data.message).addClass('success').show();
} // end if
if (data.status == 'error') {
$('.message').html(data.message).addClass('error').show();
} // end else
},
"json"
); //end POST
} // end submit handler
}); // end validate
That seemed to do the trick
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