jQuery: jQuery.ajax() and the problem with anchors - ajax

Hi all I have a problem with anchors and dynamic content loaded thought $.ajax().
Let suppose this is my jQuery code:
$("a.false").live("click", function() {
var data = $(this).attr("href");
$("div#text").hide("fast");
$("div#loader").show("fast");
$.ajax({
type: "GET",
url: "callback.php",
data: data,
dataType: "html",
cache: false,
success: function(result){
$("div#loader").hide("fast");
$("input#data").val(data);
$("div#text").html(result);
$("div#text").show("fast");
}
});
});
I think everybody knows what means this code and I'll no explain it.
callback.php answer is:
<div class="name">
<div class="replic_id">
<input type="hidden" id="replica_1" name="replica_1" value="1" />
<a id="rp1">#1</a>
</div>
<div class="names">Name 1</div>
<div class="replicas">Replica 1</div>
</div>
<div class="name">
<div class="replic_id">
<input type="hidden" id="replica_2" name="replica_2" value="2" />
<a id="rp2">#2</a>
</div>
<div class="names">Name 2</div>
<div class="replicas">Replica 2</div>
</div>
And now I javascript variable "data" value is = "movie=scarymovie#255" the page must start from anchor #255 but it starts from the begin. How I can fix it to start from anchor 255, no from begin?
with regards ;]
Fixed: Correct a IDs

It is easier to send back the anchor as its own value and just use:
window.location.hash = '#255';
It is worth noting that even though it may work, 255 is not a valid value for an ID attribute in HTML: What are valid values for the id attribute in HTML?
Edit: fixed a typo in the variable name

Related

Get data with AJAX and save them as variables

I'm totally new to AJAX and I don't seem to know the best way to search what I'm looking for. So trying to explain it here.
I have a table which lists my users. I want to be able to edit any row of the table without refreshing. So I added a button for each row, by clicking which you'll be able to edit that user with the help of Bootstrap modals.
There's this button which initiates the action:
<span class="updateInfo" user-id="<?php echo $users_array['id']; ?>" data-target=".editInfo" data-toggle="modal"><i class="fa fa-pencil" ></i></span>
$users_array is an array fetched earlier from a table in database. The table also has 'id, name, email, phone' as columns.
So, what I basically have in my JS code is this:
jQuery(document).ready(function() {
$('.updateInfo').click(function(){
var userID = $(this).attr('user-id');
$.ajax({
url: "edit.php",
method: "POST",
dataType: 'json',
data: {
selected_user_id: userID,
},
success: function(data) {
// I don't know what to do here :(
}
});
});
});
The codes included in edit.php file are as followed:
$user_id=$_POST['selected_user_id'];
$get_user=mysql_query("SELECT * FROM users WHERE id='$user_id'");
$user_array=mysql_fetch_row($get_user);
echo json_encode($user_array);
I didn't put the codes that establish database connection and the like, since they're basics and work fine.
I have several problems here:
I have no idea if the way I've written the code so far is correct.
How I'm supposed to get those results and save them as variables for a later use.
I don't know if I can use the newly created variables as placeholders or pre-defined values in a modal that exists in the original file.
P.S: The modal has a simple form with simple inputs for name, email and phone number:
<div class="modal fade editInfo" tabindex="-1" role="dialog" aria-labelledby="myNote" data-backdrop="static" aria-hidden="true">
<form method="POST">
<input name="fullname" value="" />
<input name="email" value="" />
<input name="phone" value="" />
</form>
</div>
set Id for each html element
jQuery(document).ready(function() {
$("#fullname").val("USer One ");
$("#email").val("User#gmail.com");
$("#phone").val("987654");
$('.updateInfo').click(function(){
var userID = $(this).attr('user-id');
$.ajax({
url: "edit.php",
method: "POST",
dataType: 'json',
data: {
selected_user_id: userID,
},
success: function(data) {
console.log(data);
$("#fullname").val(data.fullname);
$("#email").val(data.email);
$("#phone").val(data.phone);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="modal fade editInfo" tabindex="-1" role="dialog" aria-abelledby="myNote" data-backdrop="static" aria-hidden="true">
<form method="POST"> <input id="fullname" name="fullname" value="" /><input id="email" name="email" value="" /> <input id="phone" name="phone" value="" /> </form>
</div>
and then bind like this :

can i refresh a table from presently showing model-popup

I need to reload a table or div inside a model popup continuously, i failed with my code can you help me....
i tried with ajax ..code is below but its is not updating chats (i am doing a chat task)
**My Ajax code to check new message is or not**
function check_msg()
{
$.ajax({
type: "POST",
url: "<?php echo site_url('member/check_message')?>/",
datatype: "JSON",
success: function(data) {
data = JSON.parse(data);
if(data.MsgStatus == "1")
{
$('#newchat').ajax.reload();
} });}
**HTML**
<div class="modal-body form">
<form action="#" id="chatform" class="form-horizontal">
<input type="hidden" value="" name="UserId"/>
<div class="form-body">
<div class="container" id="container">
<table id="newchat">
<div class="Scroll" id="Scroll">
<div id="messagesout"></div>
</div> </table> </div</div>
function reload_table()
{
table.ajax.reload();
}
Use this code in your ajax and call it

PHP doesnt read textarea content sended by ajax call

i'm dealing with this ajax call:
HTML:
A form has a textarea in which user can type some text
<div id="step-3">
<h2 class="StepTitle">Testo</h2>
<form id="text" class="form-horizontal form-label-left">
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Textarea <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea id="textarea" name="testo" data-parsley-required="true" class="form-control col-md-7 col-xs-12"></textarea>
</div>
</div>
</form>
<ul id="error3_ul" class="list-unstyled">
<li id="error3_li"></li>
</ul>
</div>
JS:
This function is called by smartwizard. When user types some text and pushes button, an ajax call starts to do a server side check before to effectively insert text into db.
function onFinishCallback()
{
var data = $('#textarea').val();
$.ajax({
method: 'post',
data: data,
dataType: 'html',
url: "include/library/pull_sim.php",
success: function(result) {
successmessage = 'Data was succesfully captured';
$("#error3_li").text(result);
},
});
}
PHP:
Php receives the posted textarea value, check if a similar_text is already into db and if yes, it alerts that to user by the ajax call result.
if((!ISSET($_POST['testo'])))
$val='';
else
$val=$_POST['testo'];
$q_sim='select nciarfata from nciarf.nciarfata';
$s_sim=mysqli_query($conn,$q_sim);
$n_sim=mysqli_num_rows($s_sim);
if ($n_sim>0)
{
$simil=array();
for ($i=0;$i<$n_sim;$i++)
{
$rou=mysqli_fetch_row($s_sim);
similar_text($val, $rou[0], $percent);
if ($percent>=95.0)
{
array_push($simil,$rou[0]);
}
}
echo"val=$val, rou[0]=$rou[0], percent=$percent";
}
Question:
In my opinion something goes wrong in server side, probably in the 1st if.
Php doesnt recognized the posted value and then assign val="" instead of real text typed by user before..
Why?
Thanks for helping me.
I find the solution here:
Can't figure out why PHP not receiving POST data from $.ajax call
It wasn't a textarea issue but an ajax jquery one (data option).

Jquery Ajax call to servlet

I am trying to make an Ajax call using JQuery to a servlet that returns a JSON object.
In the JSP page I have a form, at first I didn't know how the get the data from the form,
then I found .serialize.
I have the following JavaScript:
$(document).ready(function() {
$("#submit").click(function blabla() {
var formData = $('form').serialize();
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
});
});
});
The information comes from the following form:
<form method= post">
<div class="searchCiteria">
<div id="searchValueBlock1">
<div><span class="label">Case ID:</span><input type="text" name="messagecaseid" size="25"/></div>
<div><span class="label">Onderwerp:</span><input type="text" name="messagesubject" size="25" /></div>
<div><span class="label">Afzender:</span><input type="text" name="messagesender" size="25"/></div>
<div><span class="label">Ontvanger:</span><input type="text" name="messagereceiver" size="25"/></div>
</div>
<div id= "searchValueBlock2">
<div><span class="label">Datum:</span><input type="text" name="date1" size="25"/></div>
<div><span class="label"></span><input type="text" name="date2" size="25"/></div>
<div class="submit">
<input type="submit" value="Search">
</div>
</div>
</div>
</form>
When I use the action parameter in the form the servlet repondes like it should.
But I can't seem to get the Ajax call to work.
What am I doing wrong?
you must add the success param to ajax function
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
The default behavior of the submit button is to POST the form, which will redirect the user to a URL of the action attribute ond the form. When you don't(which you should...) have an action attribute it will reload the page. To prevent the page from reloading you need to prevent the default behavior by returning false at the end of your $("#submit").click function.

How to trigger Ajax with flash buttons?

I'm working on something where there are 2 links which triggers some Ajax. However I need to turn the links into Flash buttons (AS3). I've never worked with Ajax before, and I have no idea how this can be done.
Edit:
The Ajax:
<script>
$(document).ready(function() {
$('a.catlink').unbind('click').click(function(e)
{
e.preventDefault();
var link = $(this);
var inputs = [];
var cat_type = $(this).attr('href').replace('#', '');
link.attr('disabled', 'disabled');
inputs.push('cat_type=' + escape(cat_type));
$.ajax(
{
type: "POST",
cache: false,
dataType: "html",
url: window.location.href,
data: inputs.join('&'),
success: function(html)
{
var json = $.parseJSON(html);
if (json['status'] == 1)
{
$('div.listing').html(json['html']);
}
link.removeAttr('disabled');
}
});
});
});
</script>
The HTML
<h1 class="section-head">Products
// **The 2 links*** //
<a class="catlink" href="#cinema">cinema</a> <a class="catlink" href="#smart">smart</a></h1>
<div class="listing">
<ul class="listing">
{foreach from=$products item="product_info"}
<li class="clearfix">
<div class="inner-left">
<img height="68" width="90" src="{$product_info.image}" />
<h2 class="normal mt-5">{if $product_info.price != '0'}${$product_info.price}{else}Click for price ยป{/if}</h2>
</div>
<div class="inner-right">
<h3 class="mb-0">{$product_info.productName}</h3>
<p class="small mb-5"><span class="quiet">{$product_info.category}</span></p>
<p class="mb-15">{$product_info.description}</p>
<a class="button getprice" href="{$product_info.url}">Buy Now</a>
<br><br>
</div>
</li>
{/foreach}
</ul>
</div>
If you're going to use AS3 then you can use ExternalInterface.call() to call a JavaScript function on the page. Though, using Ajax may not be required if you're using AS3 because you can make use of the URLLoader class to do the same thing (call a PHP script and decode a result).
If you describe more accurately what you want to achieve then I shall provide some example code and clarify a little more.

Resources