Jump to content

Basic problem with isset


Go to solution Solved by Barand,

Recommended Posts

Hi, I'm very new to PHP so I hope this is not frustrating. I'm having trouble understanding how "isset" works. I'm trying to get it so that when I click a button, it returns two variables(in an array). This works, but I tried to use "Isset" to detect if a array was created, then alter the variable. It's not working... I'm not too sure where I'm going wrong, could anyone give me some advice? Thanks

<?php 


if(isset($_POST['name']))
{
	$userAnswer = $_POST['name'];
	if(isset($_SESSION['test'])){
			$_SESSION['test'][$userAnswer]['var1']++;
			$test = $_SESSION['test'][$userAnswer];
			foreach ($test as $key){
					echo json_encode($key);
						};
					}
	
	else {
	$test = $_SESSION['test'][$userAnswer]=array("var1" => 1, "var2" => 2);
	
	foreach ($test as $key){
				echo json_encode($key);
				};
	}
}


?>


$(document).ready(function(){
  $("button").click(function(){

                var test = "here";
                $.ajax({
				     url: 'info.php', 
				     type: "POST",
				     dataType:'json', 
				      data: ({name: test}),
				     success: function(data){
				     	     
					 $("#click").fadeOut(function() {
					 		 $(this).append(data);
					 		 
					 }).fadeIn();
					
				     }
				 
					});
  });
  
});


Link to comment
https://forums.phpfreaks.com/topic/292265-basic-problem-with-isset/
Share on other sites

It's there, I just didn't want to put in all the code because it's rather long. (sorry, should have cleared that up in the inital post)

<?php 
session_start();
?>	
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
 <script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="jquery.ui.touch-punch.min.js"></script>
<link rel="stylesheet" type="text/css" 
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css"/>

<script src="jquery.custom.js" > </script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){

                var test = "here";
                $.ajax({
				     url: 'info.php', 
				     type: "POST",
				     dataType:'json', 
				      data: ({name: test}),
				     success: function(data){
				     	     
					 $("#click").fadeOut(function() {
					 		 $(this).append(data);
					 		 
					 }).fadeIn();
					
				     }
				 
					});
  });
  
});
</script>
Edited by 7blake

Like so?

<?php 


if(isset($_POST['name']) && isset($_POST['name2']))
{
	$userAnswer = $_POST['name'];  // name == 1
	$userAnswer2 = $_POST['name2']; // name == 2
	
	$newArray = array();
	$newArray[0] = $userAnswer;
	$newArray[1] = $userAnswer2;
	
	
		
	echo json_encode($newArray);
	
}


?>

I suppose that works. I'm a bit confused actually as to why it's being made into a string? Does json_encode convert arrays to string? I thought I needed a foreach to echo the array.

But in anycase, this wasn't the concept I was trying to understand.(but it's produced more questions :).. :|)

In the inital example, $_SESSION['test'] is not Set. So the "else" statement runs. But when I initate the action again, shouldn't $_SESSION['test'] be set, thus executing the "if" statement instead of the "else" statement?

Edited by 7blake

 

You obviously like typing :)

if(isset($_POST['name']) && isset($_POST['name2']))
{
    echo json_encode(array($_POST['name'], $_POST['name2']) );
}

Ahh :) So that'd be called using your head. Cool thanks. (btw - how come I don't have to use a loop to access the array? Is it converted to a string?) *edit* Ah ok nm

 

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

http://stackoverflow.com/questions/11195692/how-to-json-encode-php-array-to-a-json-array-not-as-a-json-object

 

Do you by chance know what is wrong with my first code? Is it my SESSION itself not registering or how I've written it out?

Edited by 7blake

You don't seem to be returning a json encoded array, rather a list of json encoded variables instead, which is just a list of those variable values

 

So you are return something like "12"; To return a json encoded array use

echo json_encode($_SESSION['test'][$username])

which will return

{"var1":2,"var2":3}

Alternatively, change the ajax request to expect plain "text", which is what you are returning.

Hmm. There's a problem somewhere prior to that in my code. Or I am doing this structurally wrong.

 

When I click the button, ajax sends via POST 'name'(not sure what you call this, POST variable?) Then PHP recieves it, checks if it isset, and moves to the IF statement.

 

On the first click  $_SESSION['test'] is not set, so the else is executed. But in the else, am I not initiating $_SESSION['test'] ? I want it so when I click the button a second time, it runs the IF statement. Is the problem with my ajax? Or maybe my SESSION isn't starting properly?

 

I tried your suggestion with 

echo json_encode($_SESSION['test'][$username])

and that won't pass any information.

<?php 


if(isset($_POST['name']))
{
	$userAnswer = $_POST['name'];
	if(isset($_SESSION['test'])){
			$_SESSION['test'][$userAnswer]['var1']++;
			$test = $_SESSION['test'][$userAnswer];
			
					echo json_encode("test2");
						
					}
	
	else {
	$test = $_SESSION['test'][$userAnswer]=array("var1" => 1, "var2" => 2);
	
	
				echo json_encode("test");
				
	}
}


?>

Sorry about the above post ^.   Had to go and edit timed out.  What Barand was saying was to return the session to the JQuery in json format since that is what your dataType is:

$test = $_SESSION['test'][$userAnswer];
echo json_encode($test);

Then JQuery will receive the value of $test as the data var in  

success: function(data) {

So basically just change your PHP to that and see what the result of the append is.

Edited by MDCode

That doesn't seem to work without defining $userAnswer as such. .. because I guess there's nothing in there display. But I got it to work on that point, thanks :)

$test = $_SESSION['test'][$userAnswer] = "string";
||
$test = $_SESSION['test'][$userAnswer] = array("one", "two");

Bah. I have such poor terminology. Sorry, I'm not even sure how to google this. What is the correct term for ['test']/[$userAnswer]? Are they indexes? Time to read up on arrays again :P

 

I still am unsure as to why the IF statement is not fireing. Any ideas?

Edited by 7blake
  • Solution

Is this what you are trying to do

 

blake.html

<!DOCTYPE HTML >
<html>
<head>
<meta name="author" content="Barand">
<meta name="creation-date" content="11/05/2014">
<title>Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
    $().ready(function() {
        $("#button").click(function() {
            var name = "test";
            $.get(
                "blake.php",
                {"name":name},
                function(data) {
                    $.each(data, function(k,v){
                        $("#click").append(k + " : " + v + "\n");
                    })
                    $("#click").append("--------------------\n");
                },
                "json"
            )
        })
        
        $("#clear").click(function() {
             $("#click").html("");
        }) 
    })
</script>
</head>
<body>
<textarea cols='20' rows='15' id='click'></textarea>
<input type="button" name="button" id="button" value="Click me">  
<input type="button" name="clear" id="clear" value="Clear">  
</body>
</html>

blake.php (called via ajax)

<?php
session_start();
if (isset($_GET['name'])) {
    $userAnswer = $_GET['name'];
    
    if (isset($_SESSION['test'][$userAnswer])) {
        $_SESSION['test'][$userAnswer]['var1']++;
    }
    else {
        $_SESSION['test'][$userAnswer] = array('var1'=>1, 'var2'=>2);
    }
    echo json_encode($_SESSION['test'][$userAnswer]);
}
else echo '';
          
?>

Wow thanks. Yes, that is generally what I was attempting to do.

 

You made more of a modification to the aJax than the PHP. I can mostly understand it, but not entirely.

In this case we're using a GET instead of POST, so I'll have to figure this out. But once the data is retrived, you started

 $.each(data, function(x, y) // In relation to  $array('var1'=>1, 'var2'=>2);

I'm not sure what the each means. The data is grabbed, so does the each isolate the key and value from the array, via x/y? Like "for each Value/Key in the array(represented by X/y) perform action?".

Thanks a bunch for helping to get it to work. Now I just have to understand it :P

 

As for the GET, I was following convention.

  • GET is for retrieving data
  • POST is for sending data for an update

The PHP returns the array

    array('var1'=>1, 'var2'=>2)

encoded as a JSON string

    data = {'var1':1,'var2':2}

 

Because the data type is specified as json it is decoded back to an array.

$.each(data, function(x, y)

is the jquery equivalent of PHPs

foreach ($data as $x => $y)
  • Like 1

Gotcha. PHP returns the data as an array via jSon, and using $.each(Data//(returned array, breaks it down into it's key/value via function variables)// function(x, y));

^^ poor writing but I think I get you. Is that the primary function of $.each? Or merely just an application of it?

 

$.each() function can be used to iterate over any collection, whether it is an object or an array.

Does this mean, for each click, the each function will iterate over every key and value in the given array target?  (sorry for the questions, it's quite rare to actually talk to someone who knows what they are doing )

Well, as it's going so far it's helped a great deal. I really appriciate the time :) Hopefully I'll start to understand the broader complexity of what I'm doing. But atleast I understand how to get this part working lol :) Thanks again. I'll probably be posting another deliema soon :S

Edited by 7blake
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.