Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax passing data to php script

Tags:

jquery

ajax

php

I am trying to send data to my PHP script to handle some stuff and generate some items.

$.ajax({  
    type: "POST",  
    url: "test.php", 
    data: "album="+ this.title,
    success: function(response) {
        content.html(response);
    }
});

In my PHP file I try to retrieve the album name. Though when I validate it, I created an alert to show what the albumname is I get nothing, I try to get the album name by $albumname = $_GET['album'];

Though it will say undefined :/

like image 388
NeedHelp Avatar asked Jul 21 '11 20:07

NeedHelp


People also ask

How do I pass a value to a PHP script using AJAX?

php $userAnswer = $_POST['name']; $sql="SELECT * FROM <tablename> where color='". $userAnswer. "'" ; $result=mysql_query($sql); $row=mysql_fetch_array($result); // for first row only and suppose table having data echo json_encode($row); // pass array in json_encode ?>

Can AJAX be used with PHP?

Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.


2 Answers

You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:

$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: { album: this.title },
    success: function(response) {
        content.html(response);
    }
});

or in its shorter form:

$.post('test.php', { album: this.title }, function() {
    content.html(response);
});

and if you wanted to use a GET request:

$.ajax({  
    type: 'GET',
    url: 'test.php', 
    data: { album: this.title },
    success: function(response) {
        content.html(response);
    }
});

or in its shorter form:

$.get('test.php', { album: this.title }, function() {
    content.html(response);
});

and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.

like image 128
Darin Dimitrov Avatar answered Oct 10 '22 12:10

Darin Dimitrov


You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {
        content.html(response);
    }
});
like image 24
kaushik Avatar answered Oct 10 '22 13:10

kaushik