I have a php loop that generates several buttons.Each button changes the content of a specific div and update some stuff in the database by using an ajax request.When the button is click it calls a function that executes the ajax request.The problem is that I am not able to pass the Div id as parameter in the function if I concatenate it with a string. Only when I write $TickCrossDiv = $i it is working (only when using number as Div id it works).
Here is my code :
for($i=0;$i<count($PlanningArray);$i++){
$TickCrossDiv = 'tickCrossDiv'.$i;
echo "<button onclick=\"SetActDone(
".$PlanningArray[$i]'PlanID'].",
".$PlanningArray[$i]['ActID'].",
".$TickCrossDiv.")\" >
Mark as done</button>"
}
Here is the function :
function SetActDone(PlanID,ActID,DivID)
{
$.ajax({
type: "POST",
url: 'testAjax.php',
data: {PlanID:PlanID, ActID:ActID},
success: function(data) {
$("#" + DivID ).html('<p>Status: Done</p> <i style="color:greenyellow; " class="fa fa-check-circle fa-2x"></i>');
}
});
}
I am getting the error :
Uncaught Error: Syntax error, unrecognized expression: #object HTMLDivElement
Without knowing what the values of $PlanningArray[$i][...] are I can't say for sure. But most likely you need to wrap your echoed variable in quotes. That would explain why a number would work, it will be treated as an integer rather than a string. Try this:
for($i=0;$i<count($PlanningArray);$i++){
$TickCrossDiv = 'tickCrossDiv'.$i;
echo "<button onclick=\"SetActDone(
".$PlanningArray[$i]['PlanID'].",
".$PlanningArray[$i]['ActID'].",
'".$TickCrossDiv."')\" >
Mark as done</button>"
}
I'm guessing that $PlanningArray[$i]['PlanID'] and $PlanningArray[$i]['ActID'] are also integers so they don't need to be wrapped in quotes.
I also fixed a typo on this line:
$PlanningArray[$i]'PlanID']
If your code works, that typo probably isn't in your real script.
Related
Not used Javascript -> Ajax -> PHP -> Javascript before and I am struggling to pick-up the return value. Ajax is calling the PHP, but all I am getting back is the HTML for the web page. Can anyone see what I am doing wrong?
Javascript: -
onChange: function(value, text, $selectedItem) {
jQuery.ajax({ url : 'index.php', type : 'post', data : { action: 'getTest', param : text },
success: function(result){
console.log('Sucess',result);
},
failure: function(result){ console.log('Failed'); }
});
}
PHP: -
$_action = isset($_Post['action']) ? $_Post['action'] : '0';
if ($_action == 'getTest') {
$test = $_Post['param'];
echo $test;
exit;
}
As I said, RESULT just seems to contain the page's HTML and not the expected string value.
Thanks
Your post variable is with small caps letters. However the Variable should be full caps ($_POST). So your php is not going into the if statement.
https://www.php.net/manual/en/reserved.variables.post.php
To debug these kind of issues start logging variables like $_action and check if their value is what you expect it to be. Then check if the if statement actually fires, etc. until you find the error.
Why am I receiving this error when my button click calls this function?
function ShowFaultMessage(message) {
$.ajax({
url: '/Home/Message/',
data: JSON.stringify(message),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function(result) {
var w = window.open("/Home/Message", "Fault Message", "width=400, height=400");
$(w.document.body).html(result.responseText);
}
});
};
I've looked at the other questions about this error, but none seem to apply here. I appear to have all my brackets and parenthesis present.
This is the button that calls the function. It appears ok as well:
return new HtmlString(string.Format("<input type='submit' id='btnShowFault' onclick='ShowFaultMessage({0})' value='Fault' />", item.Fault.Message));
I needed to put double quotes when building my HTMLString for the button in the parameter for the function call like so:
return new HtmlString(string.Format("<input type='submit' id='btnShowFault' onclick='ShowFaultMessage(\"{0}\")' value='Fault' />", item.Fault.Message));
yes you need double quote or single quote when passing a model value to javascript function consider it as a string value rather than a javascript value. This is the same case when using it on jquery or appending the model value.
var test = "alert_container";
foreach (var item in Model.ErrorLists)
{
<script>
jsfunction("#item.prop");
or
$('##test').append('<div class="alert alert-danger alert-dismissable fade in">' +
'×' +
'<strong>Error:</strong> #item.ErrorMessage </div>');
</script>
}
My goal is to pass $userId variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users.
Im having a bit of trouble getting the variable data to go to the ajax statement. What am i doing wrong?
<?php
session_start();
if(isset($_SESSION['userid'])) {
$userId = mysql_real_escape_string($_SESSION['userid']);
echo $userId;
echo ' (irrelevant code)...
//button that loads form via ajax...
Add URL
(irrelevant code)... ';
}
AJAX code:
function showAdd(str) {
$('#response').html('Processing Request. Please wait a moment...');
var userId = str;
alert (userId);
$.ajax({
type: "POST",
url: "addUrlForm.php",
data: "userId=" + str,
success: function(msg) {
$('#response').empty();
$('#content01').html(msg).show();
},
error: function () {
alert('error');
}
});
};
EDIT: I took your suggestion (thank-you) and it some-what helped. Now the alert is returning "$userId" variable as a string. How do I make it be recognised as a variable containing the session data, not as a string? I tried "showAdd($userId)" but console is telling me $userId is not defined?.
Since you're sending the userId as a parameter to the showAdd() function you should change your code to:
function showAdd(str) {
var userId = str;
// ...
}
or simply rename the parameter to userId:
function showAdd(userId) {
// use userId here
]
To make you above code send the correct userId and not the string $userId to the function you should wrap your output string in double quotes or output it directly:
echo 'Add URL';
or:
echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";
I do not understand why would you use $(this) when the userid is already present and is passed as function parameter.
Change this:
var userId = $(this).attr('userId');
To:
var userId = str;
I'm trying to add my data into a div, and its not working. The php is fine but I need a fine eye to see if they can spot any errors or can suggest any work arounds to help figure out why its not working.
I've tried to fix it for the past 5 hours or so and its racking my brains.
The user comments on a status like post and its suppose to add it to the div. Just like my main status does. The ajax for the main status is almost identical to the comment ajax below..yet the comment ahax isn't playing nice and is not inserting any data at all.
<script>
$(document).ready(function(){
$("form#mycommentform").submit(function() {
var streamidcontent = $('#streamidcontent').val();
var contents = $(this).children('#contents').val();
$.ajax({
type: "POST",
url: "comment_add.php",
cache: false,
dataType: "json",
data: { streamidcontent: streamidcontent, contents: contents},
success: function(data){
$('#containerid').html('<div class="stream_comment_holder" style="display:none;"
id="comment_holder_'+data['comment_streamitem']+'"><div
id="comment_list_'+data['comment_streamitem']+'"><div
id="tgy"></div><div class="stream_comment"
id="comment_'+data['comment_id']+'" style="margin-top:0px;"><table
width=100%><tr><td valign=top width=30px><img
class="stream_profileimage"
style="border:none;padding:0px;display:inline;" border=\"0\"
src=\"imgs/cropped'+data['id']+'.jpg\"
onerror="this.src=\"img/no_profile_img.jpeg\"" width=\"40\"
height=\"40\" ></a><td valign=top align=left>'+data['first']+'<div
class="commentholder">'+data['first']+'</div><br/><div
id="commentactivitycontainer"></div></div></table></div></div><div
class="form"><form id="mycommentform" method="POST"
class="form_statusinput"><input type="hidden" name="streamidcontent"
id="streamidcontent" value="'+data['comment_streamitem']+'"><input
type="text" name"contents" id="contents" placeholder="Say something"
autocomplete="off"><input type="submit" id="button"
value="Feed"></form></div><div class="stream_comment_holder"
style="display:;"><div class="like_name"><b><a
href="profile.php?username='+data['username']+'">You Like
This</a></b></div></div>');
}
});
return false
});
});
</script>
ERROR FOUND
success: function (data) {
alert("SUCCESS!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(xhr.status);
alert(thrownError);
}
OK
200
SyntaxError.JSONparse:Unexpectedcharacter
JSON
$json = array();
$check = "SELECT comment_id, comment_datetime, comment_streamitem FROM streamdata_comments WHERE comment_streamitem=".$_POST['streamidcontent']."";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
mysqli_free_result($check1);
$check = "SELECT * FROM users WHERE id=".$_SESSION['id']."";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
mysqli_free_result($check1);
echo json_encode($json);
I would recommend using some sort of templating system to do all the hard work assembling your content.
Take a look into Create a makeshift Javascript templating or John Resig's solution.
Building that string of mark-up inside html() is a little crude.
You also have an inline style of display:none on the first div, so you won't see it.
Have you tried stripping the function down just to see if anything gets populated
success: function(data){
$('#containerid').html('blurb');
}
I don't know if this is the only problem, but where you're trying to embed quotation marks inside the html attributes that you're creating, e.g.:
'onerror="this.src=\"img/no_profile_img.jpeg\""'
It will produce this invalid string:
onerror="this.src="img/no_profile_img.jpeg""
You should embed single quotes instead, like this:
'onerror="this.src=\'img/no_profile_img.jpeg\'"'
Which would produce:
onerror="this.src='img/no_profile_img.jpeg'"
Also, on about the sixth last line you have an attribute missing an = sign:
name"contents"
And the outer-most div you are inserting has style="display:none;".
Thats the best description I could think of. I normally do not post, but I honestly cannot figure this out.
Still in jquery learning mode, and basically what I want to accomplish is that depending on the type of button that is submitted, the script assigns variables to div's on the page. What I am making is a admin side of a user script to allow them to update that particular div that appears on the page.
When I put in the actual selectors, the script works.
When the page loads, it will take the field of the database that corresponds with the and load it. Once they push the update button, a new div will appear. The admin inputs his new data (the new information he wants to display) and it updates the mysql table, then pulls it back in through jquery's ajax.
Sorry for the long explanation. Like I said, I've never really posted, just always liked figuring it out on my own.
php page
<?php //
if(isLoggedIn())
{
echo '<button id="adultClassButton">Edit Class Information</button>';
}
?>
<div class="class" id="adultClass"><?php
$row = checkPost('adult');
echo $row['info'];
?>
</div>
<?php
echo '<div id="adultClassInput">
<textarea rows="2" cols="80" id="adultClassUpdate"></textarea>
<input type="hidden" id="className" name="adult"/>
<button id="adult">Save the Updated Class Info</button></div>';
?>
javascript (jquery) file
$(".button").click(function(){
var button = $(this).attr('id');
if (button == 'adult'){
var classDiv = $("#adultClass");
var className = $("#className");
var classDesc = $("#adultClassUpdate").val();
var classUpdateDiv = $("#adultClassInput");
postData(classDiv, className, classDesc, classUpdateDiv);
}
});
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: "name="+ className+ "& info="+ classDesc,
success:function(data){
$("#" + classDiv).html(data);
}
})
$("#" + classDesc).val('');
$("#" + classUpdateDiv).hide();
}
Like I said, if I have normal selectors in the function, it works as intended. But as of right now, I'm just stumped as to whats wrong.
Thanks a bunch!
classDiv is a jquery object not the ID of the element. So when you use this
$("#" + classDiv).html(data);
That's not working as expected.
Try
classDiv.html(data);
Your function should be like this:
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: {"name": className.val(), "info": classDesc}
success:function(data){
classDiv.html(data);
}
})
$("#"+classDesc).val('');
classUpdateDiv.hide();
}
because you already passed jquery objects (not strings) to your function, except for classDesc.
Hope this helps. Cheers