Cannot modify the value of a node in a onclick called function - javascript

I set the arguments of my function called on onclick event with PHP and I also pass "this" ( the button ) as an argument so that in my function I access the closest <td> node and change its value.
However, I can't change the value of the node.
I get
is not a function
error each time I try to modify it.
PHP code :
echo "<tr><td>";
echo "<button onclick='updateValue($index,$byte,this)'></button>";
echo "<td>".$byte."</td>";
echo "<td>".$comment."</td>";
echo "</tr>";
And my JS function there :
function updateValue(index,byte,button){
$.ajax({
url : 'commentrefresh.php',
type : 'GET',
data : 'bytenumber=' + byte +"&byte_id=" +index,
datatype : 'text',
success : function(data){
button.closest('tr').lastChild.val(data)
}
})
}

Check this fiddler and the way I get the lastChild td node.
https://jsfiddle.net/aqmtjs8k/
$(button).closest('tr').find('td:last-child')
And if you want to write inside the last td you should use .html() and not .val()
.val() is only for inputs
Correct way: $(button).closest('tr').find('td:last-child').html(data)

As the error message says, closest isn't a function on DOM nodes.
You've tagged this question jquery, and jQuery objects do have a closest method, but you haven't wrapped the DOM node in a jQuery object.

Related

Call a jquery function dynamically from a json object

Say, I have JSON data getting from API. I want to use a value of JSON key to call a user-defined jquery function.
The data I am getting from the server is :
{
"question":"What is your age?",
"graphType":"horizontalBar",
}
Now I am having a function in my script which is named as horizontalBar.
( function( $ ){
$.fn.horizontalBar = function(data){
//do some stuff
}
})( jQuery );
So, now I want something like this in order to call the function:
$().json.graphType(data);
Here is what I searched and tried to call it:
window[json.graphType](data);
What about:
$(<selector of target object>)[json.graphType](data);
This will apply the jquery-method named in json.graphType on the selected jQuery target object.
From your post I now guess, that you don't even have a selector. So, <selector of target object> is void:
$()[json.graphType](data);

How to properly call a PHP function?

I currently have a PHP function which I need to call from a different file to populate a Javascript variable. I can populate the Javascript variable just fine. However when calling the PHP function I get an error message stating that
Use of undefined constant getEstGrid - assumed 'getEstGrid' in
phpcom/db/estimatesCom.php</b> on line 29.
Here is my include file which has the function:
<?php include 'phpcom/db/estimatesCom.php';?>
Here is where I'm calling the function:
<?php echo getEstGrid($resultsE); ?>
Function code:
function getEstGrid($resultsE){//<--This is the variable passed to the function
if ($resultsE->num_rows > 0) { //<--- Check to see if the variable is greater than zero
$rows = array(); //<--- Create an empty array calls "rows"
while ($r = $resultsE->fetch_assoc()){//<--- While the database records are being returned create a variable called "r" and assign DB record.
$rows[] = $r; //<-- assign each DB record row to the array.
}
$data = array('Estimates' => $rows);//<--- Create a variable an assing the array to it.
}
//header("Content-Type: application/json;charset=utf-8");
echo json_encode($data, true);//<--- Endode the "data" variable to a JSON format.
return getEstGrid;//<--- Return the created fucntion.
}
If anyone can help with this I would really appreciate it.
I would change this:
echo json_encode($data, true);//<--- Endode the "data" variable to a JSON format.
return getEstGrid;//<--- Return the created fucntion.
By this:
return json_encode($data, true);
This way, the function just returns the data, and you can choose whether echo it o do any other thing with it out of the box.
Just remove this return statement from your function:
return getEstGrid;//<--- Return the created fucntion.
Why have you used that? Not needed.
Also, if you are using echo in your function you don't need to use echo while calling your function to print the output.
You dont have to return the function in order to use it in another file.
Instead, just return the value you need from the function:
return json_encode(...
When you try to return "getEstGrid", php is looking for a constant with that name, which doesnt exist.

Undefined JS alert

I've got an a-tag which reads as this: (and there are number of a-tags being dynamically populated as this stays inside a PHP loop.)
echo "<a onclick='trygettheid();' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
and the JS function looks like below.
function trygettheid()
{
var myvariable = $(this).attr('id');
alert(myvariable);
}
The issue is when a click is triggered, the alert says 'undefined' instead of the desired output of 'main'
Am I missing anything here?
Inside the function this does not refer to the clicked element it may be window object. To fix it pass the reference as an argument to the function. Although there is no need to use jQuery since id can be get from element id property.
PHP :
echo "<a onclick='trygettheid(this);' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
// ------^------
JS :
function trygettheid(ele){
// -----^-----
var myvariable = ele.id;
// ---^--^----
alert(myvariable);
}

Validate dynamic input form elements using Validator Plugin Jquery

I am using this http://jqueryvalidation.org/ jquery validation plugin.
HTML dynamic form will be like this
<form name="baby_book" id="baby_book">
<input name="form_elements[16]" id="form_elements[16]">
<input name="form_elements[17]" id="form_elements[17]">
<input name="form_elements[18]" id="form_elements[18]">
<a class="myfont baby_book_save" href="javascript:void(0)" onclick="validatefilesizeform('save')" >Save</a>
</form>
My JS Code will be like this
<script type="text/javascript">
var validator="";
$(document).ready(function(){
var max_length_rules= <?php echo json_encode($valid_rules); ?>;
validator=$("#baby_book").validate();
$.each(max_length_rules,function(k,v){
$.each(v, function(key, value){
$('input[id="'+key+'"]').rules('add',"required");
});
});
});
function validatefilesizeform(type)
{
if(type == 'save')
{
document.baby_book.sec_submit.value="save";
if(validator.form())
{
document.baby_book.submit();
}
}
</script>
While applying dynamic rules like that it doesn't validate the form.
In console it displays this error
Uncaught TypeError: Cannot read property 'form' of undefined
Can anyone help me how to add dyanmic rules . Thanks.
That's because when the browser finds the validatefilesizeform('save') in the onclick attribute, it evaluates that expression, i.e runs the function. With this syntax you're asigning the result of that evaluation to the onclick event, which is not what you want.
The Cannot read property 'form' of undefined error happens because in that moment the $(document).ready() callback has not yet been executed, and, when the function tries to execute validator.form(), that variable is already undefined. It will be initialized later, inside the $(document).ready().
To get the expected behavior, and avoid the error, you must change the onclick handler to this one:
`onclick="function() { validatefilesizeform('save') }"`
In this case you're registering a function as the value for the onclick attribute. And this function will be evaluated when the control is clicked.
To make it even more clear:
// This is the value returned by the function evaluation:
validatefilesizeform('save')
// This is a function
function() { validatefilesizeform('save'); }
So the second is a function that can be evaluated. The first one evaluates the function. Handlers should always be functions, and not values.

Select content within a variable instead of within the current DOM with jQuery?

I have an ajax function using jQuery that defines an error function to be called. When an error occurs on the server this error function runs. One of the variables passed in "jqXHR" contains a property called responseText. I want to dump this response text into a div on the page, but the response text contains a fully-formed HTML document. Is there any way to use jQuery to traverse this variable containing HTML in the same way I would traverse the regular DOM?
$.ajax({
blah blah blah...,
error: function (jqXHR, textStatus, errorThrown)
{
var errorText = $(jqXHR.responseText).find('body').html();
// The above line does not work. errorText is NULL.
$('#mainContent').html(errorText);
}
});
I would like to do something like the above code snippet but the way I'm doing it does not work. Is there a way to traverse this variable as if it were a DOM that I could navigate with jQuery?
UPDATE
Here is a console.log($(jqXHR.responseText))
http://www.codetunnel.com/content/images/consolelog.jpg
Some sweet discovery for me as well on this one.
This doesn't work because behind the scenes, jQuery is creating a document fragment and setting the innerHtml property on it. This does not work with the <html> and <body> nodes because those aren't document node types--they cannot be placed into the DOM.
Instead, when you call $('<html><body><b>foo</b></body></html>'), a fragment is created with just "<b>foo</b>" in it! So, you want just the body part? Just return:
$(jqXHR.responseText).html();
Fiddle to prove what I'm referring to: http://jsfiddle.net/L5PR5/1/
EDIT #2
I think your only choice, given that <head> elements are being put in there, is to use substrings:
var res = jqXHR.responseText;
$(res.substring(res.indexOf('<body'))).appendTo('#mainContent');
Try this:
var errorText = $('<div />').append(jqXHR.responseText).html();
and here's a jsfiddle.
Use .filter()
http://api.jquery.com/filter/
var myHtml = '<div id="blah">hello world</div>';
console.log($(myHtml).filter('#blah').html());
This will show "hello world" in the console. It's HTML stored in a variable. You apply the filter() from jquery to that variable (see above) and you can access your dom that way even though it's in a variable.
Assuming your html is valid xml you can do
var xmlDoc = $.parseXML( jqXHR.responseText ),
body = $( xmlDoc ).find('body')[0],
bodystring = body.xml || new XMLSerializer().serializeToString(body);
now bodystring holds the entire <body> tag (as a string) and you can use it to append it in the DOM with
$('#mainContent').html( bodystring );
demo at http://jsfiddle.net/gaby/hYukn/

Categories