I have a PHP form:
<form action="" method="post" id="CheckBoxForm">
foreach ( $results as $result ) :
<input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).'"/>
<input type="submit" name="submit" value="Submit"/>
</form>
I take values from it in js file:
jQuery('#CheckBoxForm').on('submit', function(e) {
var chkArray = [];
var CheckBoxForm=jQuery(this).serialize();
alert(CheckBoxForm);
jQuery(".chk:checked").each(function() {
chkArray.push($(this).val());
});
var selected;
selected = chkArray.join(',') + ",";
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: selected,
success:function(data){
jQuery("#feedback_country").html(data);
}
});
return false;
});
});
If I alert selected it gives me list of values. So script has initialized and took data.
At the end of the script it receive feedback data html(data) and send it back to initial php file.
PHP file which take request from js file (POST REQUEST) has such code:
foreach($_POST['check_list'] as $selected){
echo $selected."</br>";
}
And it send back 0. I can't understand what is wrong.
You have too much extra code in your JavaScript that is unneeded. You don't need those chkArray or selected variables.
jQuery('#CheckBoxForm').on('submit', function(e) {
var CheckBoxForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: CheckBoxForm,
success:function(data){
jQuery("#feedback_country").html(data);
}
});
return false;
});
That should be all you need. serialize() will take all the values from the form and create a string in the correct format to be sent to your PHP script.
Note: Your HTML is incorrect, your form should look like this:
<form action="" method="post" id="CheckBoxForm">
<?php foreach($results as $result): ?>
<input type="checkbox" class="chk" name="check_list[]" value="<?=$result->meta_value?>"/>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit"/>
</form>
You want to use the name attribute, not id on your checkboxes.
Your problem is that you are sending a single string instead of key - value pairs:
selected = chkArray.join(',') + ",";
...
data: selected,
Although I would not recommend building the query string manually - serialize() will take care of the correct escaping - you can send your check-list string like:
data: {check_list: selected},
Edit: Now in php you will have a $_POST['check_list'] variable but that is a list in a comma-separated string. So to convert it into an array and loop over it, you would need something like:
$arr = explode(',', $_POST['check_list']);
foreach ($arr as $selected) {
echo $selected."</br>";
}
Related
Background
I am a complete beginner to web designing and i am using PHP and mySQL.
Code in hand
This is my HTML file named UserRegistration.php
<?php
session_start();
?>
<html>
<body>
<script>
function FillRecord(Id)
{
$.ajax({
type: "POST",
url: "Algorithm/UserRegistration-FillUserRecords.php",
data:'Id='+Id,
success: function(data)
{
document.forms["Frm_User"].elements["txtName"].value = "";
document.forms["Frm_User"].elements["txtFName"].value = "";
document.forms["Frm_User"].elements["txtMName"].value = "";
}
});
}
</script>
<form id="Frm_User" name="Frm_User" method="POST" action="Algorithm/UserRegistration-SaveDetails.php">
<label for="txtName">Name</label>
<input type="text" name="txtName" placeholder="Name" required>
<label for="txtFName">Father Name</label>
<input type="text" name="txtFName" placeholder="Father Name" required>
<label for="txtMName">Mother Name</label>
<input type="text" name="txtMName" placeholder="Mother Name" required>
</form>
<input type="button" onclick="FillRecord(1);">//1 is fixed at the moment
</body>
</html>
This is my PHP class named UserRegistration-FillUserRecords.php
<?php
session_start();
include_once 'Connection.php';
if ($dbcon->connect_error)
{
die("Connection failed: " . $dbcon->connect_error);
header('Location: ../UserRegistration.php');
exit();
}
//Search data from database on all fields except "SNo"
//----------------------------------------------------------------------------
$sql = "Select * from usertable where id=".$_POST["Id"];
$result = $dbcon->query($sql);
$rows = array();
foreach ($result as $RowRecord)
{
$_SESSION['UserRegistration_txtName'] = $RowRecord["Name"];
$_SESSION['UserRegistration_txtFName'] = $RowRecord["FName"];
$_SESSION['UserRegistration_txtMName'] = $RowRecord["MName"];
}
exit();
?>
The Algorithm/UserRegistration-SaveDetails.php is used to save the user details into database which is working perfectly.
Problem
I want to show the data which is being retrieved by UserRegistration-FillUserRecords.php into UserRegistration.php's already created textbox when the function FillRecord is called but i have no clue as to how to assign the session variable value to my input boxes.
I Tried
1) alert(<?php echo $_SESSION['UserRegistration_txtName']; ?>);
but the statement doesn't seem to work even when i have used
2) success: function(data) in AJAX reponse has the value which i need but when i echo it, it shows the value in continuation like:-
abc
----------------
a (Name)
b (Father Name)
c (Mother Name)
and i cant seperate it as the string can be anything, it can be full of comma's, new line characters and any special symbols
Your PHP code doesn't actually output those session variables you've created to the browser. To do that, you need something like this (I'm using JSON as the format in which to send the data, as it's easiest to work with on the receiving end).
foreach ($result as $RowRecord)
{
$_SESSION['UserRegistration_txtName'] = $RowRecord["Name"];
$_SESSION['UserRegistration_txtFName'] = $RowRecord["FName"];
$_SESSION['UserRegistration_txtMName'] = $RowRecord["MName"];
}
// Create an array to send the data
$data = [
'Name' => $_SESSION['UserRegistration_txtName'],
'FName' => $_SESSION['UserRegistration_txtFName'],
'MName' => $_SESSION['UserRegistration_txtMName']
];
// Tell the browser that a JSON data file is coming
header('Content-type: application/json');
print json_encode($data);
exit();
Your jQuery AJAX handler function can then easily populate the form with these values:
function FillRecord(Id)
{
$.ajax({
type: "POST",
url: "Algorithm/UserRegistration-FillUserRecords.php",
data:'Id='+Id,
dataType: "json", //Add this so data comes back as an Object
success: function(data)
{
document.forms["Frm_User"].elements["txtName"].value = data.Name;
document.forms["Frm_User"].elements["txtFName"].value = data.FName;
document.forms["Frm_User"].elements["txtMName"].value = data.MName;
}
});
}
I hope I've correctly understood (and satisfied) what you want to achieve, please feel free to say if not.
I have a block of code which is a dynamically generated div with a form (based on array loop) that has dynamic inputs which are added by a button:
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
That code above is working and simply allows the '+' button to add a new input. I'm getting the input values as well as the tickerID from my hidden input in preparation for ajax submission. I'm getting what I expect from the serialized form but I have an issue.
The following code:
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serialize();
console.log(data);
});
</script>
Prints this:
Items%5B%5D=this&Items%5B%5D=is&Items%5B%5D=test&tickerID=1
Which I expect. The problem is that with my ajax call to my mysql insert function, I need to insert one record for each value plus the tickerID. My sql insert is inserting into columns tickerID and content. So for the above console.log, I would need the following insert:
tickerID | content
----------------------
1 this
1 is
1 test
How can I properly pass my form data to the ajax and then do something like a foreach in order to insert multiple records?
ajax call
<script type="text/javascript">
$("#Items").submit(function(e) {
$.ajax({
type: "POST",
url: addticker.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
addticker.php
$tickerID = $_POST[''];
$content = $_POST[''];
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$content');
"
$mysqlConn->query($addTicker)
Hope this works.
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
I need to be able to send a JavaScript variable to a PHP function. I was able to get it working for hard-coded values such as the code below.
<button onclick="submitform()">Click me</button>
<script>
function submitform(){
document.write(' <?php send_mail('hello'); ?> ');
}
</script>
<?php
function send_mail($subject){
//$subject => 'hello'
//Do something with subject
}
?>
However, I cannot replace the hard-coded value with a variable. I would also like to find another way to issue the PHP function call. I believe the solution lies in an ajax request. I cannot find a way to do this with the PHP code directly embedded as it is now. All of the other examples I cannot get to work. If possible, I would appreciate a demo as well. Thanks!
You can do it using forms:
<form action="send_mail.php" method="post">
<input type="text" id="mail" name = "mail">
<input type="submit" class="btn" value="Send Mail">
</form>
Then you can access the mail using $_POST["mail"] from the send_mail.php page
Another way to do it is ajax:
$.ajax({ url: '/send_mail.php',
data: {action: 'sendEmail', mymail:$('#mail').val()},
type: 'post',
success: function(output) {
alert(output);
}
});
Then in the send_mail.php page you can do:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
$mail = $_POST['mymail'];
switch($action) {
case 'sendEmail' : send_email();break;
// ...etc...
}
}
Demo for same page call:
<?php
if(isset($_GET['action'])=='myfunc') {
echo "Hello";
}
?>
<form action="?action=myfunc" method="post">
<input type="text" id="mail" name = "mail">
<input id="clickMe" type="submit" value="clickme"/>
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 am building small web app, and I want to:
read var from user input
pass this var to PHP via AJAX when the user clicks on link
receive array (JSON)
parse the array and fill them into two input values
And the last action is difficult for me.
Simple example PHP:
<?php
$array = array("name" => "James", "surname" => "Bond");
echo json_encode($array);
?>
and my HTML is something like:
<script>
$(document).ready(function(){
$("#click_me").click(function(){
$.post('127.0.0.1/read_from_php/', {
my_var : $("#my_var").val()
}, function(data) {
//how to read and parse JSON from PHP here
//and put name and surname as a input value below:
$('#name').val(data);
$('#surname').val(data);
});
});
});
</script>
<input type="text" id="my_var" name="my_var" value="">
Click to read from PHP
<div id="my_div">.. loading ..
<input type="text" name="name" id="name" value="name"/>
<input type="text" name="surname" id="surname" value="surname"/>
</div>
Use JSON.parse() to convert the json string into an object:
<script>
$(document).ready(function(){
$("#click_me").click(function(){
$.post('127.0.0.1/read_from_php/', {
my_var : $("#my_var").val()
}, function(data) {
var person = JSON.parse(data);
$('#name').val(person.name);
$('#surname').val(person.surname);
});
});
});
</script>
Or, alternatively maybe you could change to $.getJSON() as it will already handle the parsing internally.
var obj = jQuery.parseJSON(json_data);
After that, you can use it as you want.
obj.name, obj.surname
Set correct content type headers, when rendering JSON with PHP
<?php
$array = array("name" => "James", "surname" => "Bond");
header('Content-Type: application/json');
echo json_encode($array);
?>
Add a data-type to jQuery.post call, it will tell jQuery to expect JSON in response. This should allow you to directly access the data object without any additional decoding calls, read this doc for more info http://api.jquery.com/jquery.post/
<script>
$(document).ready(function(){
$("#click_me").click(function(){
$.post(
'127.0.0.1/read_from_php/',
{
my_var : $("#my_var").val()
},
function(data) {
//how to read and parse JSON from PHP here
//and put name and surname as a input value below:
$('#name').val(data.name);
$('#surname').val(data.surname);
},
'json'
);
});
});
</script>