James Hill
James Hill

Reputation: 75

jQuery $.ajax() with PHP

I'm trying to use jQuery $.ajax() but I'm facing some difficulties.

Here's the textbox field that I want to use for POST:

<input name="url" class="url" type="text" >

Here's the code:

$.ajax({
        type: "post",
        url: "file.php",
        data: $(this).serialize(),
        success: function(data) { ...............

Now this is the file.php:

<?php
if( $_REQUEST['url'] )
{

   $url = $_REQUEST['url'];
   $url = file_get_contents($url);  
   // I would need now to return something here but not sure how??!!
}
?>

Now, my question is, how to return variables in this PHP code and use them in my code above, I mean in the success part of $.ajax(). Also if I want to perform some additional stuff on the $url variable, how to do it? How to return them? :/

Upvotes: 5

Views: 6588

Answers (2)

Miguel Bot&#243;n
Miguel Bot&#243;n

Reputation: 766

If you want to return some variables/fields, the best way would be to echo a JSON string. Here is a small example:

PHP Code:

<?php
if( $_REQUEST['url'] )
{

   $url = $_REQUEST['url'];
   $url = file_get_contents($url);  

   $result['var1'] = 'something';
   $result['var2'] = 500;

   echo json_encode($result);
}
?>

JS Code:

$.ajax({
    type: "post",
    url: "file.php",
    data: $(this).serialize(),
    dataType: 'json', // maybe not needed? I do not know if jQuery autodetects it
    success: function(data) {
        // here you can use data.var1 and data.var2 to read the fields
    }
});

Upvotes: 2

Halcyon
Halcyon

Reputation: 57709

You just print/echo your 'return' value.

file.php

<?php
if( $_REQUEST['url'] )
{

   $url = $_REQUEST['url'];
   $url = file_get_contents($url);  
   // I would need now to return something here but not sure how??!!
   echo "something";
}
?>

Then in your JS:

$.ajax({
    type: "post",
    url: "file.php",
    data: $(this).serialize(),
    success: function(data) {
        console.log(data); // "something"
    }
});

As a side note. Your script looks like it accepts any URL and fetches it. It is possible to abuse scripts like that. Make sure you are aware that.

Upvotes: 1

Related Questions