Evaluating scripts in an ajax response - javascript

I have the following code:
$.ajax({
type: 'POST',
url: urlData,
data: { OwnerId: ownerIdData, Text: textData },
success: function (data) {
$('#post-container').prepend(data);
},
error: function () {
}
});
Now I want to eval the scripts contained in the variable data in the success function.
How I do that ?
Thanks in advance.
EDIT
I have the following form:
<form class="new-post-form">
<textarea id="post-creation-text-input" name="Text" rows="10"> Write something ... </textarea>
<input type="hidden" value="#Model.OwnerId" id="post-creation-id-input"/>
<input type="submit" value="Post" id="post-creation-submit-input" />
<script type="text/javascript">
$('#post-creation-submit-input').click(function (event) {
event.preventDefault();
var textData = $('#post-creation-text-input').val();
var ownerIdData = $('#post-creation-id-input').val();
var urlData = '#Url.Action("Create", "Posts")';
$.ajax({
type: 'POST',
url: urlData,
data: { OwnerId: ownerIdData, Text: textData },
success: function (data) {
$('#post-container').prepend(data);
});
},
error: function () {
}
});
});
</script>
</form>
Now the ajax response is the following view:
#using Facebook.Presentation.Web.Utils
#model Facebook.Presentation.Web.ViewModels.Posts.PostViewModel
<div class="post" id ="last-post">
<h3>#Html.UserName(Model.Author)</h3>
<br/>
<div>
#Html.DisplayFor(model => model.Text)
</div>
<br/>
#{
Html.RenderPartial("_CommentsPartial", Model.Comments, new ViewDataDictionary { { "ActionName", "Comment" }, { "ControllerName", "Posts" } });
}
</div>
This response also contains scripts that must be evaluated.
Thanks again.

Use jQuery.getScript() function. Documentation: http://api.jquery.com/jQuery.getScript/

Related

I am trying to send data to my PHP page from html page using ajax POST method but it give error ,Notice: Undefined index:

<head>
<title>Document</title>
<script>
$(document).ready(function () {
$("#search").on("keyup", function () {
var search_term = $(this).val();
console.log('value--', search_term)
$.ajax({
url: "ajax-live-search.php",
type: "POST",
data: { search: search_term },
success: function (ajaxresult) {
$("table-data").html(ajaxresult);
}
});
});
});
</script>
</head>
<body>
<div id="search-bar">
<label>Search</label>
<input type="text" id="search" autocomplete="off">
</div>
<div id="table-data">
</div>
</body>
PHP page
$search_input = $_POST["search"];
echo $search_input;
error
Notice: Undefined index: search in C:\xampp\htdocs\ajax\ajax-live-search.php on line 3
Change "type" to "method" as below:
$.ajax({
url: "ajax-live-search.php",
method: "POST",
data: { search: search_term },
success: function (ajaxresult) {
$("table-data").html(ajaxresult);
}
});

Django getlist getting null

Hello guys im currently learning on how to send data from HTML to Django backend using Ajax.
I have this HTML
<div class="form-row">
<input type="checkbox" name="car-checkbox[]" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox[]" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox[]" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
and then to send the data i use this code (Ajax)
$('#submit-car').click(function () {
const data = {user_id: user_id}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
and then on the Django side i try to get the checked checkbox
def insert_car_to_db(self, request):
cars = request.POST.getlist('car-checkbox[]')
print(cars)
Weirdly enough when i try to get the checked data, i keep getting [] value,
where did i miss ? am i misunderstand something?
P.S
i followed this post
How to get array of values from checkbox form Django
$('#submit-car').click(function () {
const car_checkbox = [];
const user_id = "Some test UserId";
const csrftoken = "Provided CSRF TOKEN";
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
console.log(data);
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<input type="checkbox" name="car-checkbox" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
So where you are sending the checkbox array value to backend /submit-car/ ?
what is user_id in your click evennt?
As you are using jquery so
$('#submit-car').click(function () {
const car_checkbox = [];
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});

How to pass Multiple input array element values

As you can see I have a for loop with Multiple ID and I want get the value of IDs and pass them to my controller, how can I achieve this ?
<form id="UserEdit">
#for (int i = 0; i < Model.Rights.Count; i++)
{
#Html.HiddenFor(m => m.Rights[i].ID)
}
<input id="BtnEditUserJS" onclick="PostFormUserEdit();" type="submit" value="Edit">
</form>
Generated HTML:
<input id="Rights_0__ID" name="Rights[0].ID" type="hidden" value="31">
<input id="Rights_1__ID" name="Rights[1].ID" type="hidden" value="32">
JavaScript:
function PostFormUserEdit() {
$.ajax({
type: 'POST',
url: '#Url.Action("EditUser")',
dataType: 'json',
data: ,
success: function (run) {
console.log('Ok');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
Controller:
[HttpPost]
public JsonResult EditUser(int[] RightId)
{
var rights = db.Rights.Where(b => RightId.Contains(b.Id)).ToList();
//do something with rights
}
You can achieve it this way :
function PostFormUserEdit()
{
var arr = [];
$("#UserEdit input[type='hidden']").each(function (index, obj) {
arr.push(obj.val());
});
$.ajax({
type: 'POST',
url: '#Url.Action("EditUser")',
dataType: 'json',
data: arr , // or you can try data: JSON.stringify(arr)
success: function (run) {
console.log('Ok');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}

Grails - Ajax submit not working?

i'm trying to update a div when a form is submited, but it seems that I am forgetting something.
here's my html:
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<meta name="layout" content="main" />
<g:javascript library="jquery"/>
</head>
<body>
<form id="formEntrada">
<label>Evento: </label>
<g:select from="${listaEvento}" name="evento_id" optionValue="nome" optionKey="id" noSelection="${['':'Selecione...']}" required="true"/><br><br>
<label>Participante: </label>
<input type="text" id="codigo" onkeyup="pesquisa(event,'/eventoEntrada/pesquisar')" value="${participante?.id}" size="15px"/>&nbsp&nbsp
<input type="text" value="${participante?.nome}" size="50px" disabled required="true">
<input type="submit" value="Adicionar">
</form>
<div id="divList">
<g:render template="list"/>
</div>
</body>
</html>
here's my JavaScript
$(document).ready(function () {
$('#formEntrada').submit(function () {
alert("evento_id+participante_id");
var evento_id = document.getElementById("evento_id").value;
var participante_id = document.getElementById("participante_id").value;
$.ajax({
type: 'POST',
url: '/eventoEntrada/entrada',
data: {"evento_id": evento_id, "participante_id": participante_id},
dataType: 'text',
success: function (data) {
$("#divLista").html(data);
}
})
});
});
and this is the method:
def entrada(){
EventoEntrada entrada = new EventoEntrada()
entrada.setEvento(Evento.get(params.evento_id))
entrada.setParticipante(Pessoa.get(params.participante_id))
println params.evento_id
println params.participante_id
entrada.hora_entrada = java.sql.Time.valueOf(new SimpleDateFormat("HH:mm:ss").format(new Date()))
entrada.saida_antecipada = false
if (!entrada.validate()) {
entrada.errors.allErrors.each {
println it
}
}else{
entrada.save(flush:true)
def listaParticipante = EventoEntrada.list()
render (template:"list", model:[listaParticipante:listaParticipante])
}
}
when i submit the form i get the url ".../.../eventoEntrada/index?evento_id=X&participante_id=Y"
why am i missing?
thanks!
I guess your Ajax url is the problem. you can try to give controller Name and action instead of giving path.
$(document).ready(function () {
$('#formEntrada').submit(function () {
var evento_id = document.getElementById("evento_id").value;
var participante_id = document.getElementById("participante_id").value;
$.ajax({
type: 'POST',
url: "${createLink(controller: 'controllerName', action: 'entrada')}",
data: {"evento_id": evento_id, "participante_id": participante_id},
dataType: 'text',
success: function (data) {
$("#divLista").html(data);
}
})
});
});

innerHTML.value not working?

I've been trying to write a JavaScript program that returns Wikipedia search results. A few days ago, I got it to the point where I could see the item being searched for, as confirmed by the alert() method, but now when I call the same alert() method it just returns "undefined":
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
I swear that this is exactly what I had while it was working, so there must be some subtle issue elsewhere. Any help is appreciated, complete code below:
HTML:
Random
<section>
<form>
<br>
<div class="divid">
<input type="text" value='' id="test" >
<button >Search</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
JavaScript:
$(document).ready(function () {
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
var button = $('button');
var toSearch = '';
var searchUrl = "http://en.wikipedia.org/w/api.php"
var x="England";
input.autocomplete({
source: function (request, response) {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
'action': "opensearch",
'format': "json",
'search': request.term
},
success: function (data) {
response(data[1]);
}
});
}
});
var playListURL = 'http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?';
$.getJSON(playListURL ,function(data) {
$.each(data.query.pages, function(i, item) {
//alert(item.title);
})
})
$.ajax({
//http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: "Carl Sagan", format: 'json' },
dataType: 'jsonp',
success:
function (x) {
//alert( x.query.search[0].title);
}
});
})
Use .innerHTML to get the html in a DOM element
Use .value to get the value of an input, textarea, or other form input
.innerHTML.value is not a thing.
If you are using jQuery, try this:
var search = $("#test").html();
alert(search);

Categories

Resources