Why is isset($_POST['submit1']) equal to FALSE? - php

This is a follow-up of another question that I posted a few hours ago (PHP post method apparently not working).
The code still does not do what it should, but the code and also the question itself have changed so much that I prefer to post a new question (also considering that questions seem to be read mainly immediately after they have been posted). I’ll try to close the earlier question (still somewhat new here).
On to the question then: why is, in the code given below, isset($_POST['submit1']) equal to FALSE when tested? In other words, why is $_POST['submit1'] equal to NULL?
I believe that’s all I need to know.
Here is the code, which consists of two files. The file ‘form.php’ (copied almost literally from the jQuery-site: http://www.visualjquery.net/category/Ajax/jQuery.post , see last example) contains the following code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="formprocessing.php" name="formpje" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" name="submit1" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post(url,{s: term},'json');
/* Put the results in a div */
posting.done(function( data ) {
var content1 = $( data ).find( '#content' );
contentstring = JSON.stringify(content1);
$( "#result" ).empty().append( contentstring );
});
});
</script>
</body>
</html>
And the file ‘formprocessing.php’ contains the following (this includes the isset-test):
<!DOCTYPE html>
<?php
if(isset($_POST['submit1'])) {
echo ( json_encode(array("content" => $invoer)) );
}
?>
Thanks!

Because you're only posting data for s; there's no submit1 in your submitted data object.

Because you never set submit1 as part of your data object that you're passing to $.post():
var posting = $.post(url,{s: term},'json');
$.post() does not automatically pass through all of your form values; it only sends what you specify in its second argument. The only thing that will be set in $_POST is the 's' key.

I would suggest to use
if(isset($_POST['s'])) {
echo ( json_encode(array("content" => $invoer)) );
}

The data from your textbox is being sent (name="s"), not your name="submit1" guy. So either include 'submit1' in your post or look for the 's' value

You can use serialize function to serialize the form. So you will get all the element including submit1 from your form.

Related

How to pass value given by javascript variables to PHP variables?

I want the variables like screen width screen height color depth and pixel depth to be used in a PHP function. Basically what I want to do is when user come in my webpage eg:localhost/try.php I want to know all above mentioned details of client without setting cookies or session properties or get parameters. Yeah and of course without reloading the page. I know php but not AJAX so can anyone help me with that?
if i understood it right, your question is When user comes to your page(e.g try.php)how to pass javascript variable(e.g screen.width screen.height) to PHP section so that you can make it as a PHP variable.
Here is a working solution.
try.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="" method="POST" name="myForm" id="myForm">
<input type="hidden" id="screenWidth" name="screenWidth">
<input type="hidden" id="screenHeight" name="screenHeight">
</form>
<script type="text/javascript">
document.getElementById("screenWidth").value = screen.width;
document.getElementById("screenHeight").value = screen.height;
function autoSubmit ()
{
let form = document.getElementById("myForm");
form.submit();
}
window.onload = autoSubmit;
</script>
</body>
</html>
<?php
if($_SERVER["REQUEST_METHOD"] === 'POST')
{
if(!empty($_POST["screenWidth"]))
{
$screenWidth = $_POST["screenWidth"];
echo $screenWidth; // see if it gets the screen.width
}
if(!empty($_POST["screenHeight"]))
{
$screenHeight = $_POST["screenHeight"];
echo $screenHeight; // see if it gets the screen.height
}
}
?>
It basically manipulate the DOM and change the value of input value to be the screen.width and screen.height and then submit the form automatically when the window is onload.
If the the server received an HTTP POST method input then it checks the name of the POST inputs and save it into each PHP variables.

using ajax for change website language

I Have very simple PHP html code for change my website language and I need to use Ajax to not-reload after select language but honestly I never used ajax before and I don't have any idea how to use that.
I google it and found some code but I fail.
HTML:
<form action="" method="get">
<input type="submit" value="per" id="per" name="per">
<input type="submit" value="eng" id="eng" name="eng">
</form>
PHP :
function lang()
{
$lang = 'per';
if (isset($_GET['per']))
return $lang = 'per';
else
return $lang = 'eng';
}
Ajax:
$.ajax({
type: "GET",
url: 'index.blade.php',
data: {name: 'per'},
success: function(data){
alert(data);
window.location.reload();
}
});
All Code's are at one page named
index.blade.php
php code working fine just need for ajax to not-reload page when I click buttons
Try this:
html:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<form action="" >
<button type="submit" id="button1">Click
</button>
</form>
<script type="text/javascript" src="1.js"></script>
<!--<script type="text/javascript" src="2.js"></script>-->
</html>
js:
document.getElementById("button1").addEventListener("click",function(e){
//alert("hello");
e.preventDefault(); //a button's default behavior is to submit the form which this function prevents
$.ajax({
url:"example.php",
success:function(result){
alert(result);
location.href=location.href; //here you can specify where you want to get your ajax call to redirect to.
}
})
return false;
})
php file:
<?php
echo "Hello world";
?>
Hope this is what you are looking for!
I suggest studying a few tutorials on Ajax, I will try to briefly touch the subject here.
First of all, when doing Ajax, you basically call a web page or script (an actual url, not a function written in PHP). The result that you get (HTML, XML, CSS, JSON, JPG), you can use in your code, insert ii in the DOM, change the document, etc.
In my opinion, changing the language is a site-wide action that should probably be implemented as a normal call. Genearaly, if you change the language, then the whole page should be translated, from the top (title) to the last bit of text down before the closing body.
If you just need to change a small portion of the web page, please see the URL
jQuery get
The page uses an example
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
that performs what you want, just change the url. Hope I helped a bit.

jQuery JSON returned from PHP

I have a simple HTML form where user can search a word from database and PHP return result as a JSON object if the word is in database.
Strange thing is that a JSON object is returned for a word that is in database when user searches by clicking on a button instead of pressing enter key. I have the following two functions to deal with either when user press enter key or click on the button to search. How to improve my code to get the JSON object from PHP when user searches by pressing enter key after they have typed the word in text field?
$('#word-submit').on('click', function() {
var word = $('#word').val();
$.post('ajax/name.php', {word: word}, function(data) {
var obj = jQuery.parseJSON(data);
console.log(obj); //I see the object in Chrome console log.
});
});
$('#word').keypress(function(e) {
if (e.which == 13) {
var word = $('#word').val();
$.post('ajax/name.php', {word: word}, function(data) {
var obj = jQuery.parseJSON(data);
console.log(obj); //No object is return here. Why? May be something is wrong in my code.
});
}
});
<html>
<head>
<title>Welcome</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form>
<input type="text" id="word">
<input type="button" id="word-submit" value="Search">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/global.js" charset="UTF-8"></script>
</body>
</html>
PHP script works just fine. So I am not pasting it here.
The problem is most likely that your form is submitting. I would just add one listener on the form's submit event which should handle clicking the button and hitting Enter, eg
$(form).on('submit', function(e) {
e.preventDefault(); // don't submit
var word = $('#word').val();
$.post('ajax/name.php', {word: word}, function(data) {
console.log(data);
}, 'json');
});
Ideally, you shouldn't have to parse the JSON or even tell jQuery the response data type (see 'json' arg above). Make sure your PHP script has something like this...
header('Content-type: application/json');
echo json_encode($someDataArrayOrObject);
exit;
In order to make the button work with the above, change its type to submit, ie
<input type="submit" id="word-submit" value="Search">
button work because it prevent the form auto submit / reload it self.
pressing enter key on that textbox causing the form to submit and then reload it self without even triggering the $('#word').keypress(function(e)).

PHP overriding AJAX post request

On my Code I have this callback
$('#tagList').tagit({
//Every new dag will be pushed in the list array
tagsChanged: function(tagValue,action,element){
list.push(tagValue);
$.ajax({
url: "dostuff.php",
type: "POST",
data:{ items:list.join("::")},
success: function(data){
$('#wrap').append(data);
}
});
}
});
What it does it that each time I add a tag the newly added tag will be pushed in the array and after that it will make an AJAX post request.
And Then i have these field here
<form method = "POST" action = "demo3.php">
News Title <input id = "news_title" type = "text" name = "news_title" /><br>
<label>Insert Some tags </label>
<ul id="tagList" data-name="demo2">
</ul>
<input type = "submit" name = "submit" id = "submit" value = "Post News" />
</div>
</form>
and when I click the submit(it basically reloads the page) the $_POST['items'](This was created on AJAX request everytime a new tag is added) is being erased or removed in the POST global array. and therefore leaving my $_POST global array empty.
Is there anyway I can merge these two? or anyway not to let PHP override or remove the $_POST['items'] ?since I would be needing items for my query
Also I am using a plugin called tagit
If you guys are interested here's my whole code
<!doctype html>
<html>
<head>
<script src="demo/js/jquery.1.7.2.min.js"></script>
<script src="demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagit-stylish-yellow.css">
<script>
$(document).ready(function () {
var list = new Array();
$('#tagList').tagit({
//Every new dag will be pushed in the list array
tagsChanged: function(tagValue,action,element){
list.push(tagValue);
$.ajax({
url: "dostuff.php",
type: "POST",
data:{ items:list.join("::")},
success: function(data){
$('#wrap').append(data);
}
});
}
});
});
</script>
</head>
<body>
<div id="wrap">
<div class="box">
<button class = "viewTags">View Tags</button>
<form method = "POST" action = "demo3.php">
News Title <input id = "news_title" type = "text" name = "news_title" /><br>
<label>Insert Some tags </label>
<ul id="tagList" data-name="demo2">
</ul>
<input type = "submit" name = "submit" id = "submit" value = "Post News" />
</div>
</form>
</div>
</body>
</html>
and here's dostuff. php
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
print_r($_POST);
?>
The way PHP handles requests are that every request is completely separated from every other one, this sometimes referred as the share nothing architecture. This is the reason of that the request generated from the <form> to demo3.php doesn't know about the other requests sent by ajax to dostuff.php is this separation. This is not necessarily php specific, it's because the underlying HTTP protocol is stateless.
If you want to include tags into the request generated when your <form> is submitted you need to add those values to the form. For this, the tagit library has a built in way controlled by two config option:
itemName controls what the parameter named (defaults to item)
fieldName controls what the field in the itemName gets called (defaults to tags)
If you initialize your plugin like this (demo without styles):
$('#tagList').tagit({
itemName: 'article',
fieldName: 'tags'
});
Then on submit, the parametes sent down to php should be in $_POST['article']['tags'], the parameter names generated will look like article[tags][]. See the demos of the plugin. (the page source has nicely formatted javasript examples). By default simply calling $('#tagList').tagit(); without all the extra callbacks or configuration should work.
This is how it should show up in the net panel of firebug (never mind the demo4.php not beeing there)
If you want to do it manually you can hook into the submit event of <form> like this:
$('form').on('submit', function(){
var $form = $(this),
tags = $('#tagList').tagit('assignedTags'); // see the docs https://github.com/aehlke/tag-it/blob/master/README.markdown#assignedtags
$.each(tags, function(i, tag){
$('<input type="hidden" name="tags[]">').attr('value', tag).appendTo($form); // using jquery to create new elements
});
});
By using the assignedTags method (with jquery ui calling schema) of the tagit plugin, you can get the tag names, and simply add a new hidden input just before submitting the <form>. Joining them together like this might be a bad idea if your can include any string imaginable even ::.
In the example, i've used separate input for each tag so in your demo3.php they will arrive as an array (ending the name with [] makes php do that).

Collect checkbox values in jQuery and POST them on submit

I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>

Categories