0

I make an ajax call to a server and the server returns javascript and jquery code such as

$('someclass').html('<form id='billform'>......</>');
$('#billform').submit();

How do I execute this on the client side?

AshanPerera
  • 596
  • 1
  • 7
  • 18
  • `$('#billform').submit();` hope this is the problem and the use `id="billform"` – Sasikumar Sep 22 '16 at 05:59
  • Technically you can run any arbitrary code using `eval` in practice, this is a really bad idea in most situations and suggests that you are probably not doing something correctly. – VLAZ Sep 22 '16 at 06:00

4 Answers4

1

You could put that code inside a script tag and append it to the body This procedure is described best here: https://stackoverflow.com/a/611016/4202031

However, it is not recommendet to simply execute some javascript which is loaded via ajax. I would recommend to work with events that would trigger this code which is on your page already.

$.get('/sumUrl', function(data) {
  switch(data.action) {
    case 'event1':
      //do sth.
      break
    case 'event2':
      // do sth. else
      break
  }
})
Community
  • 1
  • 1
n1ru4l
  • 488
  • 1
  • 10
  • 29
1

You can include the code as a function in your static page, then call the function from the returned ajax call. A small example:

on your static page:

function submitmyform(formcontents)
{
   $("someclass").html(formcontents);
   $("#billform").submit();
}

on your ajax success method:

$.ajax({
    url: "/getform",
    method: "POST",
    data: $(".myform").serialize(),
    success: function(data){
        submitmyform(data);
    }
});
Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
0

You have to put your id in quotation marks, and as id instead $ use #

$('someclass').html('<form id="billform"></>');
$('#billform').submit();
Bartłomiej Gładys
  • 4,525
  • 1
  • 14
  • 24
0

You can use eval function from javascript to execute the scritp which are string e.g.

eval('alert("Hello!")');

I your case

eval('$(".someclass").html("<form id="billform">......</>")');
eval('$("#billform").submit()');
Hemant D
  • 192
  • 5