-2

I have the following problem, the following script sends a keyword a PHP file hosted in another domain (I already added the CROS headers), this PHP returns me some "echos of different variables" (title, thumbnail, url, etc.) And it works but randomly returns me "Undefined variables".

The first thing was to add an if (isset ()) to my variables in PHP and the error does not appear anymore but the results returned by my searches are much smaller (Before adding it averaged 10 to 20 results, Now I get 5 results).

Can this be a problem with my script?

My form.php

<form method="POST" action="" id="form-busqueda">
<input type="text" name="keyword">
<button id="search" name="search">Search</search>
<div id="results"></div>
            <script>
            jQuery(function($){
                var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
                $('[id^="form-busqueda"]').on('submit', function(e) {
                    e.preventDefault();
                    $.ajax({
                        type : 'POST',
                        url  : 'http://localhost/ladoserver/script.php',
                        data : $(this).serialize(),
                        beforeSend: function(){
                            $('#results').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
                        }
                    }).done(function(data) {
                        $('#results').html(data);
                    });
                });
            });
        </script>
</form>

My script.php (dlPage is a function that create cURL connection):

<?php
if (isset($_POST['keyword'])) {
    $search = $_POST['keyword'];
    $html = dlPage("http://example.com/" . $search);
    //where I search and get with simple_html_dom example:
    $video = $videos->find('div.example2>a', 0);
    $title = $video->innertext;
    $url = $video->attr['href'];
    $id = $video->attr['id'];
    $thumbnail = $video->find('div.thumb', 0)->innertext;
    echo $title;
    echo $url;
    echo $id;
    echo $thumbnail[0];
}
?>

I've updated my code, I didn't put all the code because I thought that it isn't relevant, my script.php works fine with pure PHP. The problem appear when I use AJAX.

I'm getting the following error:

Notice: Undefined variable: title in C:\xampp\htdocs\webs\ladoserver\script.php on line 13

Notice: Undefined variable: title in C:\xampp\htdocs\webs\ladoserver\script.php on line 13

Notice: Undefined variable: url in C:\xampp\htdocs\webs\ladoserver\script.php on line 14

Community
  • 1
  • 1
Kokox
  • 519
  • 1
  • 9
  • 24
  • You need to show us how you define those variables in your PHP-file, since that's were the issue seems to be. We need to see _all_ relevant code. – M. Eriksson Jun 15 '17 at 18:55
  • ...and if the result gets smaller when you're using `isset()` it simply means that you're not setting all the variables. – M. Eriksson Jun 15 '17 at 18:57
  • Please read: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) and also [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) – M. Eriksson Jun 15 '17 at 19:02
  • Ok, Im sry, I've updated my question with relevant information. Im using simple_html_dom – Kokox Jun 15 '17 at 19:21
  • How are you setting the `$url`, `$id` and `$thumbnail` variables? The code above just seem to check if some arbitrary variables are set, and if all of them are, you echo them, otherwise not. (unless you _still_ have some code you haven't shown us, you shouldn't get any results at all). – M. Eriksson Jun 15 '17 at 19:26
  • Ok, I've updated my information. – Kokox Jun 15 '17 at 19:41
  • @JorgeAguilar Thanks for posting the full script.php. The problem with the exact code that you've posted, is that your `foreach` is defining `$videos` (plural), but you're setting your $title/etc variables to a value from `$video` (singular). Because $video is not set (instead, $videos is), you will get that warning about an undefined variable. If this is not actually your problem, can you update your post to include __which__ variables are undefined in your warning messages? – RToyo Jun 15 '17 at 20:28
  • I've updated my code. $video variable (singular) search inside $videos. When I work with pure PHP I not get any error but with AJAX I get undefined variable. I can't understand why. I got 15 results fine but some warings. It can appear randomnly. – Kokox Jun 15 '17 at 20:41
  • Okay, guys first I apologize for any inconvenience I may have caused. I'm still learning how to use stackoverflow. I think I found the solution to the problem (although I do not yet understand why I got these errors). Instead of using "isset" I used "!empty" and apparently no longer returns that error and the number of results is the same. I hope this error does not reappear. – Kokox Jun 15 '17 at 21:06
  • 1
    @JorgeAguilar Sorry, I missed the part where $video gets defined. `isset` and `empty` behave similarly, except that isset checks if a variable is declared, while empty checks if there is a value assigned to the variable. Do you understand why the number of results was lesser when you were using `isset`? Also, out of curiosity, have you tried just setting your $url/$id/$thumbnail to blank values, as Magnus suggested above, and like I suggested in my answer below? – RToyo Jun 15 '17 at 22:50
  • Yes I tried and work well, do you know why I got this error only with ajax? Or I had luck when I tested with pure PHP. – Kokox Jun 15 '17 at 23:13
  • @JorgeAguilar Glad it helped. As for why it only happens with ajax: I don't think that ajax is the cause of the error. What is probably happening, is that the value you're looking for in $video doesn't exist. For example, `$title` is one of the variables that you get this warning about, so I would suspect that `$video->innertext` is blank when your script tries to pull that from the URL. When you tested "just your script" (as opposed to making an ajax call) were you pointing your script to the exact same `$_POST['keyword']` as your ajax call? – RToyo Jun 16 '17 at 15:23

2 Answers2

1

The undefined variable is coming from your PHP file (/ladoserver/script.php).

What generates the variables being returned? The most common "cause" of this, is by only setting the variables within a block of code that might not be executed (eg within an if block, or in a loop that iterates 0 times)

You could get around the error (assuming you're okay with blank values) by defining each of the variables at the top of your script.

<?php
$title = "";
$thumbnail = "";
$url = "";
$id = "";
?>

Edit: @snip1377 reminded me that you can also just use isset at the end of your script before the output as well.

Here's some sample code for your $thumbnail variable, which you could apply to all your variables being returned

<?php
if (isset($thumbnail))
{
    echo $thumbnail;
}
else
{
    echo "";
}
?>

Alternativaely, you can use a ternary operator:

<?php
    echo (isset($thumbnail)) ? $thumbnail : '';
?>

Edit again: just to illustrate what I mean about how the variables might not get defined within a script, here is an example that could cause that undefined error:

<?php
if ($_POST['value'] == 1)
{
    // This will never be reached unless $_POST['value'] is exactly 1
    $return_val = 1;
}

echo $return_val;
?>

This will give the undefined warning, if $_POST['value'] is anything other than 1.

Similarly, if $_POST['value'] were 0 in the following code, it would have that undefined warning as well:

<?php
for ($i=0; $i<$_POST['value']; $i++)
{
    // This will never be reached if $_POST['value'] is less than 1
    $return_val = $i;
}
echo $return_val;
?>

In the examples above, you can simply define $return_val at the top of the script, and you won't get the error anymore.

RToyo
  • 2,877
  • 1
  • 15
  • 22
  • This is a comment and not a real solution to the problem since we simply don't know what's causing it (since the OP hasn't actually showed us that yet). At best, this _might_ help with the symptom, but it ignores the cause. – M. Eriksson Jun 15 '17 at 18:58
  • @MagnusEriksson I may have phrased it like a comment, but it includes a solution. Possibly the only solution, if the OP's script has cases where it will never set one or more of these variables. – RToyo Jun 15 '17 at 19:00
  • That's my point. We need more info before we can try to solve it. Right now, we're all just stabbing in the dark. – M. Eriksson Jun 15 '17 at 19:01
  • You are just check.but we need a way and the way is just '$_POST['value']'. Other thigs are not needed :) – Omid Reza Heidari Jun 15 '17 at 19:09
  • @MagnusEriksson Fair enough. But there's basically two causes of this problem: The first and most common is if the variable is not defined in the first place. The second most common is if the variable is defined, and then `unset`. I guess a third option would be if the OP is referencing the wrong variable, but that's unlikely since there are actual results returned sometimes. I posted this as an answer rather than a comment because OP's problem is probably caused by the first reason - referencing a variable that has not been defined. – RToyo Jun 15 '17 at 19:10
  • @snip1377 I may have missed something in the original question, but how do you know the OP is trying to access these variables from $_POST? It seems very unlikely that the OP is just returning $_POST values, based on what was described. – RToyo Jun 15 '17 at 19:14
  • @snip1377 The OP's issue seems to be when he tries to use an undefined variable. Not when he's trying to access an undefined index. (two totally different error messages). – M. Eriksson Jun 15 '17 at 19:15
  • The op is sure to send data .and he dont want to check.op can check with other thins too!!! – Omid Reza Heidari Jun 15 '17 at 19:15
  • Op can check like this 'if isset($_POST){}' . no need to have a 'for(){}' !!!!!!! – Omid Reza Heidari Jun 15 '17 at 19:19
  • @snip1377 Ah, I see what you mean now. Those last two code snippets were just examples of what will not work. The `isset` check is all that is needed. But you've reminded me that I should improve the "answer" to include an isset example. – RToyo Jun 15 '17 at 19:20
  • .if you like and if you think my answer is correct please vote it up.i vote your answer – Omid Reza Heidari Jun 15 '17 at 19:22
0

You send this data as a post method.you shuld echo them with $_post['name'] but you just echo $name

Use this in script.php :

<?php 
    echo $_POST['title'];
    echo $_POST['thumbnail'];
    echo $_POST['url'];
?>
Ivan
  • 34,531
  • 8
  • 55
  • 100
Omid Reza Heidari
  • 658
  • 12
  • 27