How to dynamically change text with javascript - javascript

I am adding a "like" feature to my screenshot gallery. I have successfully worked it out to change color to red when someone likes... and go back to gray when unlike... and then a php script handles all the DB magic.
But I can't wrap my head around how to change the actual text value shown; i.e. if someone likes, change the text from 10 to 11. If they unlike, change from 2 to 1, etc.
Can anyone suggest an approach to look into?
These are my javascript & html snippets if they help. The text in the HTML I want to change here is represented by "$row['Likes']"
$(".ajax-unlike").submit(function(){
var refid = $(this).find('input[name="refid"]').val();
var data = {
"action": "unlike"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "galleryajax.php", //Relative or absolute path to response.php file
context: document.getElementById(refid), //!! ADD THIS
data: data,
success: function(data) { //!! REMOVE refid FROM HERE
$(this).removeClass("thumb-comment-red", 1000);
}
});
return false;
});
<span class="thumb-comment" id="like'.$row['GalleryID'].'">
<form class="ajax-like" method="post" accept-charset="utf-8">
<input type="hidden" name="mcname" value="'.$user->profile_fields['pf_minecraftname'].'" />
<input type="hidden" name="galleryid" value="'.$row['GalleryID'].'" />
<input type="hidden" name="refid" value="like'.$row['GalleryID'].'" />
<input type="hidden" name="likerswithoutthisuser" value="'.str_replace($user->profile_fields['pf_minecraftname'],"",$row['Likers']).'" />
<button type="submit" style="border: 0; background: none;">
<i class="fa fa-heart"></i>
'.$row['Likes'].'
</button>
</form>
</span>
new code for comment down below
//Look for forms with "like" class
$(".ajax-like").submit(function(){
var refid = $(this).find('input[name="refid"]').val();
var btnrefid = "button#" + refid;
var formrefid = "form#" + refid;
var data = {
"action": "like"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "galleryajax.php", //Relative or absolute path to response.php file
context: document.getElementById(refid),
data: data,
success: function(data) {
$(this).addClass("thumb-comment-red", 1000);
$(btnrefid).html("<i class='fa fa-heart'></i> " + data["newlikes"]);
//Now stop further changes from recording based on submissions from this specific form
$(formrefid).submit(function(){
alert("You have already liked or unliked this screenshot. Please reload the page if you want to change your mind.");
});
}
});
return false;
});

Have a look at innerHTML like:
document.getElementById("demo").innerHTML = "value";
Or JQ way
$(selector).html("value");

success: function(data) { //!! REMOVE refid FROM HERE
$(this).removeClass("thumb-comment-red", 1000).innerHTML="UR New TEXT HERE";
//can even use $(element).text("text") or $(element).html("<span>TEXT</span>") like any html elements can be added according to requirement if you plan to use jquery//
}

Related

upload a form's file and text data to PHP using jQuery and AJAX

Good morning. I'm trying to make the form submission of a message more fluid avoiding the reload of the page for the sending of it. Since the message may be text or image, I need to send both of them to a PHP page for upload. I'm using this code in the html page:
<form id="newmessage" enctype="multipart/form-data">
<textarea form="newmessage" id="messagetext" name="messagetext" ></textarea>
<input type="submit" name="submit" value="send" onclick="return newMessage();">
<input type="file" accept="image/*" id="image" name="image">
</form>
<script>
function newMessage(){
var messagetext = document.getElementById("messagetext").value;
var image = document.getElementById("image").value;
$.ajax({
type:"post",
url:"new_message.php",
data:
{
"messagetext" :messagetext,
"image" :image,
},
cache:false,
success: function(html) {
document.getElementById("messagetext").value = "";
}
});
return false;
}
</script>
As you can see, I'm allowing users to type in the textarea or upload a file. When they submit the form, the newMessage() method is invoked and sends image and messagetext to new_message.php, which process them:
// new_message.php
$messagetext = $_POST["messagetext"];
$image = $_FILES["image"]["tmp_name"];
if((!empty($messagetext) || isset($image))) {
if(!empty($messagetext)) {
// create text message
} else if(isset($image)) {
// create image message
}
}
When I write a text message it works perfectly, but it doesn't send anything if it's image. Maybe the image variable in AJAX is not taking the file properly. I excuse if this question is unclear, but I'm a beginner in StackOverlow and I'm open to edits. Thanks for all replies.
can you try this. you don't need to worry about the file and message in textarea. Make sure you have added jQuery.
$("#newmessage").on("submit", function(ev) {
ev.preventDefault(); // Prevent browser default submit.
var formData = new FormData(this);
$.ajax({
url: "new_message.php",
type: "POST",
data: formData,
success: function (msg) {
document.getElementById("messagetext").value = "";
},
cache: false,
contentType: false,
processData: false
});
return false;
});

How can I loop over form data using serialized (jQuery / Ajax)

I'm trying to get post id and insert it into database after user click on add to favorite button.
The problem that all the post are return id 30 which is the last id in the database.
My php/html code
while($row = mysqli_fetch_array($get_posts)) {
<i style="float:right;" class="fa fa-pinterest-square">
<form id="pin_post" method="post"> ';
if (isset($_SESSION['user_id'])){
<input type="hidden" value="'. $_SESSION['user_id'].'" name="user_id" />
}
<input type="hidden" value="'.$row['post_id'].'" name="post_id[]" />
</form>
</i>
The jQuery / Ajax code
<script>
$(document).on("click",".fa-pinterest-square",function(e) {
$.ajax({
url: "includes/test.php",
type: "POST",
data: $('#pin_post').serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
I'm getting last id in the database when I click any post.
Please help me to get the id of each post when I click on the
Since you are using #pin_post when serializing it you will get the last hit when jQuery is looking for #pin_post. Either you should use a unique id or something like this
$(document).on("click",".fa-pinterest-square",function(e) {
var form = $(this).find('form'); //Since the form is child to <i>
$.ajax({
url: "includes/test.php",
type: "POST",
data: form.serialize(),
success: function(data) {
alert(data);
}
});
});

Give link to the text results in template

I was created a Django app and it produce IP address of corresponding domain name.
jQuery
$(document).ready(function() {
$("#button").click(function() {
var input_string = $("#forminput").val();
$.ajax({
url: "/ajaxexample_json",
type: "POST",
dataType: "json",
data: {
client_response: input_string,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function(json) {
$('#result').append('ServerResponse:' + json.server_response[][1]);
},
error: function(xhr, errmsg, err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
HTML
<form method="post" name="example form" >
{% csrf_token %}
<input name="example" id="forminput" type="text">
<input id="button" type="button" value="send to server"></input>
</form>
<div id="result">
</div>
Here if we enter "google.com" to the input form it produce output like this
ServerResponse:216.58.197.78
Here I want to get output in link format, ie
ServerResponse:link(216.58.197.78)
If I will click the link it directly go through 216.58.197.78 in localhost
Output
Simple fix is to set it as hyperlink. Replace the line from success function with below.
$('#result').html( ''+json.server_response[][1]+ '');
Using append will keep on appending to existing content. With multiple server calls you will get multiple links shown in result.
you can use this -
$('#result').append( 'ServerResponse:link(' + json.server_response[][1]+')');
replacing this in your existing code-
$('#result').append( 'ServerResponse:' + json.server_response[][1]);

Using jQuery or Javascript redirect to given page with a value

I have a dropdown, on its change it should redirect to a page with the dropdown's value say as a POST
I tried something like this:
$(document).ready(function() {
$('some_dropdown').change(function() {
var id = $(this).val();
var datastring = 'id=' + id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
window.location.href("xyz.php");
}
});
});
});
On the xyz.php page:
if ($_POST['id']) {
Blah Blah..
}
It's not recognizing that id value on the xyz page. I want it's value on the redirected page.
Edited - To make things more clear, I tried out to print the xyz.php's contents on my original page (instead of redirecting) like this -
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
FYI, "somediv" was <div class="somediv"></div> in my original page(no-redirecting) and it worked!! It could identify the id. Some how can't work it out with redirecting. It can't identify the id.
Edited --
Last thing, if I don't redirect and use
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
The data loads perfect, my question is can I make some changes in the dynamically loaded textboxes and insert them in the database
If you have to make a post request can make it by appending a virtual form.
Here is the code for that.
$(document).ready(function() {
$('[name="some_dropdown"]').change(function() {
var mval = $(this).val(); //takes the value from dropdown
var url = 'xyz.php'; //the page on which value is to be sent
//the virtual form with input text, value and name to be submitted
var form = $('<form action="' + url + '" method="post">'+
'<input type="text" name="id" value="' + mval + '" />'+
'</form>');
$('body').append(form); //append to the body
form.submit(); //submit the form and the page redirects
});
});
and on PHP
if(isset($_POST['id'])){
echo $_POST['id'];
}
Your datastring should be key value pair. Like this.
var datastring = {'id':id};
you have few mistakes in your code so your correct code will be like this
$('.some_dropdown').change(function(){
var id = $(this).val();
var datastring = 'id='+id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html){
window.location.href= "xyz.php?"+datastring+"";
}
});
});
});
and php code
if(isset($_GET['id'])){
Blah Blah..
}

Checking text of individual divs and changing content

I have repeats of the same code multiple times because of my PHP echoing the content out, and I want to interact with each div separately. It's hard for me to explain, but here's an example of the code repeated just twice. Hopefully it fully represents what I actually have...
<form id="favorite"><div id="images"><input type="submit" style="background-image: url(grey.png);" onclick="submit" value="" /></div></form>
<form id="favorite"><div id="images"><input type="submit" style="background-image: url(grey.png);" onclick="submit" value="" /></div></form>
javascript:
$('#favorite').submit(function() {
var url = document.URL;
if(document.getElementById("images").innerHTML.indexOf("grey") != -1) {
$.ajax({
type: "POST",
url: url,
data: $("#favorite").serialize(),
success: function(data)
{
$('#images').html("<input type=\"submit\" style=\"background-image: url(red.png);\" onclick=\"submit\" value=\"\" />");
}
});
} else {
$.ajax({
type: "POST",
url: url,
data: $("#favorite").serialize(),
success: function(data)
{
$('#images').html("<input type=\"submit\" style=\"background-image: url(grey.png);\" onclick=\"submit\" value=\"\" />");
}
});
}
return false;
});
So, if I were to click the image for the top form, it works perfectly. It will run the PHP and it will change the image without refreshing. If I click the bottom image, it will run the PHP, but it will refresh the page and it won't change the image. So it seems like if I click the bottom one, it doesn't like the Javascript. I don't know if it's because it's looking at both of the forms since they have the same ID (which I can't fix since it could possibly have hundreds), or something else, which I don't see any problems. I'm guessing there's some way to do it using "this", but I'm unsure of how to use it.
Thank you!
You need to change a few things. Your selector to bind the event only matches the first occurrence of #favourite as id's should be unique. You get around this by using an attribute equals selector.
In addition, ensure you select each sub-element in the context of the current form, similar to this:
$('[id=favorite]').submit(function () {
var $form = $(this); // the current form
var $image = $('#images', $form) // get images element in the context of current form
var url = document.URL;
if ($image.html().indexOf("grey") != -1) {
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), // use current form, don't re-select
success: function (data) {
$image.html("<input type=\"submit\" style=\"background-image: url(red.png);\" onclick=\"submit\" value=\"\" />");
}
});
} else {
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), // use current form, don't re-select
success: function (data) {
$image.html("<input type=\"submit\" style=\"background-image: url(grey.png);\" onclick=\"submit\" value=\"\" />");
}
});
}
return false;
});

Categories

Resources