javascripthtmlajax

Working with Ajax, PHP, and Javascript


I'm in no way, shape, or form anywhere near as close or experienced as most of you. However, my experience in PHP compared to Javascript is slightly better. So please excuse me, if my code seems mediocre or "newbie."

Anyways, I have a single page with a form with a simple input box and then two checkboxes. I'm working with ajax for the first time, and I was able to get my code to work, in a sense. In my PHP code, I have it run certain things depending on what checkbox is selected. However, with this ajax code (and/or PHP as well), when it executes my code it runs all of my code even if the checkbox is selected or not. I'm here asking if you see what I did wrong:

[index.php -> form code]

<form method="post" class="form-horizontal">
<fieldset>

<!-- Form Name -->
<legend>Enter the tweet URL below to begin using the service.</legend>


<div id="ajaxDiv" class="alert alert-success">We've successfully completed your request, check twitter now. Or, simply click <a href="<?php echo $_POST['url']; ?>">here</a>.</div>

<!-- Text input-->
<div class="control-group">
  <label class="control-label" for="url">Tweet URL</label>
  <div class="controls">
    <input id="url" name="url" type="text" style="height:43px; width:100%; font-size:18px;" placeholder="" class="input-xlarge" required="">
    <p class="help-block">The URL of the tweet we are favouriting or retweeting. <span style="font-size:15px;">Example: https://twitter.com/topIess/status/411632658683150336</span></p>
  </div>
</div>

<!-- Multiple Checkboxes -->
<div class="control-group">
  <label class="control-label" for="checkboxes">What would you like for that tweet?</label>
  <div class="controls"  required="required">
    <label class="checkbox" for="checkboxes-0">
      <input type="checkbox" style="margin-top:15px;" name="retweet" id="checkboxes-0" value="Retweet">
      Retweets
    </label>
    <label class="checkbox" for="checkboxes-1">
      <input type="checkbox" name="favorite" style="margin-top:15px;" id="checkboxes-1" value="Favourite">
      Favourites
    </label>
  </div>
</div>

<!-- Button -->
<div class="control-group">
  <label class="control-label" for="submit"></label>
      <div class="controls">
    <button type="submit" onclick="postStuff();" class="btn btn-inverse">Start Process...    </button>
      </div>
</div>

</fieldset>
</form>
<div id="status"></div>

[index.php -> javascript]

<script>
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var fn = document.getElementById("url").value;
var ln = document.getElementById("checkboxes-0").value;
var url = "handle1.php";
var ln1 = document.getElementById("checkboxes-1").value;
var vars = "url="+fn+"&retweet="+ln+"&favorite="+ln1;
hr.open("POST", url+"?x="+nn+"&y="+nn1, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
    document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "Processing...";
}
</script>

[handle1.php -> my PHP code]

<?php
/**
 * @file
 * User has successfully authenticated with Twitter. Access tokens saved to session and DB.
 */

require_once('twitteroauth/twitteroauth.php');
$con=mysqli_connect("host","user","","twtid");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM twitter");
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
        $connection[$row['id']] = new TwitterOAuth('ZG808c0pad0ar7wpgYPmA', 'BWHnOag1aWQtoYRBH5OtsI9m9Ghr3pTuMBo6z4ZNNP8', $row['key'], $row['secret']);
}
/* Create a TwitterOauth object with consumer/user tokens. */
/* $content = $access_token['oauth_token']. " " . $access_token['oauth_token_secret']; */
/* $content = $connection->get("account/verify_credentials"); */

$url1 = parse_url($_POST['url'], PHP_URL_PATH);
$url = explode("/", $url1);

 /* If method is set change API call made. Test is called by default. */
$method = 'statuses/retweet/'.$url[3];
$amt = 18;
$sub = rand(1,2);
$amt1 = $amt-$sub-1;
for ($x=1; $x<=$amt; $x++)
   {
if($_POST['retweet'] == "Retweet"){
$content = twitteroauth_row($method, $connection[$x]->post($method), $connection[$x]->http_code);
}
if($x == $amt) {
$done = "yes";
}
}

for ($x1=1; $x1<=$amt1; $x1++)
   {
if($_POST['favorite'] == "Favourite"){
$content = $connection[$x1]->post('favorites/create', array('id' => $url[3]));  
}
}

Solution

  • in your javascript you are posting the value property of your checkboxes, that is the wrong one to use in this situation (as the value of a checkbox is always the same). instead you should be checking if the checked property is true, as that defines if a checkbox is checked or not.