I'm working on creating a simple online booking system using PHP and AJAX.
The current layout is:
Each booking grabs a preset list of items then users can add additional items that they need.
To do this I have set up an AJAX button that calls a new drop down list each time its clicked. (This means a page could have 1 additional item or even 20, depending on how many they need.)
Once the additional items have been selected, they can then submit the form and will be guided to a confirmation page that is meant to list what they have chosen.
The issue:
None of the data is being carried through from any of the drop down lists that get added.
My AJAX script and php code on page 1 is:
<script>
function changeIt()
{
$.ajax({
type: "POST",
url: "details.php"
}).done(function( result ) {
$("#msg1").append( "" +result);
});
}
</script>
<form name ="addequip" id="addequip" action="confirmbooking.php" method="post">
<input type='button' value="Add Item" onClick="changeIt()"/>
<div id="msg1"></div>
<input type='submit' value='submit'/>
details.php:
<?php
require_once("dbconn.php");
$sql = "SELECT REFERENCE, DESCRIPTION FROM descEquip";
$result = mysql_query($sql,$conn);
?>
<select name="equip">
<?php while ($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row["REFERENCE"];?>"><?php echo $row["DESCRIPTION"];?></option><?php } ?>
</select>
And lastly my confirmation page is:
<?php $item = $_POST['equip']; ?>
<?php echo $item ?>
I'm not too sure if i need to add something to the AJAX script in order for this to work as intended or if something needs to be changed in the details.php? (I'm very new to AJAX)
I have viewed a previous question 'passing form data to mySQL through AJAX' and I couldn't make it work for me.
Lastly, for additional lists (when more than 1 item is required) do I need to have a feature that states each equip list have a different name? likename="equip<?php echo $i ?> where $i = 1++;
Any tips or examples would be appreciated,
thanks.
Never assume all will work as you want it - check if sth goes wrong in your code:
var jqxhr = $.ajax(
{
type: 'GET',
async: false,
url: 'details.php',
success: function(data, textStatus /* always 'success' */, jqXHR)
{
// ok if we are here it means that communication between browser and apache was successful
alert( 'on_ajax_success data=[' + data + '] status=[' + textStatus + ']' );
$("#msg1").innerHTML( result );
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert( 'ERROR: [operation failed]' );
}
});
Moreover - use Firefox with Firebug installed so that you can see your ajax queries/responces.
Related
I'm having trouble with an AJAX POST to PHP call.
JS in an PHP file (tableOutput.php)
var changedArr=[];
var undoRedoArr=[];
//For editing data, http://tabulator.info/docs/3.3
$("#tabulator").tabulator({
cellEdited:function(cell){
//this is called whenever a cell's value is edited.
var value = cell.getValue();
var theID = cell.getRow().getIndex();
var ip=cell.getRow().getData();
var field = cell.getField();
var x=Object.values(ip);
console.log(ip);
changedArr.push(x);
},
});
//called when I hit a button
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(){
alert("SAVED!");
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
</script>
<?php
include "getInfo.php";
?>
PHP code in a different file (getInfo.php)
<?php
if(!empty($_POST['ipString'])){
echo '<script language="javascript">';
echo 'alert("Post")';
echo '</script>';
}
if(!empty($_REQUEST['ipString'])){
echo '<script language="javascript">';
echo 'alert("Request")';
echo '</script>';
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
</html>
Earlier in the files, I have a GET command that works.
HTML in tableOutput.php
<div class=form>
<form onsubmit="fillTable()" >
<input type="submit" name="deny" value="Denied" />
<input type="submit" name="permit" value="Permitted" />
</form>
</div>
getInfo.php
$test="'CREATE'";
if( isset( $_GET['deny'] )){
$test="'DENY'";
}
if( isset( $_GET['permit'] )){
$test="'CREATE'";
}
Tried on Fedora and Windows. Code is on a server. Browser: Firefox
The Ajax posts successfully. I get an alert box saving "SAVED!", but nothing echos on the page. If I use window.location.href instead, then the getInfo.php echos to the page. The problem is that I get redirected to the getInfo.php page, which I don't want.
How do I get the Ajax to post to the getInfo.php file? Why is it not working?
It looks like you are trying to mix two different mechanisms here (AJAX and post-back). When you use AJAX, simply echo-ing output will not insert that content into the DOM (like it does when using a full post-back). Your echo statement puts data into the output stream that is then consumed by your success function. And it will stay there unless you programmatically (using javascript/jQuery) insert it into the DOM. You can manually insert that into the DOM. There are many ways of doing that. The key is looking at your response object. This is one possibility:
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(response){
alert("SAVED!");
//add the script element to the DOM body
$(response).appendTo('body');
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
It is important to understand that when including a php file (like getInfo.php), the output is written on the client side and cannot be accessed by php anymore.
What you want is to request the getInfo.php, get its response the write it on the client side.
Client:
<script>
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(textResponse /* you MUST use this parameter*/){
alert("SAVED!");
// textResponse is the string the server sends. do whatever you want with this
document.getELementById("out").innerHTML = textResponse;
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
</script>
<div id="out"></div>
At the server side, it is important you do not include any <head> or <body> tags, otherwise you will have a new document inside your <div id="out"></div>! You should write just pure text, or something that can be put inside a div element, like a table.
Server: getInfo.php
<?php
if (isset($_POST['ipString'])) {
echo "A request has been made";
}
?>
or write pure html closing the php tags (a nice trick):
<?php
if (isset($_POST['ipString'])) {
?>
A request has been made
<?php
}
?>
If your getInfo.php file needs to have its <head> and <body> tags, you must exit() the script so the rest of the file will not be sent.
<?php
if (isset($_POST['ipString'])) {
echo "A request has been made";
exit(); // exit here so ajax doesn't get the rest of the file
}
?>
<html>
<head></head>
<body></body>
</html>
Finally, if you want to be flexible and have your client do stuff based on what the server sends, you should try JSON which converts objects to strings and vice versa.
The problem was not with the code posted.
At the beginning of getInfo.php, I forgot to add "php"
It was:
<?
instead of:
<?php
I have to transfer data from one div to another, I am using AJAX to do this.
<script type="text/javascript" src="lib/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#aq").click(function(){
var name1 = $("#n1").val();
$.ajax({
type: "POST",
url: "risultato.php"
data: "name1=" + name1 ,
dataType: "html",
success: function(msg)
{
$("#risultato1").html(msg);
},
error: function()
{
alert("Chiamata fallita, si prega di riprovare...");
}
});
});
});
</script>';
<form name="modulo1'.$dationennx['id'].'">
<input type="hidden" name="name1" value="'.$dati['id'].'"
id="n1'.$dationennx['id'].'">
<a href="javascript:rispondithread(\'homeq\');"
id="aq">'.stripslashes($dationennx['oggetto']).'</a><br>
</form>
<script>
function rispondithread(h) {
$("#rispondithreadforum").attr("style", "display:block;");
}
</script>`
I am fetching the data from my table from the 'risultato.php' page, which i want to use to show a textarea on my main page with the fetched data.
<?php
$nome = $_POST['name1'];
$query = "SELECT * FROM login2.podcast
WHERE login2.podcast.id = '$nome'
ORDER BY login2.podcast.data DESC";
$dati = mysql_query($query);
while($ris = mysql_fetch_array($dati) ){
echo'
<textarea class="form-control textareaabc" readonly tabindex="8">'.stripslashes($ris['testo']).'</textarea>';
}
?>
It doesn't work if i try to fetch the data using mysql_query, but it does when i try echoing the post data in the page.
$nome = $_POST['name1'];
echo $nome
This writes the '$nome' variable in my main page.
$nome = $_POST['name1'];
echo'<input type="text" value="'.$nome.'" name="nome">';
i don't understand this. why it doesn't work? what's wrong?
It is highly likely that there is no data for the '$nome' variable in your table
Make sure that you are actually receiving data from the database, does it print out the textarea? If not, you do not have any id in your podcast table table matching the '$nome' variable.
Testing your code
Try checking if you actually get anything back when you print something out in that page, could you possibly be pointing to the wrong page?
other
Overall, i would recommend using PDO or atleast mysqli, MySQL is no longer supported since PHP 7 and deprecated since PHP 5. See: PHP.net documentation about mysql extension
sorry, i forget to include the connection to the database into the file risultato.php :P
thanks to everybody
I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.
I'm trying to send AJAX data to my wordpress table but all I can get from my PHP is a 0. Its on the admin side. Can anyone help me?
Also all of this code is inside my plugin-admin.php file inside my plugin folder.
<?php
if ( ! defined( 'ABSPATH' ) || ! current_user_can( 'manage_options' ) ) exit;
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<script>
jQuery(document).ready(function($) {
var spostsarray = new Array();
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: "POST",
action: "featured_submit_action",
data: {"posts": spostsarray},
success: function(data){
console.log(data);
}
});
});
});
</script>
I've condensed it a bit but the general idea is that I can grab all the recent posts and the user can select which ones they want to feature, send that to the PHP method and edit the table with it.
The problem is with my AJAX callback I only ever return 0 and not the data sent from the javascript.
SOLVED:
After some help from Rohil_PHPBeginner I figured it out. The reason it didn't work is that I was executing the code from the menu page at at that point it was too late to add a hook. Here is the page I used to solve it:
AJAX in WP Plugin returns 0 always
Below code worked perfectly fine for me:
<?php
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<?php
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
add_action( 'wp_ajax_nopriv_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<script>
jQuery(document).ready(function($) {
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: ajaxurl,
type: "POST",
data: data,
success: function(data){
console.log(data);
}
});
});
});
</script>
You don't need to pass the AJAX url in that way because when I used your code, it is showing me with PHP. WordPress provides a default url for AJAX so you can use that( ajaxurl which I used in below code).
Other than that You have not added code for no-privilege user (if it is going to use only for privileged user then it is okay otherwise you need to add code for that).
WordPress returns 0 when an ajax call doesn't find a valid callback function (though the 0 could be return from many other things).
WordPress looks for callbacks matching wp_ajax_{callback} when a user is logged in and wp_ajax_nopriv_{callback} when the user is logged out. {callback} is populated with the POST'd value of the "action" hidden input. Note that you're not passing the action into your AJAX call. You should change:
data: {"posts": spostsarray},
to
data: data
Since you're not going to match a callback function without passing in action, WordPress is returning 0
I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});