Question

So I'm trying to get PHP to send the promo code back through ajax; why is it not receiving it?

I have tried a couple different methods but none seem to be working

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script type="text/javascript">

function submit() {
 $.ajax({
     url: 'index.php',
     type: POST,
     data: $('form.ajax').serialize(),
     success: function(response) {
         alert(response);
     }
 });
}

</script>

HTML:

  <select name="app">
    <option value="balloon">Balloon Doop</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
  </select>


<input type="submit" id="submit1" value="submit"  onclick="submit()" data-icon="info" />

PHP Code

<?php

$nothing = "";
$option = "balloon";
if ($_POST['app'] == $option) {

$promo = file('balloon.txt');
echo ($promo[0]);
$data = file_get_contents("balloon.txt");
$newdata = str_replace($promo[0], $nothing, $data);
file_put_contents("balloon.txt", $newdata);
} else {
    echo ("Not available");
}

?>
Was it helpful?

Solution

You did not cancel the default submit action of the form so the page refreshes.

function submit(e) {
    e.preventDefault();
    $.ajax({
        url: 'index.php',
        type: POST,
        data: $('form.ajax').serialize(),
        success: function(response) {
            alert(response);
        }
    });
}

//needs to be called on document ready
$('form.ajax').on("submit", submit);

If you insist on doing it the way you have it coded.

Add return false; at the function and onclick="return submit()"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top