modelandview var parameter using ajax.updater - javascript

In a page JSP y get by JSTL a var ModelAndView in "${model}
In this page I use JAVASCRIPT to update a DIV with ajax.updater, the code here:
document.getElementById("idFa").value=image.title;
var frm2="${model}";
var dataString = 'mail=acevallo#hotmail.com&idFar=' + image.title + "&frm2=${model.farmers}";
new Ajax.Updater( "pcBody_content2", "tabProductsFruitC2.jsp", { method: "get",parameters:dataString,evalScripts: true });
my problem is, when I update the DIV with the new page tabProductsFruitC2.jsp. In this new page I haven't the var ${model}, so I have that send by parameter this var.
I tried it with var frm2, but it convert my var in string and I can not my modelandview var. How I can send by parameter my model var ${model}.
thanks, guys

Finally I found one solution for this problem....
I had that using JSTL into JavaScript, get my data in one array and send by parameter using LOAD of jquery, so:
enter code here
function productsLoad(image){
var contactTypesList = new Array();
var tmpArray = new Array();
var newOption,newOption2;
var i=1;
<c:forEach items="${model.farmers2}" var="contactType">
newOption = '${contactType.farmerId}';
contactTypesList.push(newOption);
if ((newOption==image.title)&&(i==1)){
<c:forEach items="${contactType.products}" var="prd">
newOption2 = '${prd.key}';
tmpArray.push(newOption2);
</c:forEach>
i=i+1;
}
</c:forEach>
var dataString = 1;
$j("#pcBody_content2").load("jsp2/tabProductsFruitC2.jsp",{ 'choices[]': tmpArray } );
}
</script>

Related

How to send an integer from ajax without jquery?

I am trying to send an integer called 'petadid' from this js to the django view called 'petadlikeview'. But it looks like the data is not going there in the view.If i print 'petadid' in the view, it shows 'None'. Can anyone please tell me what is wrong? I am new to ajax and django.
Here is my js:
<script>
$(document).ready(function(argument) {
$.ajaxSetup({cache:false});
var element = document.getElementById("likes");
var petadid = $(this).attr("data-petadid");
element.addEventListener("click",function(){
var req = new XMLHttpRequest();
req.open("POST",'/petadlike/')
req.onload = function(){
console.log(req.responseText);
console.log(petadid);
var data = JSON.parse(req.responseText);
}
req.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
var data = {
'petadid':petadid,
}
req.send(data);
});
});
</script>
And here is my django-view:
def petadlikeview(request):
print("vau")
if request.method=="POST":
print("vai")
petadid = request.POST.get('petadid')
print(petadid)
petad = PetAd.objects.get(pk=petadid)
like_count = petad.petadlikes_set.all().count()
like, created = petadlikes.objects.get_or_create(user=request.user,petad=petad)
print(created)
if created is False:
petadlikes.objects.get(user=request.user,petad=petad).delete()
like_count -= 1
liked = False
else:
like.save()
like_count += 1
liked = True
dict = {'like_count':like_count}
return JsonResponse(dict)
return HttpResponse(str(like_count)+' people have liked this')
else:
return HttpResponse('Bad Request')
XMLHttpRequest will not automatically convert an object to POST data as jQuery does, you need to create the URL-encoded string yourself.
var data = "petadid=" + encodeURIComponent(petadid);
Also
var petadid = $(this).attr("data-petadid");
should probably be
var petadid = $(element).attr("data-petadid");

javascript 'object object' from localstorage

I am getting an alert saying [object] object when I execute showlogsf function
var fdata = {fidval, fweightval, feggslaidval, fgraineatenval, fwaterval};
var fidval = document.getElementById('#fid');
var fweightval = document.getElementById('#fweight');
var feggslaidval = document.getElementById('#feggslaid');
var fgraineatenval = document.getElementById('#fgraineaten');
var fwaterval = document.getElementById('#fwater');
These are the two functions that could be triggered from button click
$('#submitf').click(function (){
localStorage.setItem ("fdatak", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload);
});
});
You're pushing an object as an alert. the HTML displays this as [object Object]. You have to address the actual properties of this object, so:
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload.fidval);
alert(fdataload.fweightval);
alert(fdataload.feggslaidval);
// etc etc...
});
EDIT: Seems like you're also saving the document element, rather than the value. I assume the fdataload.properties are actual values, you should either grab the raw HTML data or input value of this instead of the HTML element itself
I guess your fdata is an array right?.
Try this var fdata = [fidval, fweightval, feggslaidval, fgraineatenval, fwaterval];
I edited values of array as xxx.value instead of xxx
var fdata = new Array();
$('#submitf').click(function (){
var fidval = document.getElementById('fid');
var fweightval = document.getElementById('fweight');
var feggslaidval = document.getElementById('feggslaid');
var fgraineatenval = document.getElementById('fgraineaten');
var fwaterval = document.getElementById('fwater');
var fdata = [];
like this
fdata.push (fidval.value, fweightval.value, feggslaidval.value, fgraineatenval.value, fwaterval.value);
localStorage.setItem ("fdata", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem('fdata'));
document.getElementById("flogview").innerHTML = fdataload;
});
Now it saves but I have another problem, why it is replacing data every time I click showlogsf button??

Passing array from php to javascript through ajax response

This is my first post in stackoverflow. I have always got my answers from previously posted questions. This problem has been bugging me and all the solutions I tried have not worked.
I have a js function which makes an ajax request to get weather info of town passed:
var _getWeatherInfo = function(ntown){
var town = ntown;
var url = "PHP/weather.php?town=" + town;
request1.onreadystatechange = _refreshWeatherList();
request1.open("GET", url, true);
request1.send("");
}
I am using the following php code to return the sql results stored in array:
<?php
//Connection to the database
$mysql = mysql_connect("localhost","xuvaz","x");
//Selecting Database
$db = mysql_select_db("weather");
$town = $_GET['town'];
$tarray = array();
$sql1= mysql_query("SELECT * FROM weather WHERE town='$town'");
while($row = mysql_fetch_assoc($sql1)) {
$tarray = array('town' => $row['town'],'outlook' => $row['outlook']);
}
echo json_encode($tarray);
?>
Then I have a function that is called when the request is completed:
var _refreshWeatherList = function() {
var weather_info = request1.responseText;
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();
}
The problem is I cant access the array values.
I can see the values as {"town":"Christchurch","outlook":"fine"} in firebug under response.
Even when I use JSON parse it gives error in the firebug , JSON.parse: unexpected end of data. If
I can just access the data my whole project would be completed.
Your PHP code is returning an object (last row from your loop) rather than an array of objects, but your JavaScript is expecting an array.
Change your PHP to the following to appand to $tarray:
while($row = mysql_fetch_assoc($sql1)) {
$tarray[] = array('town' => $row['town'],'outlook' => $row['outlook']);
}
Your JavaScript needs to wait for readyState = Loaded and JSON-decode the responseText:
var _refreshWeatherList = function() {
if(request1.readyState == 4) {
var weather_info = JSON.parse(request1.responseText);
....
}
}
If the parse is failing, trying logging it to the console to make sure the PHP isn't returning extra characters.
var _refreshWeatherList = function() {
var weather_info = eval("("+request1.responseText+")");
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();}
'request1.responseText' must be 'object' use eval() --! my english not well
Thank you for all your help. I found the fault. I forgot to include these two lines.
if (request1.readyState == 4) {
if (request1.status == 200){

Pass a variable from razor to javascript and display it

I have a variable
var result = client.DownloadString(query);
in mvc 4 rzaor. By hovering it in the debugging process, it likes the image below
What I want is to display it, so I return it to javascript with the code:
function myFunction() {
$('#response').text('#(Url.Action("result"))');
}
EDIT:
<div id="response"></div>
#{
var strSearch = "test";
var options = "include-passage-references=true";
var client = new WebClient();
var query = string.Format("http://www.xxx.org/v2/rest/passageQuery?key={0}&passage={1}&options={2}", "IP", Server.UrlEncode(strSearch), options);
var result = client.DownloadString(query);
}
However nothing found.
You have to use the ViewBag for that.
On C#:
ViewBag.result = client.DownloadString(query);
On HTML:
function myFunction() {
$('response').text('#ViewBag.result');
}

Generating JSON Object

I'm trying to parse the rows in a table that I generate using Javascript by adding items to a cart and then create a json object when the user hits save order of all the items and pass it to a php script using $.post in jQuery.
The only trouble I'm having is understanding JSON objects and how to push more items onto the object. I get an error in firebug telling me that devices[i] is undefined. Not really sure how else to accomplish this. I thought it was really just an array.
function Save()
{
var devices = new Object();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
You currently have devices declared as an object, but you're treating it like an array.
You need to declare it as an array of objects.
function Save()
{
var devices = new Array();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i] = new Object();
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
or something like that.
(Updated to show it in your code)

Categories

Resources