Kyle Heier
Kyle Heier

Reputation: 15

Update variable using $.ajax on .click

EDIT: The question has more to do with altering the variable (valueA) than anything. I am already getting the desired load result using the script below. I am trying to attach something to the script that will ultimately alter valueA once clicked.

I am designing multiple pages that will load into a main content div on click using .load

index.php

//Setting default value

$valueA = 5;

//Created separate div to allow me to monitor the variable and changes    

<div><?php echo $valueA; ?></div>

//Loading first page into div

<div id=main_content>

<?php include 'page1.php'; ?>    

</div>

Included in page1.php is a button that will load the page assigned to it.

page1.php

<button id="button1">Click Me!</button>

<script>
 $(document).ready(function(){
   $('#button1').click(function(){
     $('#main_content').load('page2.php').hide().fadeIn('slow');
     $.ajax({
        type: 'POST',
        url: 'index.php',
        success: $valueA += 5,
     });
  });
})

Upon clicking, page2.php will load, but the value will remain 5. I am trying to figure out how to add the 5 using the ajax script to the valueA. Ultimately, the new page would load, and the value would increase to 10.

Upvotes: 1

Views: 1788

Answers (1)

mhodges
mhodges

Reputation: 11116

The incrementing of your php variable has to be done in a php script, not javascript. Javascript inherently knows nothing about your php, and vis-versa.

The other thing to mention is that the success property on the $.ajax object is a function, so you should define it as such. See jQuery Documentation for full details on $.ajax

$.ajax({
  ...
  ...
  success: function () { ... }
});

Edit

After clarification, here is an updated, more thorough example.

HTML

<div id="valueAContainer"><?php echo $valueA; ?></div>

jQuery

$.ajax({
  url: "yourphpscript.php",
  method: "GET" (or post, whatever is applicable),
  data: { valueA: $("#valueAContainer").text() },
  success: function (data) {
     $("#valueAContainer").text(data);
  }
});

PHP

// get valueA variable from request
$oldValue = $_GET['valueA'];
// Do whatever you want to it - increment, save to DB, etc.
$updatedValue = $oldValue + 5;
// Return updatedValue to javascript
echo $updatedValue

Upvotes: 1

Related Questions