0

I am trying to run a javascript function once a user click on a button. I am echoing the script, but nothing is happening.

button code in .php file:
case 'create':
    echo '<script type="text/javascript">clearform();</script>';
break;

Javascript file:
function clearform()
{
    document.getElementById("serviceMileage").value="";  
}

It only displays this in the console:
<script type="text/javascript">clearform();</script>

I want to clear an input field once a user clicks on the button

Abre Pio
  • 1
  • 2
  • 1
    Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – GrumpyCrouton Oct 14 '19 at 19:42
  • Just add `clearform();` to an `onclick` attribute on your button. `` - You are going to have a hard time making PHP run a JavaScript function on your page. – GrumpyCrouton Oct 14 '19 at 19:43
  • I know I can do that, but I first want to execute more code in the button code and once a condition is met, I want to clear the input field – Abre Pio Oct 14 '19 at 19:45
  • How do you submit the form? It's ajax or regular form submit? – Felippe Duarte Oct 14 '19 at 19:51
  • regular form submit
    – Abre Pio Oct 14 '19 at 19:54
  • How are you echoing the script onclick? Ajax call? – epascarello Oct 14 '19 at 19:56
  • Yes sorry ajax call, my bad – Abre Pio Oct 14 '19 at 19:57
  • 2
    It's better to return some value from the backend, like `{"error":"1"}`. Then in the function where you process the return you can check `if (data.error ==1) clearform();` – Felippe Duarte Oct 14 '19 at 19:59
  • Okay thanks will add that. Where do you think is my problem? – Abre Pio Oct 14 '19 at 20:01
  • Are you writing the response back to the page after it comes back from ajax? – Rasclatt Oct 14 '19 at 20:09
  • Sorry I am new to this. Can you please give me more detail to your question? – Abre Pio Oct 14 '19 at 20:13
  • Well, when you receive the response back from your php, it's essentially passive data until you do something with it. If you took the `` from the php and put it back into your current page, it likely would work. So you would use something like `document.getElementById('confirmation').innerHTML = response;` and it would place that script into an empty `div` like `
    ` which would already be on your page somewhere.
    – Rasclatt Oct 14 '19 at 23:25
  • @Rasclatt Thank you. Could you maybe show me how to this in my code. I would really appreciate it – Abre Pio Oct 14 '19 at 23:42
  • You don't have enough code to know what you are actually doing that is not working. I would need to see the relevant ajax and html. – Rasclatt Oct 14 '19 at 23:53

0 Answers0