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];
Related
I am using a jquery calendar script that assigns the content of a div using ajax.
$('#details-event-id').html(id);
The div tag:
<div id="details-event-id"></div>
is in another file and displays the id correctly.
<div id="details-event-id">91</div>
Is it possible to get the id, 91, to be assigned to a PHP variable?
Using ajax you can send the value to the server and then assign to the php variable.
If you think you assign php variable in any javascript event in client side, its not possible without any asynchronous calling of the server script.
If I understand correctly you would like to send the variable id to a PHP file. You can achieve this by using AJAX. Bellow I'm showing two ways to get it done.
var id = $('#details-event-id').html(id);
AJAX with good old JS
ajax(myfile.php, {id:id}, function() {
// the following will be executed when the request has been completed
alert('Variable id has been sent successfully!');
});
function ajax(file, params, callback) {
var url = file + '?';
// loop through object and assemble the url
var notFirst = false;
for (var key in params) {
if (params.hasOwnProperty(key)) {
url += (notFirst ? '&' : '') + key + "=" + params[key];
}
notFirst = true;
}
// create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
AJAX with JQuery
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: ({
id: id
}),
success: function(data) {
// the following will be executed when the request has been completed
alert('Variable id has been sent successfully!');
}
});
Offtopic: you can see why some prefer JQuery...
When either function (Jquery or plain JS) is launched it will send the variable id to the file myfile.php. In order to retrieve the variable from the call you won't use $_GET[...] but $_REQUEST[...].
myfile.php
<?php
if(!isset($_REQUEST['id'])) {
echo "no variable was sent";
}
$id = $_REQUEST['id'];
// process data, save in db, etc ....
You may return a value to the JS callback function by using echo() not return
My code igniter web page has side bar check boxes and news articles on main panel updated from database. when i select check box i want to pass check box ID to controller and return only relevant news articles according to check box value. How to do it? What is the mechanism using here?
example web site same as i expected
<?php
foreach ($data as $add) {
echo "<div>";
echo '<p class="target">' .$add->news_data. '</p>';
echo "</div>";
}
?>
To Do that ...You have to make an ajax call "onclick" of checkbox group and then on ajax call you have to fire query with the IDs which have been passed
So,set AJAX function
$("#sidebar input[type='checkbox']").click(function(e){
var values = [];
$( "input[name='post_type']:checked" ).each(function(){
values.push($(this).val());
});
var Type = values.join(", ");
$.ajax({
type: "POST",
url: "filterpost.php",
data: "typID="+Type ,
cache: false,
success: function(){
alert("success");//just to check only
}
});
});
Step 2:Now create filterpost.php file
Now get the post value at the other side
$id = $_POST['typID'];
and from here fire the appropriate query using "IN" keyword
Step 3:
and pass that data to the view after that.
I can't give you the whole example directly...just follow this steps
I hope you will get solution
$('input[type="checkbox"][name="change"]').change(function() {
if(this.checked) {
// some ajax request
}
});
Similarly with plain JavaScript:
// checkbox is a reference to the element
checkbox.onchange = function() {
if(this.checked) {
// some ajax request
}
};
And your function function return an JSON as your example
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
}
}
});
I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.
I need to send form values from one page to another and from that page to a third page. I would need the form values from the first page in the third page. How can I do it?
I have the code that transfers form values to the next page. How can I send the same form values to the third page?
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript">
// we will add our javascript code here
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg){
$("#note").ajaxComplete(function(event, request, settings){
if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
window.location.href = "http://www.google.com";
$("#fields").hide();
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
</script>
you can use GET
window.location.href = "http://yourdoamin?value= serialize text variable";
Get URL parameters & values with jQuery
Assuming you're using only simple values (not passing arrays), you can do something like this:
echo "<form id='second_page' method='post' action='third_page.php'>";
foreach ($x in $_POST) {
echo '<input type="hidden" name="' . htmlspecialchars($x) . '" value="' . htmlspecialchars($_POST[$x]) . '" />';
}
Use sessions - here is a Tutorial
You can set the values from Form #1 as input tags with hidden type in Form #2. That way, when you submit Form #2, values will be available in Form #3.