5

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

0

2 Answers 2

2

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
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

And is it correct to use things like that: " $('some text box').writeText(data); "?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.