user3057706
user3057706

Reputation: 73

Sent AJAX to PHP, update DB, get new JSON

I have the following code:

$(document).ready(function() {
$.getJSON('model.php',function(data) {
    $('h1').append(data['event']);
    $('.img-circle').attr('src',data['image'])
    $('a').attr('href',data['url']);
    var eventname = data['event'];

$('.starter-template').on("swipeleft",function() {
    var events = {'event': eventname};
    $.ajax({
        type: "POST",
        url: "getchoices.php",
        dataType: 'json',
        data: {event: JSON.stringify(eventname) }
    });
})
})
})

It takes a swipe, and sends that data to the database. The change in the database then updates the model.php JSON, which I would like to then read the new values into the document, but I am stuck on how to do this. Originally I repeated the original section like so:

$(document).ready(function() {
$.getJSON('model.php',function(data) {
    $('h1').append(data['event']);
    $('.img-circle').attr('src',data['image'])
    $('a').attr('href',data['url']);
    var eventname = data['event'];

$('.starter-template').on("swipeleft",function() {
    var events = {'event': eventname};
    $.ajax({
        type: "POST",
        url: "getchoices.php",
        dataType: 'json',
        data: {event: JSON.stringify(eventname) }
    });
$.getJSON('model.php',function(data) {
    $('h1').append(data['event']);
    $('.img-circle').attr('src',data['image'])
    $('a').attr('href',data['url']);
    var eventname = data['event'];
    })  
})
})
})

But this seems to always send the same data['event'] to the PHP, rather than changing each time.

Upvotes: 0

Views: 282

Answers (1)

apoq
apoq

Reputation: 1454

You assign eventname on every swipe like this:

$.getJSON('model.php',function(data) {
    $('h1').append(data['event']);
    $('.img-circle').attr('src',data['image'])
    $('a').attr('href',data['url']);
    var eventname = data['event'];
    }) 

The thing is that you do not alter your global eventname variable which is defined above. Changing your code (2nd $.getJSON) to following should do the job:

$.getJSON('model.php',function(data) {
     ...
      eventname = data['event']; // omit var
    }) 

Upvotes: 1

Related Questions