store the text-box value in arrays - php

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;
}
?>

Related

How to handle multiple checkboxes whit PHP sent by jquery.ajax?

I'm sending a form in async with jquery.ajax method. On the PHP side it receive the right array (I think), but for some reason it shows me an error message when I try to extract the checkboxes values with a normal cicle. What can I do to fix it?
This is the Warning message I see:
Warning: Invalid argument supplied for foreach() in /home/mybestfa/public_html/ajax/verifica.php on line 206
If I try to echo the given array, I see this below. I suppose that this string it's creating the issue because actually it doesn't seem to be like a normal array. It's like a GET string:
categoria%5B%5D=bellezza&categoria%5B%5D=educazione
So the final question is, how can I extract the checkboxes values from the array?
HTML:
<form id="form_step1" action="ajax/verify.php" method="POST">
<?php
$query="SELECT name FROM category";
$result=mysqli_query($connessione, $query);
$num_check=0;
while ($row=mysqli_fetch_array($result)) {
$category_name=$row['name'];
$num_check=$num_check+1;
?>
<label for="check[<?php echo $num_check; ?>]">
<input type="checkbox" id="check[<?php echo $num_check; ?>]" name="category[]" value="<?php echo $category_name; ?>">
<?php echo $category_name; ?></label>
<?php
}
?>
<p id="result_step1"><ul></ul></p>
<input type="submit" id="button_step1" name="button_step1" class="form_button" value="Continue">
</form>
JS:
$(document).ready(function() {
$("#form_step1").submit(function(event) {
event.preventDefault();
var fields_step1=$('#form_step1').serialize();
var submit_step1=$("#button_step1").val();
$.ajax({
url: "ajax/verify.php",
method: "POST",
data: {fields_step1: fields_step1,
submit_step1: submit_step1},
dataType: "text",
success: function(risposta,status){
console.log(risposta);
if(status=="success") {
$("#risultato_step1").html(risposta);
if (risposta == "prosegui") {
$("#risultato").html("");
}
}
})
}
PHP:
if(isset($_POST['submit_step1']))
{
$errorForm=false;
$categories=$_POST['fields_step1'];
foreach ($categories as $category)
{
echo "Founded: $category<br>";
}
}
PS: I pasted the code translating the italian variables in english. So I apologize if I forgot to translate something along the road.

Submitting AJAx form in a php loop

I have been searching for 3 weeks and can't seem to solve this issue. I am new to Ajax but have figured out how to use it to submit a single form. I am trying to learn how to use Ajax to submit a form in a php loop however. I think it has something to do with individual id's but I'm not sure how to create them. My programming below only allows me to submit the first form. Does anybody know how to fix this so I can submit the forms in the loop? Thank you very much in advance for your help
Here is my code so far
<!DOCTYPE html>
<html>
<head>
<?php include 'dbconnection.php';?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function chk()
{
var name=document.getElementById('name').value;
var dataString='name='+ name;
$.ajax({
type:"post",
url: "dataInsert.php",
data:dataString,
cache:false,
success:function(phtml){
$('.msg1').html(phtml);
}
});
return false;
}
</script>
</head>
<body>
<?php
$query=mysqli_query($connect,"SELECT distinct first_name from people " );
while ($row=mysqli_fetch_array($query))
{
?>
</br> <?php echo$row["first_name"]; ?>
<form>
<input type="text" id="name">
<br/>
<input type="submit" value="submit" onclick="return chk()">
</form>
<p id="msg" class="msg1"></p>
<?php
}
?>
</body>
</html>
dataInsert.php
<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>
<?php
include 'dbconnection.php';
$first_name = $_POST['name'];
mysqli_query($connect, "INSERT INTO people(first_name)
VALUES ('$first_name')");
?>
Any help would be really appreciated
Since id's must be unique through out the HTML-document, you need to give each field a different id. That goes for all id's on element (like the msg as well) When that's done, you can pass that id to your method, making your js-function reusable.
The loop (see the comments to see the changes):
<?php
$query=mysqli_query($connect,"SELECT distinct first_name from people " );
// Initiate a counter variable
$i = 1;
while ($row=mysqli_fetch_array($query))
{
?>
</br> <?php echo$row["first_name"]; ?>
<form>
<!-- Append the counter to the ID -->
<input type="text" id="name<?= $i ?>">
<br/>
<!-- Send just the current counter to your method -->
<input type="submit" value="submit" onclick="return chk('<?= $i ?>')">
</form>
<!-- Append the counter to the message ID -->
<p id="msg<?= $i ?>" class="msg1"></p>
<?php
// Increment the counter
$i++;
}
?>
The js-function (again, see the comments to see the changes):
// Add the counter id as an argument, which we passed in the code above
function chk(id)
{
// Append the counter id to the ID to get the correct input
var name=document.getElementById('name' + id).value;
var dataString='name='+ name;
$.ajax({
type:"post",
url: "dataInsert.php",
data:dataString,
cache:false,
success:function(phtml){
// Instead of using the class to set the message, use the ID,
// otherwise all elements will get the text. Again, append the counter id.
$('#msg' + id).html(phtml);
}
});
return false;
}
Now you should be able to send all forms seperate from eachother.

Add information to textarea and save it in an array

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.

How To Get Variables Submitted by AJAX Using PHP Correctly?

I have this ajax/jquery code :
var headline = $("input#headline").val();
var subheadline = $("textarea#subheadline").val();
var pics = $("input#pics").val();
var dataString = 'headline='+ headline + '&subheadline=' + subheadline + '&pics=' + pics;
$(".save-notice").hide();
$.ajax({
type: "POST",
url: "web-block/forms/process-001.php",
data: dataString,
success: function() {
$(".save-notice").show();
$(this).parents(".manage-content-wrap").next(".ribbon-content").fadeIn();
}
});
on the other side, I have this HTML form :
<form action="" id="select-block" class="general-form">
<div class="input-wrap">
<input class="clearme" name="Headline" value="<?php echo $Headline;?>" id="headline"/>
</div>
<div class="input-wrap">
<textarea class="clearme" name="Sub-Headline" id="subheadline"><?php echo $SubHeadline;?></textarea>
</div>
<label>Bottom Left Image</label>
<div class="up-mask">
<span class="file-wrapper">
<input type="file" name="Pics" class="photo" id="pics" />
<span class="button">
<span class="default-txt">Upload Photo</span>
</span>
</span>
</div><!-- .up-mask -->
<input type="hidden" name="Key" value="<?php echo $Key;?>"/>
<input type="submit" class="submit-btn" value="SAVE" />
<span class="save-notice">Your changed has been saved!</span>
</form>
as you can see process-001.php is the file which process all variables from HTML form. but I have difficulties to 'catch' $Headline and $SubHeadline submitted by that form, which actually 'manipulates' by Ajax too...
I tried using this code on process-001.php :
$Headline = $_POST['Headline'];
$SubHeadline = $_POST['Sub-Headline'];
but seems that those variables are empty... how to get variables submitted by AJAX correctly?
Try datastream like
var dataString = {
headline: headline,
subheadline: subheadline,
pics:pics
};
for fatching in php you need to use
$Headline = $_POST['headline'];
$SubHeadline = $_POST['subheadline'];
and it will work fine
headline and Headline are not the same key. Your keys need to match exactly.
Also, as building the strings by hand can become extremely tricky very quickly, you may want to consider using an object literal or serialize():
data: {
'foo': 'bar',
'baz': [1, 2, 3]
}
Would have $_POST['foo'] === 'bar' and $_POST['baz'] === array(1, 2, 3)
You also shouldn't assume that any kind of inputs exist:
$headline = (isset($_POST['headline'])) ? $_POST['headline'] : null;
Otherwise you can get index undefined notices.
Also, since you're not using any of the options that $.post doesn't expose, you could just use $.post for shorthand:
$.post("web-block/forms/process-001.php", {
data: $("#select-block").serialize(),
function() {
$(".save-notice").show();
$(this).parents(".manage-content-wrap").next(".ribbon-content").fadeIn();
}
});
Or:
$.post("web-block/forms/process-001.php", {
data: {
Headline: $("#headline").val(), //input#headline is redundant -- getting a node by ID is extremely efficent; getting by tag is not
'Sub-Headline': $("#subheadline").val()
},
function() {
$(".save-notice").show();
$(this).parents(".manage-content-wrap").next(".ribbon-content").fadeIn();
}
});
$_POST variables are case-sensitive - your variables on the ajax side are lowercase, the PHP side is capitalized.
Are you sure that process-001.php is ever requested? Because, one of the possibilities is that when you click the submit button, the wrapping form has been submitted with empty action.
A safer way is
<input type="submit" class="submit-btn" value="SAVE" onclick="return false;" />
And
<script type="text/javascript">
$('form#select-block input:submit').click(function() {
// ajax goes here
});
</script>

Jquery submit and post to post a form unable to return data

i have problem with jquery submit and post. I would like to submit a form and post it to my php for a check, and return the php result back to the form. However, I have problem with the returning of data, it basically ignores the result.
This is my html form:
<form id="form" method="post">
<p id="status">Status:</p>
<p class="text">
<label for="name" class="label">Name:</label>
<input type="text" id="name" name="name" value="" size="30" />
</p>
<p class="text">
<label for="email" class="label">Email:</label>
<input type="text" id="email" name="email" value="" size="30" />
</p>
<p class="submit">
<input type="submit" name="send_btn" id="send_btn" value="Send" />
</p>
</form>
This is my javascript to do the submit and post:
$('#form').submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
$.post('notify.php', {name: name, email: email}, function(data) {
$('#status').html(data);
});
});
This is the php that does the check and return the data:
<?php
if (isset($_POST['name'], $_POST['email']))
{
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
if ($name == "myname")
{
$output = 'It matches!';
}
else
{
$output = 'No matches!";
}
}
?>
Can please highlight what has gone wrong? Thank you.
You need to echo or die in your php script, so your function can get the results.
So, change your script to this:
<?php
if (isset($_POST['name'], $_POST['email']))
{
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
if ($name == "myname")
{
$output = 'It matches!';
}
else
{
$output = 'No matches!';
}
echo $output;
}
?>
Notice the third to last line, where I am calling echo $output - whatever you echo will be returned from your ajax call. If you want to get more complex, you should return a JSON object.
$results = array("result" => "It Matches!", "foo" => "bar");
echo json_encode($results);
EDIT: You also need to change the " to a ' at the end of your else.
Print the answer on PHP
as comment suggest
echo $output;
at the end of the line
In your php code, you aren't actually writing $output to the page.
<?php
// your code
echo $output;
?>
dont forget
return false;
If u forget it, the form when submit will refesh and ajax will fail ;
$('#form').submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
$.post('notify.php', {name: name, email: email}, function(data) {
$('#status').html(data);
});
return false;
});

Categories