user1197457
user1197457

Reputation: 59

How do I pass value of ajax variable to php script in this example?

Notice this post:

Auto-refresh echo

One solution was to do this:

down vote

$(function(){
    setInterval(function(){ 
         $("#refresh").load("user_count.php");
    }, 10000);
});

All this does is it talks to user_count.php to GET data. The .php file then sends that back to be printed out on the page. But say I wanted to also send data to the .php file for it to do stuff with. So like I defined two variables in the javascript code, then wanted the value of each variable to be sent to that php script for processing. What's the syntax for that?

Upvotes: 0

Views: 1176

Answers (3)

JasonWyatt
JasonWyatt

Reputation: 5303

A really simple solution to this would be to use $.param() and append it onto your URL:

$(function(){
    setInterval(function(){
        $('#refresh').load('user_count.php?'+ $.param({
            yourFirstVariable: 'foo', 
            anotherVariable: 'bar'
        }));
    }, 10000);
});

Where yourFirstVariable and anotherVariable are parameters for your php script.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

You can add it to the URL:

$("#refresh").load("user_count.php?something="+valueA+"&somethingElse="+valueB);

BTW - these are JavaScript variables, not "AJAX variables".

Upvotes: 1

Grim...
Grim...

Reputation: 16953

You can use .ajax(): http://jqapi.com/#p=jQuery.ajax

$.ajax({
  url: "mypage.php",
  data: {
     foo: 1,
     bar: "blah"
  },
  context: document.body,
  success: function(ret){
    alert("Anything your php script outputs will be returned to the ret variable");
    alert(ret);
  }
});

You php file will then be able to use $_POST['foo'] and $_POST['bar'].

Upvotes: 0

Related Questions