2

Let's say I'm currently browsing mypage.html, which in its header has a link to the following js file:

<script language="JavaScript" type="text/javascript" src="jsfile.js"></script>

In jsfile.js, there's a function keyup() that is executed when the user types something into #searchbar, whose value is then stored in search = $(#searchbar).val();

I then pass this value on to search.php as follows:

$.post( "search.php", { searchval: search }, function(sentdata){
    console.log(sentdata);
});

where the content of search.php reads:

<?php
if(isset($_POST[searchval])){
        $search = $_POST[searchval];
    echo "input value is $search";
    echo "<script type='text/javascript'> alert('its working') </script> ";
}
?>

However, instead of an alert pop up (or anything else that would normally be executed in JS), the second echo simply prints " alert('its working') " into the console. How can I modify search.php to allow it to inject actual js into myfile.html? Note that I've also tried wrapping the js code in tag.

Related question: why is it that when I omit console.log(sentdata), search.php does no longer echo anything into the console?

2

2 Answers 2

1

How I can modify search.php to allow it to inject actual js in myfile.html?

First of all, you need to modify your javascript file:

$.post( "search.php", { searchval: search }, function(sentdata){
    eval(sentdata);
});

And no need for javascript tags, just echo a valid Javascript code:

if(isset($_POST[searchval])){
    echo "alert('its working');";
}

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/eval

Sign up to request clarification or add additional context in comments.

2 Comments

despite the provided explanation, I don't quite see why that first modification was necessary. isn't the purpose of function(sentdata) simply to return something on successful execution of $.post?
@ephemeral You get a string from server. Javascript doesn't know whether it's a code or not. You must execute it, eval is used for this.
0

you can do this

$.post( "search.php", { searchval: search }, function(data){
    alert(data);  // this will alert the data which will print on search.php
});

and in the php file echo the data you want to print like

if(isset($_POST[searchval])){
    echo 'its working. i got'.$_POST[searchval];
}

Comments

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.