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]);
Related
I am trying to send user text from a web page to my flask app to run a script on the user text and then return a result. The problem I am having is that the text isn't appearing on the server (flask_app.py) side. Here is the .js that is supposed to be sending the text (index.js):
$(document).ready(function(){
console.log('I have loaded');
//Grab DOM elements to use later
analyzeTextButton = $("#analyze-button");
analyzeTextButton.click(function() {
// get text
text = $("#user-text").val();
//console.log(text); //This part works
$.ajax({
type: "POST",
url: "analyze",
dataType: "json",
data: {
text
},
success: function(results, results2, verbs) {
text = results.text;
console.log("Success!");
console.log(verbs);
}
})
})
Here is the Flask app that is trying to receive it. I've tried several different versions (from other Stack Overflow questions and various tutorials) but none of them work. They are labeled content1-5.
flask_app.py:
#app.route('/analyze', methods=['POST'])
def analyze():
print('You made it to analyze', file=sys.stderr) #This gets printed
content = request.get_json(silent=True)
content2 = request.json
content3 = request.get_json()
content4 = request.form.get('html', '')
content5 = request.form['contents']
print(content, file=sys.stderr) #These all return "None"
print(content2, file=sys.stderr) #Trying to make them return user text
print(content3, file=sys.stderr)
print(content4, file=sys.stderr)
print(content5, file=sys.stderr)
text = "The text is not being found"
results = my_script(content) #Run a script on whichever works
return jsonify({'results': results})
Here is the page that is trying to send the information (index.html):
<div class="row">
<form role="form" method='POST' action='#'>
<textarea class="form-control" id="user-text" name="contents" placeholder="Enter a comment"></textarea>
<button type="button" id="analyze-button" class="btn btn-default">Not Working Button</button>
<button type="submit" id="analyze-button2" class="btn btn-default">Working Button</button>
</form>
EDIT: When I look in my browser, I see that POST appears to be sending the correct string: "here+is+my+text"
data: {
text
}
should be proper JSON,it should be something like
data: {
"value":text
}
where value is key and text variable is value.
The request needed to specify that the text was html:
$.ajax({
type: 'POST',
url: "analyze",
data: {html:text},
dataType: 'json',
success: function (ret) {
alert('JSON posted: ' + JSON.stringify(ret));
}
});
On the flask app the request can be read with this line:
content4 = request.form.get('html', '')
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);
}
});
});
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//
}
I am trying to submit a form using an image input type. The ajax request performs fine, and I get a response back from my php script. My problem is that I want the image button to change it's image when it is submitted (and it wasn't doing that). The firebug console said that form.pic is undefined, and the image does not get updated. Any Ideas why?
javascript/jquery
function new_user(form){
var url = "attendance.php";
var dataString = "status="+form.astatus.value;
dataString = dataString+"&id="+form.mark_attend.value;
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(data) {
form.pic.src = data; //Error here
},
error: function(jqXHR, textStatus, errorThrown){ console.error("error: " + textStatus, errorThrown);}
});
return false;
}
HTML
<form method="POST" onSubmit="return new_user(this);" >
<input type="hidden" value="attended" name="astatus" />
<input type="hidden" value="idKey" name="mark_attend" />
<input type="image" src="greencheck.png" name="pic" />
</form>
$(form).find('input[name="pic"]').attr('src', data);
This, I think, is the cleanest way to do this considering that you are using jQuery.
On my site i am loading shopping products with the "add to cart"-button dynamically with a jquery ajax call. For the shopping cart itself, I use jcart, jquery plugin.
When I then add an item to the cart, jcart calls a php-file with ajax and POST. All works fine, the products are correctly added to the cart, but the page reloads every time I add an item to the cart.
When I don't use the ajax call to load the products (e.g. load them directly in the page), all works fine, so there must be a conflict somewhere.
Any clues?
This is my products-function and the html.
...
<script>
function loadProducts(str) {
$.ajax({
type: 'GET',
async: true,
url: 'ajax/load.php',
data: {'max-id' : str},
cache: false,
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
});
}
</script>
<script>
$(document).ready(function() {
var n = '';
loadProducts(n);
});
</script>
<script src="jcart/js/jcart.js"></script>
</body>
</html>
The jcart-Plugin with its ajax-call can befound here:
http://conceptlogic.com/jcart/standalone-demo/jcart/js/jcart.js
Here are the functions from jcart.js.
$.ajaxSetup({
type: 'POST',
url: path + '/relay.php',
cache: false,
success: function(response) {
// Refresh the cart display after a successful Ajax request
container.html(response);
$('#jcart-buttons').remove();
},
error: function(x, e) {
...
}
});
...
function add(form) {
// Input values for use in Ajax post
var itemQty = form.find('[name=' + config.item.qty + ']'),
itemAdd = form.find('[name=' + config.item.add + ']');
// Add the item and refresh cart display
$.ajax({
data: form.serialize() + '&' + config.item.add + '=' + itemAdd.val(),
success: function(response) {
// Momentarily display tooltip over the add-to-cart button
if (itemQty.val() > 0 && tip.css('display') === 'none') {
tip.fadeIn('100').delay('400').fadeOut('100');
}
container.html(response);
$('#jcart-buttons').remove();
}
});
}
...
// Add an item to the cart
// is called from the submit-buttons within each product picture
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
The "loadProducts()" function puts this into #products container for each item:
<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="SDK12345" />
<input type="hidden" name="my-item-name" value="Product Name" />
<input type="hidden" name="my-item-price" value="1.00" />
<input type="hidden" name="my-item-qty" value="1" />
<ul>
<li><img src="product-image.jpg"/></li>
<li>1.00 Dollar</li>
</ul>
<input type="submit" name="my-add-button" value="Add to cart" class="button" />
</fieldset>
</form>
I'm guessing you are calling the loadProducts() function in a binded click action on your add to cart button. If you are using an element with a default click behavior. You might want to prevent that with a 'return false;' on the last line of your binded click function.
like this:
$('a.addtocart').bind('click', function(){
//logic here (ajax)
return false;
});
After your success function there's also a comma that might get messy in IE:
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
Remove the comma
I think there's an error in your ajax call, try to work it out... i cant see the logic of your php file that adds products to your basket. but if you want to send the data of your form (quantity, itemid), serializing your form data should be enough. No need to pass extra get variables.
function add(form) {
$.ajax({
data: form.serializeArray(),
url: 'yourfile.php',
success: function(response) {
// logic
}
});
}
Ok, I found the solution.
As the forms are loaded via ajax, they were no correctly interpreted by jcart.js (though the functions all worked fine for themselves).
"bind" didn't work, but "live" fixed it:
$('.jcart').live('submit',function(e) {
add($(this));
e.preventDefault();
});