How to make redirection with variable URL - javascript

I have a form on my page an there is a problem with PHP/JS redirect.
I have 3 conditions:
I can't use PHP "header location" to redirect because I need the page not to be refreshed on form submit, so I defined button type='button', NOT type='submit' and I'm using AJAX.
I can't define redirection URL in AJAX's "success", because the URL should be variable, depending on previous user's actions. So I need to define the URL in PHP.
I have to define URL only after user has clicked on the button on my page, not before.
The problem is, that JS doesn't see the URL defined in PHP, so redirection doesn't work (If I define the URL in AJAX's "success", then it works fine).
$(document).ready(function () {
$("#my_button").click(function () {
$.ajax({
type: 'POST',
url: 'file.php',
data: {check_button: '1', email: 'user#email.com'},
success: function(data){
//var url = "https://.................."; // THIS WORKS FINE!
var url = document.getElementById("my_url").value; // THIS DOESN'T WORK!
window.location.href=url;
}
});
});
});
// echo "<input type='hidden' id='my_url' value='https://................'/>"; // THIS WORKS FINE!
if (isset($_POST['check_button'])) {
echo "<input type='hidden' id='my_url' value='https://................'/>"; // THIS DOESN'T WORK!
// Do something
}
And I need to define the URL exactly in this statement. How can I do that?
Thanks for your help in advance.

Make the following change in PHP code :
if (isset($_POST['check_button']))
{
echo "https://................"; // URL you want
}
Then make the following change in Ajax code :
$.ajax({
type: 'POST',
url: 'file.php',
data: {check_button: '1', email: 'user#email.com'},
success: function(data)
{
window.location.href=data;
}
});

Related

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

Ajax / Jquery refresh page after variables are passed

Okay so am using Ajax to send a JS variable from index.php to page2.php . Once it is set to page2.php, the database is edited while the user has been on index.php the entire time. However, I need the index.php to reload or refresh once page2.php has finished updating the database in the background. To give you a better clue, I will include some of my code.
On Index.PHP is :
<a href='#' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
and
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
});
}
So basically when they click the button that says "Update" it sends the ID of the button the page2.php and page2.php from there updates the changes the database using that info. However, the URL the user is on is:
http://website.com/index.php#
and the database has not updated for them and they have to see the annoying hash symbol in the URL. I have googled how to refresh the page in JS, and found things that either do not work or do work , but result in the variables not being sent to the PHP file. I just need it so that after it is sent to the php file, and preferably after the php file is finished, the index.php page refreshes and without the # at the end.
e.preventDefault() is the answer but if I may suggest:
Get rid of that inline function and add the event handler with jQuery.
$(function () {
$('.dbchange').click (function (e) {
e.preventDefault();
var id = this.id;
$.ajax({
type: "POST",
url: 'page2.php',
data: {NewID: id},
success: function(data) {
window.location.reload();
}
});
});
});
Remove # then replace with javascript:void(0):
<a href='javascript:void(0)' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
JS:
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
success: function() {
window.location.reload();
}
});
}

codeigniter or PHP - how to go to a URL after a specific AJAX POST submission

I am successfully inserting data into my database in codeigniter via a an ajax post from javascript:
//JAVASCRIPT:
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
$('body').append(data); //MH - want to avoid this
}
});
//PHP:
public function respond(){
$this->load->model('scenarios_model');
$responseID = $this->scenarios_model->insert_response();
//redirect('/pages/view/name/$responseID') //MH - not working, so I have to do this
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
echo "<script>window.location = '$redirectURL'</script>";
}
But the problem is that I can't get codeigniter's redirect function to work, nor can I get PHP's header location method to work, as mentioned here:
Redirect to specified URL on PHP script completion?
either - I'm guessing this is because the headers are already sent? So as you can see, in order to get this to work, I have to echo out a script tag and dynamically insert it into the DOM, which seems janky. How do I do this properly?
Maybe you can 'return' the url in respond function and use it in js
PHP :
public function respond(){
// code
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
return json_encode(['url' => $redirectURL]);
}
JS :
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
dataType: 'JSON',
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
window.location = data.url
}
});
you have to concatenate the variable. That's all.
redirect('controller_name/function_name/parameter/'.$redirectURL);

Ajax link to run codeigniter controller then update html

Sorry for the most simplest of questions but I can't seem to get anything to work. It's the first time I've really played around with AJAX.
I'm developing in codeigniter and I have a link that when clicked runs the controller: photo function: like and allows the logged in user to like the photo then redirects the user back to the photo and displays a slightly different version of the button showing that the user likes the photo.
<?php if ( $like_count > '0' ) { echo $like_count; } ?>
It works fine but I thought it would be cool to replace it with an ajax function so it's more of a fluid motion instead of navigating off the page and then back again.
Any help would be greatly appreciated.
$(".uk-button").click(function(e) {
e.preventDefault();
//Here you can add your ajax
$.ajax({
url: site_url + 'photo/like',
data: {
liked : 1
},
type: 'POST',
dataType: 'json',
async : false,
success: function(success_record) {
console.log(success_record,":success_record");
//You might receive your like count from PHP here
}
});
});
In your success record you would get your PHP record values. Based on that you can increment or decrement count in success function
You can do something like this:
$(document).ready(function()
{
$('.likeLink').on('click', funciton()
{
var obj = $(this);
var id = obj.attr('id'); //anything you want to pass to update your like somewhere
$.ajax(
{
type: 'POST',
url: 'YourFilePathWhereYouWillDoTheLike',
data:
{
id: id,
},
cache: false,
success: function(response)
{
obj.html("You have liked this!");
}
});
return false;
})
})

Categories

Resources