Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.ajax() with PHP

Tags:

jquery

ajax

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? :/

like image 382
James Hill Avatar asked Oct 22 '22 08:10

James Hill


2 Answers

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
    }
});
like image 104
Miguel Botón Avatar answered Oct 27 '22 16:10

Miguel Botón


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.

like image 27
Halcyon Avatar answered Oct 27 '22 17:10

Halcyon