Passing variables to ajax with onclick - javascript

I have a problem with the variables, that I want to pass through ajax to php.
In an php file, I generate some divs with id and name attributes.
livesrc.php
echo "<div class=\"search-results\" id=\"" . $softwareArray['Sw_idn'] . "\"
name=\"" . $softwareArray['SoftwareName'] . "\"
onclick=\"addBasket(this.id, this.name)\" >
" . utf8_encode($softwareArray['SoftwareName']) . "</div>";
The relevent part is this:
onclick="addBasket(this.id, this.name)
Sorry for the escapes, in html the div looks like:
<div class="search-results" id="235"
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this.id, this.name)">...</div>
This looks okay, but in the js "addBasket", the variable sw_name is not set. (undefinded)
The JS in the head section:
<script type="text/javascript">
function addBasket(sw_id, sw_name)
{
alert(sw_name);
$.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data)
{
$("#basket").html(data);
});
}
</script>
The sw_id is set, but the sw_name is not working. Is the call in html with "this.name" correct?

it's because this.name did not exists if you want to access the attribute you have to call this.getAttribute('name') id are particular and can be access directly.
Personally I will give juste this to the function and extract id and name in the function
onclick="addBasket(this)";
<script type="text/javascript">
function addBasket(el)
{
var
sw_id = el.id,
sw_name = $(el).attr('name');
alert(sw_name);
$.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data)
{
$("#basket").html(data);
});
}
</script>

You could pass the whole element into your js:
<div class="search-results" id="235"
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this)">...</div>
Then grab what you want in your function
function addBasket(sw) {
alert( sw.id + ' ' + sw.getAttribute( 'name' ) );
}

Related

Reg Ex doesnt validate if i use # along with other characters or number

this is the same question i asked before. sorry but i check all the link provided it doesnt help. and sorry this is the first time i asked question here so was not very clear about how to ask
I am explaining here again with full details:
i have an input text field.
I Use jquery to validate the input date entered by user in this input box.
I pass the data enter as parameter in javascript GET method and pass it to PHP and validate it there with simple REG Ex. It does validate in all account. But if i add # with any test case this validation fails.
my code:
Input field:
<div id="clntFstName" >
<label for="clnt_fst_name">First Name</label>
<input type="text" id="clnt_fst_name" name="clnt_fst_name" onBlur="checkFieldValid(this.value, this);" value=""/>
<div class="msgError"></div>
</div>
If you the function CheckFieldValid is called as the user leaves a field input box.
java script:
function checkFieldValid(value, obj) {
var elem = obj.name;
$('#' + elem).parent().children('.msgError').html('');
var $label = $("label[for='" + obj.id + "']").text();
var $id = obj.id;
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" + value + "&lab=" + $label + "&id=" + $id, function(json) {
if (json.status.length > 0) {
$.each(json.status, function() {
if (this['fail'] == 'fail') {
var info = '<div class="warningMsg"> ' + this['message'] + '</div>';
$('#' + elem).parent().children('.msgError').html(info);
$('#' + elem).focus();
$('#' + elem).val("");
}
if (this['success'] == 'success') {
$('#' + elem).parent().children('.msgError').html('this is success');
}
});
if (json.status == 'empty') {
$('#' + elem).parent().children('.msgError').html('this is empty');
}
}
});
}
PHP code:
if($_GET['action'] == 'checkInputFieldValid'){
if(!empty($_GET['varField'])){
// this creates dynamic session variables and add values to it.
$_SESSION[$_GET['id']] = $_GET['varField'];
if(preg_match('/^[a-zA-Z]+$/',$_GET['varField'])){
$txtVar = 'It is a valid '.$_GET['lab'];
array_push($validFieldArray, array('success' => 'success', 'message' => $txtVar));
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 0;
}else{
$txtVar = 'Enter a valid '.$_GET['lab'];
array_push($validFieldArray, array('fail' => 'fail', 'message' => $txtVar));
unset($_SESSION[$_GET['id']]);// unset the session variable to clear when page refresh
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 1;
}
}
}
I dont know where I am wrong? I did all as told by other members May be I am doing something wrong with Java script when I pass the GET request variables? as far as
I think I did exactly what other member told me about PHP part. but may be the data is wrong when i take it from Java script part? As i checked it with other values return from PHP. but when I put # in my input box IT does not make the AJAX call and doesnt return the JSON nor set the session variable. So probably when I pass the varible as GET parameter It doesnt run the AJAX and just doesnt validate so plz tell me how can i pass # as GET parameter so that i correctly validate the fields in my PHP .
Plz help I will loos my job :(
Your $.getJSON call should use encodeURIComponent() to make sure you're not creating the wrong URL:
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" +
encodeURIComponent(value) +
"&lab=" +
encodeURIComponent($label) +
"&id=" +
encodeURIComponent($id), function(json) {
If you don't do that, then a # character will be interpreted as signalling the start of the hash field of the URL, and the rest of the URL will be ignored.

HTML/PHP/JS issue - onclick function not working

So here i am trying to call a function that passes 2 values as parameters (added dynamically using php). The damn thing doesn't seem to work no matter what i try. Can any of you guys point out what i'm doing wrong? Here is the code:
// HTML/PHP
$pid = $row['postID'];
$pt = $row['postTitle'];
//There arrays are working great.
Delete // Does not call delpost
Delete // BUT if i remove the second parameter, it works! How?
// JS
<script language="JavaScript" type="text/javascript">
function delpost(id, title) {
if (confirm("Are you sure you want to delete" + title + "?")) {
window.location.href = 'index.php?delpost=' + id;
}
}
</script>
The quotes on "delpost are wrong. delpost is a function so onclick"<?php echo delpost($pid,$pt); ?>" should work.
Delete // Does not call delpost Delete // BUT if i remove the second parameter, it works! How?
first delete is not working because when you are passing two value on a function one value is blank that why its not working
<?
$pid = 1;
$pt = 2;
//There arrays are working great.
?>
Delete // Does not call delpost
Delete // BUT if i remove the second parameter, it works! How?
<script language="JavaScript" type="text/javascript">
function delpost(id, title) {
alert(id);
if (confirm("Are you sure you want to delete" + title + "?")) {
window.location.href = 'index.php?delpost=' + id;
}
}
</script>
Delete
I tried your code directly and it worked, but i also have added another way of writing it:
<?php
$pid = 42;
$pt = 'Awesometitle 2000';
?>
Delete
Delete 2
<script>
function delpost(id, title) {
console.log(id);
console.log(title);
}
</script>
Both variations should print 42 and "Awesometitle 2000" in your console.

Select2() is not a function

So i have downloaded select2 i have "installed it" by putting it into my folder and then loaded it on my site when i check the console (where i can see all of the scripts being loaded) i can see the file select2.js
I went to their documentation and copied it and added $("#e9").select2();
However when i load the page i get the following error:
TypeError: $(...).select2 is not a function
$("#e9").select2();
Have anyone else experianced anything like this?
Additional information here is my script:
jQuery(document).ready(function(){
var max_amount = parseFloat($('#max_amount').val());
$( "#item_amount" ).keyup(function() {
if($(this).val() > max_amount){
$(this).val( max_amount);
}
if( /\D/.test($(this).val()) ){
alert('Må kun indeholde tal!');
$(this).val('');
}
if($(this).val()== '0'){
alert('Må ikke være 0!');
$(this).val('');
}
});
$("#e1").select2();
});
function addToBasket(){
var amount = $('#item_amount').val();
if(amount == ""){
amount = 1;
}
if(amount > 0){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Products/addItemToBasket',
dataType: 'json',
data: {
id: window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1),
amount: amount
},
success: function (data) {
var urlToBasket = myBaseUrl+'Products/basket';
var newAmount = parseInt(amount)
var price = data[0]['Product']['pris'];
var id = data[0]['Product']['id'];
var dat = data;
var tmp_basket_html = $('#basket_amount').html();
if($('#basket_amount').html() !== " Tom"){
$('#shopping_table_body').append(
"<tr id='"+id+"'>" +
"<td class='image'>" +
""+
"</td>" +
"<td class='name'>" +
" "+data[0]['Product']['name'] +
"</td>"+
"<td class='quantity'>" +
"x "+amount +""+
"</td>"+
"<td class='total'>" +
""+price*amount+
"</td>" +
""+
"<td class='remove'>" +
"<input class='icon-remove' type='button' onclick='removeItemFromBasket("+id+")'>"+
"</td>"+
"</tr>"
);
}else{
$("#shopping_menu").append(
"<ul class='dropdown-menu topcartopen'>"+
"<li id='basket_list'>"+
"<table id='shopping_table'>"+
"<tbody id='shopping_table_body'>"+
"<tr id='"+id+"'>" +
"<td class='image'>" +
""+
"</td>" +
"<td class='name'>" +
" "+data[0]['Product']['name'] +
"</td>"+
"<td class='quantity'>" +
"x "+amount +""+
"</td>"+
"<td class='total'>" +
""+price*amount+
"</td>" +
""+
"<td class='remove'>" +
"<input class='icon-remove' type='button' onclick='removeItemFromBasket("+id+")'>"+
"</td>"+
"</tr>"+
"</table>"+
"</li>"+
"<div class='well pull-right'>"+
"<input type='button' onclick='goToBasket()' class='btn btn-success' value='Tjek ud'>"+
"</div>"+
"</ul>"
)
}
updateTotal(amount,price);
updateBasketAmount();
}
});
}
Notifier.success('Vare tilføjet', 'Tilføjet'); // text and title are both optional.
}
function updateTotal(amount, price){
var price = parseFloat(price);
var oldValue = parseFloat($('#basket_total_cost').html());
var newPrice = amount*price+oldValue;
$('#basket_total_cost').html(newPrice);
}
function updateBasketAmount(){
var tmp = $('#basket_amount').html();
if(!isNaN(tmp)){
var oldAmount = parseInt(tmp.substr(0,2));
var i = oldAmount + 1;;
$('#basket_amount').html(
""+i+" vare(r)"
);
}else{
$('#basket_amount').html(
"1"+" vare(r)"
);
}
}
function goToBasket(){
window.location.href = myBaseUrl+'Products/basket';
}
I was having this problem when I started using select2 with XCrud. I solved it by disabling XCrud from loading JQuery, it was it a second time, and loading it below the body tag. So make sure JQuery isn't getting loaded twice on your page.
This error raises if your js files where you have bounded the select2 with select box is loading before select2 js files.
Please make sure files should be in this order like..
Jquery
select2 js
your js
Had the same issue. Sorted it by defer loading select2
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js" defer></script>
I was also facing same issue & notice that this error occurred because the selector on which I am using select2 did not exist or was not loaded.
So make sure that $("#selector") exists by doing
if ($("#selector").length > 0)
$("#selector").select2();
Add $("#id").select2() out of document.ready() function.
you might be referring two jquery scripts which is giving the above error.
I used the jQuery slim version and got this error. By using the normal jQuery version the issue got resolved.
The issue is quite old, but I'll put some small note as I spent couple of hours today investigating pretty same issue.
After I loaded a part of code dynamically select2 couldn't work out on a new selectboxes with an error "$(...).select2 is not a function".
I found that in non-packed select2.js there is a line preventing it to reprocess the main function (in my 3.5.4 version it is in line 45):
if (window.Select2 !== undefined) {
return;
}
So I just commented it out there and started to use select2.js (instead of minified version).
//if (window.Select2 !== undefined) {
// return;
//}
And it started to work just fine, of course it now can do the processing several times loosing the performance, but I need it anyhow.
Hope this helps,
Vladimir
Put config.assets.debug = false in config/environments/development.rb.
For me, select2.min.js file worked instead of select2.full.min.js. I have manually define files which I have copied from dist folder that I got from github page. Also make sure that you have one jQuery(document).ready(...) definition and jquery file imported before select2 file.
For newbies like me, who end up on this question: This error also happens if you attempt to call .select2() on an element retrieved using pure javascript and not using jQuery.
This fails with the "select2 is not a function" error:
document.getElementById('e9').select2();
This works:
$("#e9").select2();
In my case, I was getting this error in my rails app when both webpacker and sprockets were trying to import jQuery. I didn't notice it until my code editor automatically tried to import jQuery into a webpacker module.
I was having the same problem today and none of the other answers worked. I don't understand how or why this worked, but it did and (knock on wood) still does.
But first, a bit about my specific situation:
I was using select2 in one .js file and trying to get it into another one, but got this error. jQuery was working fine in the other .js document, and the second one I tried to use was called LATER in the html than the first .js document I was writing, and both later than the jquery and select2 tags.
OK, now for the solution that doesn't make sense, but does work:
I put the definition of the jQuery element into the earlier .js file and the .select2 on that variable in the later .js file. Weird, right? So, like this:
<head>
*blah blah blah html headers*
<script src="/static/js/jquery-3.6.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<body>
*blah blah blah page stuff*
<script src="/static/js/first.js"></script>
*blah blah some more stuff*
<script src="/static/js/second.js"></script>
first.js
const selector = $('#select-this')
second.js
selector.select2({
*&c, &c, &c.*
ControlId.select2({...}); was not working but following worked:
$(ControlId).select2({...});

Javascript/jquery .load passing variable

Stuck on a jquery/javascript function that is attempting to .load a set PHP script but passing get variable parameters. As an aside this is set to happen automatically after 5 seconds. New to posting here but have read a lot of posts and can't seem to find exactly what I am doing wrong.
This function works:
function LoadMyPhpScript()
{
$('#MyDiv').load('hello.php');
}
setTimeout(LoadMyPhpScript,5000);
This function does not work:
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'hello.php';
strURL = strURL + cPhpParamString;
$('#MyDiv2').load(strURL);
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
Here's the hello.php
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Note: this is just a mock-up, would use regex to validate gets, etc in production.
RESOLVED
Here is what I ended up with, thank you!
function LoadMyPhpScript1(cPhpParamString)
{
$('#MyDiv1').load('hello.php'+cPhpParamString);
}
setTimeout(function() { LoadMyPhpScript1('?MyVar1=0&MyVar2=1'); },5000);
When you do this:
LoadMyPhpScript2('?MyVar1=0&MyVar2=1')
You are executing the function and passing the result to setTimeout
Try this:
setTimeout(function() { LoadMyPhpScript2('?MyVar1=0&MyVar2=1'); },5000);
However, sending the url querystring like that is an odd way of doing it. Something like this might be better:
function LoadMyPhpScript2(myVar1, myVar2)
{
var strURL = 'hello.php';
$('#MyDiv2').load(strURL, { myVar1: myVar1, myVar2: myVar2 });
}
setTimeout(function() { LoadMyPhpScript2(0, 1); },5000);
Better try this way:
File help3.html:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'help3.php';
strURL = strURL + cPhpParamString;
$.ajax({
url: strURL
}).done(function(data) { // data what is sent back by the php page
$('#MyDiv').html(data); // display data
});
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
</script>
</head>
<body>
<div id="MyDiv">
</div>
</body>
</html>
File help3.php:
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Test on my localhost, and both files on the same folder.

Javascript Quotes Problem When Dynamically Adding Content

I'm trying to dynamically add content stored in a variable. However, single quotes are causing problems.
var dynamicelementcode = $("<div id='container'>" + data + "</div>");
dynamicelementcode.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
If the data variable contains a single quote, it breaks my code. How can I solve this problem? The data variable gets its content from a serverside php script.
Any php/js/jquery solution appreciated
Edit:
PHP Code Serverside
$comment_body = "The boy's bicycle";
echo '{ "author": "'.$author.'", "message": "'.$comment_body.'","parentid": "'.$parent_id.'","currentid": "'.mysql_insert_id().'","timestored": "'.$timestampa.'" }';
Jquery Code, Clientside
var newrootcomment = $("<div class='comment'><div class='comment-holder'><div class='comment-body'>"+ data.message + "</div> <abbr class='timestamp' title=''>" + data.timestored + "</abbr><div class='aut'>" + data.author + "</div> <a href='#comment_form' class='reply' id='id"+ data.currentid + "'>Reply</a> </div> </div>");
newrootcomment.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
var dynamicelementcode = $('<div id="container">').text(data)
jQuery text function automatically escapes quotes for you.
UPD. Escaping only single quotes:
var dynamicelementcode = $('<div id="container">').html(data.replace(/'/g,'''))
UPD 2. If you look at the source of your page you'll see something like "message": 'The boy's bicycle' - that's a syntactic error.
Here's a better way to pass PHP data to JavaScript, works with quotes too:
$comment_body = "The boy's bicycle";
echo json_encode(array(
'author' => $author,
'message' => $comment_body,
'parentid' => $parent_id,
'currentid' => mysql_insert_id(),
'timestamp' => $timestamp
));
jQuery already has methods to insert text, you don't need to concatenate strings or take care yourself of escaping. Use the .text() method:
var dynamicelementcode = $('<div id="container"></div>').text(data);
Reference and examples: http://api.jquery.com/text/#text2

Categories

Resources