Is it possible to do this in PHP + CSS? Got a textarea with the result of an array inside it:
<textarea class="ta_scripts"><?php
foreach ($script as $script_launcher){
echo $script_launcher."\r\n";
}?></textarea><br><br>
The code below shows a textarea with something like this:
This is a beautiful line 1 from the array
This is a beautiful line 2 from the array
This is a more beautiful line 3 from the array
And so on.
So what I want is to add some text inside the textarea, then when click a submit button this text will be added to the array $scriptlauncher[]
If I wrote "this is my new text" then the result of textarea must be:
This is a beautiful line 1 from the array
This is a beautiful line 2 from the array
This is a more beautiful line 3 from the array
this is my new text
My first approach:
HTML and PHP and call to Javascript
<form name="frmscript" onsubmit="return false;">
<?php if (isset($_POST["script"])) {
$script = $_POST["script"];
}?>
<textarea class="ta_scripts" name="ta_scripts"><?php
foreach ($script as $script_launcher){
echo $script_launcher."\r\n";
}?>
</textarea><br><br>
<input type="button" name="execscript" value="Execute scripts" id="submit" onClick="addtext();" />
</form>
Javascript:
function addtext() {
var newtext = document.frmscript.ta_scripts.value;
document.frmscript.ta_scripts.value = "";
document.frmscript.ta_scripts.value += newtext;
window.location.href = "index.php?script=" + newtext;
}
Second Approach (can't save the new array yet)
HTML and PHP and call to Javascript:
<form name="frmscript" onsubmit="return false;">
<?php /*if (isset($_POST["script"])) {*/
if($_POST){
$script = json_decode($_POST["script"]);
}
?>
<textarea class="ta_scripts" name="ta_scripts"><?php
foreach ($script as $script_launcher){
echo $script_launcher."\r\n";
}?></textarea><br><br>
<input type="button" name="execscript" value="Execute scripts" id="submit" onClick="addtext();" />
</form>
Javascript:
function addtext() {
var script = document.frmscript.ta_scripts.value;
document.frmscript.ta_scripts.value = "";
document.frmscript.ta_scripts.value += script;
script = JSON.encode(script);
var miAjax = new Request({
url: "index4.php",
data: "script=" + script,
onSuccess: function(textResponse){
$('result').set("html", textResponse);
},
onFailure: function(){
$('result').set("html", "Error!!");
}
})
miAjax.send();
Third approach (Any help would be much appreciated!):
HTML and PHP:
<form name="frmscript" onsubmit="return false;">
<?php /*if (isset($_POST["script"])) {*/
if(isset($_GET['script'])){
$script = $_GET['script'];
}
?>
<textarea class="ta_scripts" name="ta_scripts"><?php
foreach ($script as $script_launcher){
echo $script_launcher."\r\n";
}?></textarea><br><br>
<input type="button" name="execscript" value="Exec script" id="submit" onClick="addtext();" />
</form>
Javascript:
$(document).ready(function () {
$('#execscript').click(function () {
/* var name_val = $('input[name="script"]').val();*/
var script = document.frmscript.ta_scripts.value;
$.ajax({
type: "GET",
url: "index4.php", //get response from this file
data: {
name: script
},
success: function (response) {
$("textarea#ta_scripts").val(response); //send response to textarea
}
});
});
});
I'm not sure I completely understand you, but in order to read lines into an array:
$text = trim($_POST['testtextarea']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
//Push to scriptlauncher array.
array_push($scriptlauncher, $line);
}
I've not tested this, but it should put you on the right track.
Related
Still learning ajax.
Now i go stuck at this point.
Am trying to get the value of the checkbox on my form.
Below is my HTML code
<form method="post">
<input type="text" name="mytext" id="text">
<br>
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<input type="submit" id="form4" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax Script
$(document).ready(function() {
$("#form4").click(function(event) {
var action = 'another_test';
var text = $("#text").val();
var agreed = $("#agreed").val();
event.preventDefault();
$.ajax({
type: "POST",
url: "test3.php",
data: {
mytext:text,
test:agreed,
action:action
},
success: function (response)
{
$(".form-message").html(response);
}
});
});
});
Then this is my PHP code below which is on a different page
<?php
if (isset($_POST['action']))
{
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$mytext = $_POST["mytext"];
$errorEmpty = false;
if (empty($mytext)) {
echo "<p>enter your text</p>";
$errorEmpty = true;
}
elseif (empty($test)) {
echo "<p>Click the checkbox</p>";
$errorEmpty = true;
}
else {
echo "<p>Correct</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
It works for text, textarea input but not for checkbox. I know am wrong. Am still learning though.
Please help me. Thanks in advance.
Using $("#agreed").val() you only receive the value you setted in the "value" attribute on your input checkbox tag. To get a boolean value of checkbox's state you have to do use .is() function
$("#agreed").is(":checked");
There's a DIV, that display images using an external php. HTML passes the item name (user input text) to AJAX as a POST.
I'm trying to update only this DIV using AJAX but it refreshes the entire webpage? How can I fix this so only <div class="imgSlots" id="auto"> is refreshed when Submit button is pressed?
php file:
if( isset($_POST['submit']) ){
$resData = htmlentities('img/'.$_POST['val1']).'/';
}
if( isset($resData) ) {
$files = '*.*';
$fin = glob($resData.$files);
$counts = count($fin);
$imgs = array();
$div= '';
foreach ($imgs as $fin) {
$div .= '<div class="imgSlots" id="imgSlots">';
$div .= '<li><div class="imgSlotsInner"><input type="image" src="'.$fin.'"/><testDes>"'.basename($fin.$files).'"</testDes></div></li>';
$div .= '</div>';
}
echo $div;
}
HTML
<div class="searchBar">
<form action="" method="post">
Furniture item:
<input type="text" name="val1" id="val1" />
<input type="button" value="Submit" id="btn" />
</form>
</div>
<div class="menuList">
List of Furniture:
<select id='myList' name="mList" onchange='document.getElementById("val1").value = this.value;'><option value="">Furniture Available</option>
</select>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').click(function(e) {
e.preventDefault();
$.ajax({
url: 'php/filep.php',
type: 'POST',
data: $('#submit').val(),
success: function(data, status) {
$("#imgSlots").html('');
$("#imgSlots").html(data);
}
});
$("imgSlots").fadeOut("slow");
});
});
</script>
you need to do some changes like below (and i hope this is what you need)
in html create div with id imgslots like below
<div class="imgSlots" id="imgSlots">
</div>
in js do like this
var val1 = $('#val1').val();
then in data
data: {'val1':val1},
and in php
if( isset($_POST['val1']) ){
$resData = htmlentities('img/'.$_POST['val1']).'/';
}
and in loop
$list= '';
foreach ($imgs as $fin) {
$list.= '<li><div class="imgSlotsInner"><input type="image" src="'.$fin.'"/><testDes>"'.basename($fin.$files).'"</testDes></div></li>';
}
echo $list;
The way you doing it your submit button has 2 action :
the submit action as a type submit button
the onclick action that you set from jquery
You have two options
Override the form submit action (also remove the onclick event)
var form = $('<My form selector>');
form.submit(function () {
$.ajax({
type: post,
url: "your url",
data: form.serialize(),
success: function(jsonObj){
}
});
});
The other solution is to delete the type submit form the button and keep you onclick event as it is. Also in ajax request in data: you have to put an object with the data you want to sent.
i have one html page in them one text-box
<input type="text" id="region&activity">
<input type="button" id="result" value="submit">
in text-box i am entered Race in Gujarat i want to store this value in to Array
something. Race in one array and Gujarat in another array
help me or give some idea to do this.
thanks
try this
<?php
$abc='race in gujrat';
list($event,$state) = split('in',$abc);
echo $event;
echo $state;
?>
and store that string in array
Using PHP
This result assumes you are splitting them into an array after the space.
$text = "Race in Gujarat";
$result = explode(" ", $text);
echo $result[0]; //Race
echo $result[1]; //in
echo $result[2]; //Gujarat
if you want to use java script then do something this type:-
<script>
$(function(){
$("#filter").click(function(){
var name = $('#select').val();
alert(name);
$.ajax({
type: "POST",
data: {"name":name} ,
url: "array.php",
async: false,
success: function(result) {
alert(result);
$("#result").text(result);
}
});
});
});
</script>
this is your html code:-
</head>
<body>
<input type="text" id="select">
<input type="button" id="filter" name="button" value="Search">
<div id="result">
</div>
</body>
</html>
this is array.php:-
<?php
$name= $_POST['name'];
$result = explode("in", $name);
foreach($result as $row){
echo $row;
}
?>
As your question isn't clearly defined, I'm assuming that you wish to remove the word "in", and split the the string into separate arrays on the space character.
How about (using jQuery for convenience):
var splitRegion=$("#region&activity").val().replace(/in /g," ").split(" ");
myArray1.push(splitRegion[0]);
myArray2.push(splitRegion[1]);
By the way, I believe an ampersand (&) is an illegal character in an id.
try this:-
<?php
$abc= $_POST['name'];
list($event,$state) = explode('in',$abc);
$array1[]=$event;
$array2[]=$state;
foreach($array1 as $city)
{
echo $city;
}
foreach($array2 as $st)
{
echo $st;
}
?>
I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;
I want to add a comment system after my article,
php part code
<?php
...
while($result = mysql_fetch_array($resultset))
{
$article_title = $result['article_title'];
...
?>
<form id="postform" class="postform">
<input type="hidden" name="title" id="title" value="<?=$article_title;?>" />
<input type="text" name="content" id="content" />
<input type="button" value="Submit" class="Submit" />
</form>
...
<?php
}
?>
ajax part:
$(function($) {
$(document).ready(function(){
$(".Submit").click(function(){
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var anyBlank = 0;
if(anyBlank == "0")
{
var title = $("#title").val();
var content = $("#content").val();
$.ajax({
type: "POST",
url: "ajax_post.php",
data: "title="+title+"&content="+content,
success: function(date_added){
if(date_added != 0)
{
structure = '<div class="comment_date_added">'+date_added+'</div><div id="comment_text"><div id="comment_content">'+content+'</div>';
$("#post_comment").prepend(structure);
}
});
});
ajax_post.php
echo $title;
echo $content;//get $title and $content and insert into database.
my question: <form id="postform" class="postform"> is written into a MYSQL_QUERY result circle. how to modify ajax part so that every div.submit can post its own value to ajax_post.php and then return the data into $("#post_comment").prepend(structure); Thanks to all.
You have to give the input fields a class instead of an ID. IDs have to be unique in an HTML document:
<form class="postform">
<input type="hidden" name="title" class="title" value="<?=$article_title;?>" />
<input type="text" name="content" class="content" />
<input type="button" value="Submit" class="Submit" />
</form>
Then you can make the data lookup relative to the clicked element:
var title = $(this).siblings('.title').val();
var content = $(this).siblings('.content').val();
I also suggest to pass an object to the data attribute for automatic URL encoding of the values:
data: {title: title, content: content}
Then, when you create a new entry for the #post_comment section, you have to give these elements also a class instead of an ID (and don't forget to use var!):
var structure = '<div class="comment_date_added">'+date_added+'</div><div class="comment_text"><div class="comment_content">'+content+'</div>';
or more jQuery like:
$('<div />', {class:'comment_data_added'})
.append($('<div />', {class: 'comment_date_added', text: date_added}))
.append($('<div />', {class: 'comment_content', text: content}))
.prependTo('#post_comment');
Further notes:
You have somehow a nested ready() handler:
$(function($) { // <--┐
$(document).ready(function(){ // <--┴- this is the same
//...
});
});
Either do:
jQuery.noConflict();
jQuery(function($) {
$('.Submit')...
)};
or
$(function() {
$('.Submit')...
)};
This part in the click handler:
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var anyBlank = 0;
does not seem to do anything. Besides that, the submit button has no ID and no name.
Depending on the further structure of your PHP code, you should have a look at the alternative syntax for control structures. It makes easier to mix PHP and HTML without fiddling around with brackets.