user2444298
user2444298

Reputation: 37

POST data through AJAX and set as variable

I am not very familiar with javascript especialy when it comes to functions and ajax. I am trying to get some data from another php page and have it put into a div. When I ever i load the page nothing comes up.

My ultimate goal is to get the data into a php or javascript but first need to figure out how to get / receive data.

here is the php code of feedupdate.php

    <?php
require "dbc.php";

    $function = $_POST['function'];

    switch($function)
    case('initiate'):
    $search="SELECT * FROM Feedtest ORDER BY id DESC";
    $request = mysql_query($search);
    $mostrecent= mysql_fetch_array($request);
    $mostrecentid = $mostrecent['id']
    echo json_encode($mostrecentid);
     break; 


    case('update'):
    $search="SELECT * FROM Feedtest ORDER BY id DESC";
    $request = mysql_query($search);
    $update= mysql_fetch_array($request);
    $updateid = $update['id'];
    echo json_encode($updateid);
     break;          
?>

here is the ajax

<div id="datacheck"></div>

  <script>
  $(document).ready(function()  {
     $.ajax({
          type: 'POST'
          url: 'feedupdate.php'
          data: {'function': 'initiate',},
          datatype: "json"
          success: function(msg) {
              $('#datacheck').html(msg);
          }

        });
  }); // document ready

Upvotes: 2

Views: 316

Answers (3)

Brombomb
Brombomb

Reputation: 7076

In your AJAX you are passing data back to the PHP script:

data: {'function': 'getState'},

But in your php script you don't have a case statement that matches getState you only have initiate and update. So you can either write code to support getState or you can pass in either initiate or update to the data parameter.

Also watch out for trailing comma's. They won't work in IE. You should remove the comma after 'getState' on the data line.

You are also missing a comma after type, url, and datatype

  $(document).ready(function()  {
     $.ajax({
          type: 'POST', // add comma
          url: 'feedupdate.php', //add comma
          data: {'function': 'initiate'}, // remove comma
          dataType: "json", // add comma
          success: function(msg) {
              $('#datacheck').html(msg);
          }

        });
  });

Alos you can look at using the shorthand method $.post docs

Upvotes: 1

Tito
Tito

Reputation: 9044

There is a typo in the ajax jquery code

success: fuction(msg) {...

it should be spelled "function".This typo might be the problem , plus there should be switch case for

getState

in your php code.

Upvotes: 2

Noor
Noor

Reputation: 1391

You are passing getState in data from JavaScript while in PHP you do not have a similar case to match in switch statement. Instead of getState pass update or initiate.

If you just want to check either AJAX call is working or not write

echo "something message"; exit();

Upvotes: 1

Related Questions