I have this code which uses jquery and ajax to send a request to the other page i.e.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<input type="button" id="butt" value="button11111111111111" >
</html>
<script>
$("#butt").on('click',function(e)
{
$.ajax(
{
type:'POST',
url:'testmysql.php',
data:
{
product_type:"cake";
}
});
});
</script>
When i click the above button it should send the request and data to the other file testmysql.php
<?php
session_start();
$_SESSION['type']=$_POST['product_type'];
echo $_SESSION['type'];
?>
However , when i refresh the other page after clicking the button i do not see any kind of echo and it gives me a notice stating
Undefined index: product_type
Since, i am new to ajax and jquery is there anything i am missing ?if yes,then what should i do to make this work ?
Thanks!
Note: Both of them are in the same directory.
First of all, remove the semicolon(;) from this statement,
product_type:"cake";
^
otherwise it will give you syntax error. And now comes to your issue.
when i refresh the other page after clicking the button i do not see any kind of echo and it gives me a notice stating Undefined index: product_type
That because when you refresh testmysql.php page, the $_POST array would be empty, and there would be no index named product_type in $_POST array. You can verify it using var_dump($_POST);.
On testmysql.php page you can check whether $_POST['product_type'] is set or not like this:
<?php
session_start();
if(isset($_POST['product_type'])){
$_SESSION['type']=$_POST['product_type'];
echo $_SESSION['type'];
}
?>
you added the ; at the end of the data object. remove it and try.
and you are sending a ajax request to the testmysql.php page, the $_POST['product_type'] will available when you are send the request. when you refresh the page the you are not sending any post request to testmysql.php page.
Related
I am trying to insert html and javascript which is generated in php into a div in the page.
a.php file:
function get_preset() {
return (bunch of html, javascript);
}
b.php:
<div id="preset_preview">
//<?php echo get_preset(); ?> //this works well, but I need to execute this every time I click a button in jquery.
</div>
I can use ajax to communicate between my jquery and a.php successfully, but how do I place returned content from get_preset function call in php into preset_preview div?
Is there a way to do this without sending data with ajax from get_preset function call into jquery, then use jquery to put this into preset_preview div?
Can php somehow do it alone each time on request from jquery like this?
So I use jquery ajax to call php to execute this:
<div id="preset_preview">
<?php echo get_preset(); ?>
</div>
What is confusing to me is that php can do it successfully (as example above demonstrates) without sending data with ajax to jquery first.
a.php file
function get_preset() {
return (bunch of html, javascript);
}
echo get_preset();
b.php file
<button type="button" id="preview">Preview Preset</button>
<div id="preset_preview">
<?php include "a.php"; ?>
</div>
<script>
$('#preview').on('click', function(e) {
e.preventDefault();
$("#preset_preview").load('a.php');
});
</script>
There are several methods of jQuery AJAX which you can actually use. Example above is using load() which wraps your request with get method (you can override its request method by calling ajaxSetup(), anyways) to relative URL of a.php.
You can see a.php echoing (string of?) get_preset() function which will then placed inside <div id="preset_preview"> in b.php file.
To expand the needs of AJAX in this case is because PHP only does something like
Getting a request, no matter what the method is (get, post, put, etc)
Returns a response. Usually after you do some logic related to request value.
It dies whenever your expected response rendered to client side. You can't do anything magic behind the wall right after response is returned. In the other word, a page load is needed.
And then AJAX comes to help you create another request to corresponding PHP file. It revives a PHP file to do (another) request -> do some logic -> then do returning it. Silently, without a page load.
And in respond of comment -- Can this be done with function calls somehow without including the actual php file in preset_preview?
It's all yes. As long as you serve whatever the caller needs.
a.php file
function get_preset() {
return (bunch of html, javascript);
}
echo get_preset();
The a.php is simply echoing get_preset().
b.php
<button type="button" id="preview">Preview Preset</button>
<div id="preset_preview"></div>
<script>
$('#preview').on('click', function(e) {
e.preventDefault();
$("#preset_preview").load('a.php');
});
</script>
The b.php file is simply doing a request to a.php file. Whenever the button with selector id #preview is clicked it will load whatever a.php content to #preset_preview.
You can also render the content of a.php just after the page ready. This is similar approach like my first snippet as written on above.
<script>
$(document).ready(function() {
$('#preset_preview').load('a.php');
});
$('#preview').on('click', function(e) {
e.preventDefault();
$("#preset_preview").load('a.php');
});
</script>
It simply tells you that you should load a.php right after the b.php page is ready and "reload" it once the button clicked.
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
Any help is certainly appreciated.Thank You
Also it's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
There's multiple ways of doing so. I personally would use AJAX. On a 'form submit', run a javascript function calling an AJAX request to a .php file to check the form information, all using post method. Calculate all the $_POST['variables'] checking for your defined errors. You would have an html element print the errors via AJAX request.
If there are 0 errors then in the request back return a string as so that your javascript function can look for if its ready to go. If ready to go, redirect the user to where ever you please.
AJAX is not hard and I only suggested the idea sense you put javascript in your tags.
Another method:
Having all your code on one .php file. When you submit the form to the same .php file check for the errors (at the top of the file). If $_POST['variables'] exist, which they do after you submit the form, you echo your errors in the needed places. If zero errors then you redirect the page.
I am trying to print alert when user is redirected to login-redirect, however the alert isn't working as I want it to, instead it brings the user straight to the login-redirect.
Here's my code:
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<?php
session_start();
if( !isset($_SESSION["loginSuccess"]) ){
echo "<script type='text/javascript'>alert('Login failed!');</script>";
header('Location:' . $base_url . 'login-redirect');
}
?>
That's just how it works. You're doing a redirect, but it doesn't run the js before redirecting. If you want to run the js then you'll need to do the redirect different using a meta tag or JavaScript, rather than a http header.
The alert is working.
I think your session variable is not set.
I have PHP page that have submit button to another URL.
I want to reload the current page after the submit button clicked, and add div to the HTML.
My page url is: /foo.php, and in the HTML I have:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
As you can see the form sends request to /bar page.
I want to reload the /foo.php (the current page), and change the HTML to:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
<div>Thank you!</div>
My problem is how can I know that the user click on the button and the refresh was because the click, and not because just navigating.
Another thing, if it possible, I want that the new div will disappear if the user refresh the page again.
Why don't you just append the div in the success callback of the get function? You wouldn't have to reload the page.
<div id="btn_area">
<button onclick="$.get('/bar', function() { $('#btn_area').append($('<div>').html('Thank You');)})">Submit</button>
</div>
By the way, i hardly recommend to separate the javascript from the html and not put it directli in the DOM.
Another Method would be, to fire an additional form with a hidden parameter to the same side. After that, you check on the serverside the hidden parameter and display the div.
A third method is, to set a cookie in the Callback, reload the side, check the cookie, display the div and remove the cookie again.
In my opinion, the first mentioned option (add the div directly in the callback without reloading) would be by far the 'prettiest', but of course i don't know what else is going on on your site
Alternatively, you could simulate a flash session (one time use session) if you opt to do this in PHP. Consider this example:
foo.php
<?php session_start(); ?>
<form method="POST" action="bar.php">
<button type="submit" name="thank_you">Submit</button>
</form>
<?php if(isset($_SESSION['thank_you'])): ?>
<?php unset($_SESSION['thank_you']); ?>
<h1>Thank You!</h1>
<?php endif; ?>
bar.php
<?php
session_start();
if(isset($_POST['thank_you'])) {
$_SESSION['thank_you'] = true;
// processes
header('Location: foo.php');
}
?>
Demo
You can handle that in js side. Just make your request, and in callback, you can manipulate dom. You can see below;
<button>Submit</button>
$("button").on("click", function() {
var $button = $(this);
$.get("/echo/html", function() {
$button.after("<div>Thank you!</div>");
});
});
I've been working on a web app that allows users to submit content and have that content, and today I've been seeing some unexpected results without making any significant changes.
The basic functionality of the app is that the user submits some POST data from a form on a web page index.php, whereupon a PHP script submit.php is run to add the data to a table in a database. Meanwhile, a Jquery function on index.php is refreshing the contents of a div with rows selected from the table by means of a script load.php, and the function is called once per second.
The problem is that today, suddenly, I'm seeing long (10-20 minute) delays between when the data is added to the table and when it shows up in the Jquery-refreshed div. Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
I've checked the MySQL database before and after submit.php is called and I've verified that the data is being added instantaneously once it's submitted, so the problem has something to do with how the load.php script is called from Jquery.
This just started today. Strangely, I've been seeing this same behavior with another AJAX app that I built earlier to test the same I/O mechanism, and I haven't touched that app's code in over a week. My system administrator says there haven't been any changes to the server that would account for this.
I've posted all the code to provide all necessary information, but I think the problem is either in load.php or the javascript updateMyContent() in index.php.
index.php
<script language="JavaScript">
setInterval("updateMyContent();",1000);
$(function(){
updateMyContent=function(){
$('#refreshData').load("./module/load.php").fadeIn("slow");
}
});
</script>
<script language="JavaScript">
$(document).ready(function(){
$('#submitForm').on('submit',function(e){
$.ajax({
url:'./module/submit.php',
data:$('#submitForm').serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
$('#textID').val('');
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
</script>
<div style="float: right;
top: 0;
" id="submitDiv">
<form id="submitForm" action="" method="post">
<textarea id="textID" type="text" name="content" rows=5></textarea>
<input type="submit" value="send" name="submit"/>
</form>
<br>
<span id="error" style="display: none; color:#F00">error</span>
<span id="success" style="display:none; color:#0C0">success</span>
</div>
<div style="float: center;" id="refreshData"></div>
submit.php
<?php
if(isset($_POST['content']))
{
$content=$_POST['content'];
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$insertSQL="insert into submission (content) values (?)";
$stmt=$db->prepare($insertSQL);
$stmt->execute(array($content));
}
else
{
echo "FAIL!";
}
?>
load.php
<?php
try
{
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$PDOsql="select * from submission order by id desc";
$stmt=$db->query($PDOsql);
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $resultRow)
{
printf("%s<br>",$resultRow["ID"]);
printf("%s<br>",htmlspecialchars($resultRow["content"]));
$stmt->closeCursor();
}
}
catch(PDOException $ex)
{
echo "an error occurred! ".$ex->getMessage();
}
?>
The issue with it taking so long to return the Ajax response is probably that the table submissions has grown. Rather than each second loading all the submissions, append only new submissions to the div. I.e. keep track of the last id received and use this in the query so the where clause is limited.
Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
Ajax response can be cached by the browser just like anything else. To prevent that, you can:
Put no-cache headers in the page that processes the request to prevent browser caching of the Ajax responses. IE is particularly stubborn and will require the most forceful headers.
Add a parameter to your Ajax request that is a random number, to make every request unique.
Tell JQuery to prevent caching (it just does #2 for you). Use $.ajaxSetup ({ cache: false }); or add the cache: false, attribute to each call to $.ajax