Hy,
I have a live username validation using ajax :
<td id="user_process_live"><input type="text" id="user_live_ver" name="user" /></td>
abnd the following java :
$("input#user_live_ver").blur(function() {
var username=$(this).val();
var dataString = 'username=' + username;
$.ajax({
type: "POST",
url: "ajax/login_ajax.php",
data: dataString,
cache: false,
success: function(html) {
$("td#user_process_live").html(html);
}
});
});
The login_ajax.php returns the same <input type=text id=user_live_ver name=user /> but with different styles applied (background-color and border-color) : red if username already exist and green if user does not exist ...
The problem is the script does this just one time .. just one .blur() ...
If i remove the .ajax({ ... etc }); and insert alert(dataString); every time i click out that input the alert() is triggered but not the same for the .ajax() ...
What seems to be the problem ? Thanks a lot
The problem is that you are replacing the input after the first ajax request returns so your blur event isn't bound anymore. Try using delegate to bind your event:
var process_live = $("#user_process_live");
process_live.delegate("#user_live_ver", "blur", function() {
var username = $(this).val(),
dataString = {'username': username};
$.ajax({
type: "POST",
url: "ajax/login_ajax.php",
data: dataString,
cache: false,
success: function(html) {
process_live.html(html);
}
});
});
When you add the html string back in with the success function, you loose the event handler attached to the input element.
Maybe try changing the styles on the input depending on what you get back in the success function rather than replacing the HTML entirely.
success: function(result) {
if (result) {
$("input#user_live_ver").addClass("valid");
} else {
$("input#user_live_ver").addClass("invalid");
}
}
All your PHP script has to do now is return true if the username is valid and false if not.
Use json_encode($result)
Maybe the reference for blur event was lost after the html replace, I dont try so I dont know.
but did you try to set the blur event again?
This is probably happening because you're removing the element that $("input#user_live_ver") references and then adding a new one to the DOM, so that blur event binding goes away.
You have two options:
Use .live() to bind the event so that it also binds to future matching elements. More info here.
Don't replace the DOM element in the response from the AJAX resource. Just re-style it. (This will offer slightly better performance as well.)
java*SCRIPT*... they are VERY different things! And, instead of returning an input, why not return a success or fail message and update the class accordingly? Saves a few DOM calls
Related
I have a website where you can edit inline by clicking the table cell. After click and type the string, you need to press enter in order to update the data. My problem is, I want to automatically send the data without pressing enter. What key event should i use with this one? onkeypress? and how would i remove the enter key event?
$('td.edit').keydown(function(event){
arr = $(this).attr('class').split( " " );
if(event.which == 13)
{
$.ajax({type: "POST",
url: "../../controller/inline.php",
data: "value="+$('.ajax input').val()+"&rownum="+arr[2]+"&field="+arr[1]+"&ids="+'<?php echo isset($_POST['frmID'])?$_POST['frmID']:$_GET['id']; ?>'+"&dFrom="+'<?php echo isset($_POST['frmDateFrom']) ? $_POST['frmDateFrom']:date('n\/j\/Y', strtotime("-15 days")); ?>'+"&dTo="+'<?php echo isset($_POST['frmDateTo'])?$_POST['frmDateTo']:date('n\/j\/Y'); ?>',
success: function(data){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}});
}
});
Well, I experienced same situation too.
You really need to save automatically?
Simple solution is 'focusout()' or 'onBlur()' maybe.
But it is too risky.
It means just single miss click or miss key press firing save event.
If you have multiple columns to input somthing.
Don't do that.
But just single column, try 'onBlur()' or 'focusout()'
I'll waiting your wise solution. :3
I believe an onBlur event is what you're looking for. http://api.jquery.com/blur/
What you can do (although I wouldn't recommend it) is to use a setTimeout to save the data. This way the user can keep on typing without saving, but once he stops typing for a second or so it will save the data.
Take a look at the example here (http://jsfiddle.net/G2LxD):
var timer;
$('input').keyup(function() {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
$.ajax({
type: "POST",
url: "../../controller/inline.php",
data: "[your-data]",
success: function(data){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
}, 1000);
});
I'm working on a small project that requires Ajax to fetch data from database and update a page. The query to the database is built on the fly by the user and the query strings build like a chain. So for example the first item of the chain effects the next and the next and so on. Therefore it creates a list of post variables that I can't "know" ahead of time. I figured this would be a pretty simple thing to achieve however it's proving not to be. Here is my issue.
When I use a .changed event and try to seralize the form before posting it. I get nothing but empty strings. I've noticed that if I hard code the post variables everything works just fine. Is there something I'm missing? Does .changed not have a seralize method?
I am also using a CURL bridge since the server with the data is on another domain. I don't think that is causing any issues though. I believe it has to do with my event choice.
Here is the code:
$('#selector').change(function() {
$.ajax({
type: "post",
dataType: 'json',
url: "/pages/curlbridge.php",
data: $("#queryform").serialize(), //"select=all&date=2013"
success: function(data)
{
console.log(data);
var resultset = data;
}
});
Was Asked to attach the HTML. It's just a simple form
<form id="selector">
Select: <input type="text" id="select" />
Date: <input type="text" id="date" />
</form>
<br />
I agree with #m1ket that #queryform doesn't exist, although you can't use serialize() on a single input element, so the following line is incorrect:
data: $(this).serialize(), //"select=all&date=2013"
Perhaps what you can do is this (which gets all the data in the form the #selector is a part of):
data: $(this).closest('form').serialize(), //"select=all&date=2013"
EDIT
My bad, I didn't pay attention to the HTML posted in the original question
Scope issue maybe? Does this work:
$('#selector').change(function() {
var formData = $(this).serialize();
$.ajax({
type: "post",
dataType: 'json',
url: "/pages/curlbridge.php",
data: formData, //"select=all&date=2013"
success: function(data)
{
console.log(data);
var resultset = data;
}
});
});
$("#queryform") does not exist. Your jQuery should read like this:
$('#selector').change(function() {
$.ajax({
type: "post",
dataType: 'json',
url: "/pages/curlbridge.php",
data: $(this).serialize(), //"select=all&date=2013"
success: function(data)
{
console.log(data);
var resultset = data;
}
});
});
Also, are you using .change() because you want to submit the AJAX request every time a user enters a key?
I'm not sure if there is any way to do this or not, but this would solve so many of my problems if there is a simple solution to this.
What I need/want to be able to do is return HTML and JSON in my success of ajax request. The reason being, I want to request a file and return all of that page, but I also want to be able to return a specified set of information from the page in json, so I can use it for other things.
This is what I'm doing now:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
}
});
This is what I'd like to be able to do:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
$("title").html(json.PageTitle)
}
});
on the page that is being returned, I would specify what I want the title to be. (For instance, if it's a profile, I would return the user's name)
HTML and data wrapped in JSON
You can do it by returning a 2 element JSON array.
The first element contains HTML and the second element contains another JSON array with the data inside. You just need to unwrap it carefully without breaking anything.
Serverside
$html = '<div>This is Html</div>';
$data = json_encode(array('page_title'=>'My Page'));
$response = array('html'=>$html, 'data'=>$data);
echo json_encode($response);
Clientside
//Ajax success function...
success: function(serverResponse){
$("body > .container").html(serverResponse.html);
var data = JSON.parse(serverResponse.data);
$("title").html(data.page_title)
}
Note 1: I think this is what #hakre meant in his comment on your question.
Note 2: This method works, but I would agree with #jheddings that its probably a good idea to avoid mixing presentation and data. Coding karma will come back to bite.
Trying to mix the retun value to contain presentation and data seems like a potential for confusion. Why not split it into two calls and fetch the data on success of the other?
Something like:
$.ajax({
type: "POST",
url: "inc/"+view_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html) {
$("body > .container").html(html);
$.ajax({
type: "POST",
url: "inc/"+data_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(json) {
$("title").html(json.PageTitle);
}
});
});
You also have the option of including the data in html5 data attributes
For instance, if you're returning a list of Animals
<ul id="ZeAnimals" data-total-animals="500" data-page="2">
<li>Cat</li>
<li>Dog</li>
...
</ul>
You can then collect the data you require using
$('#ZeAnimals').data('total-animals')
Sometimes separating your request into two different ajax calls makes sense also.
You may use a library that does that automatically, like http://phery-php-ajax.net. Using
Phery::instance()->set(array(
'load' => function(){
/* mount your $html and $json_data */
return
PheryResponse::factory()
->json($json_data)
->this() // points to the container
->html($html);
}
))->process();
$(function(){
var $container = $('body > .container');
$container.phery('make', 'load'); // or $container.phery().make('load')
$container.bind('phery:json', function(event, data){
// deal with data from PHP here
});
$container.phery('remote');
});
You may, as well, use phery.views to automatically load a portion of the site automatically, without having to worry about client-side specific code. You would have to put a unique ID on the container, container in this example:
$(function(){
phery.view({
'#container': {}
});
});
Phery::instance()->views(array(
'#container' => function($data, $params){
/* do the load part in here */
return
PheryResponse::factory()
->render_view($html)
->jquery('.title')->text($title);
}
))->process();
ok, i have these two input fields where a user puts in two twitter names. When the submit button is pressed, both names should be send to a .php file with the POST method that checks if both usernames exsist on twitter.
Sending and receiving the answer for one value already works, but how can i also add the second? I already have this:
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
**data: {'user1' : $('#user1').val() },** //how to append user2?
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
the fields in the form:
<td><input type="text" name="user1" id="user1"/></td>
<td><input type="text" name="user2" id="user2" /></td>
and this is how the values should be able to be cathed in the .php:
$user1 = $_POST['user1'];
$user2 = $_POST['user2'];
So the question really is: how can I append the second username to the above jQuery POST function?
p.s. I am starting with javascript and jQuery, how do you guys work with this as no error messages are shown ever.. is there an environment/programm where I get debugging help with javascript?
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
It's a simple enough extension-- just follow the same pattern.
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
That said, jQuery does also have a .serialize() function that you could apply on the containing form, which automatically serializes the whole form. This could prove useful for you.
EDIT: It's worth mentioning that the jQuery selectors above look on the id for the name "user1" (etc.), whereas the PHP script expects the form elements' name to be "user1" (etc.). Here you have them as the same thing.
A more reliable jQuery selector that would allow you to always use the name in both jQuery and PHP is simply to use an attribute selector in jQuery:
$('input[name="user1"]').val()
This will catch any <input> element with the name attribute set to "user1".
You're probably looking for serialize. Your code would look something like this:
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form").serialize(),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
If you're sure you don't want serialize you could try this:
data: {'user1' : $('#user1').val(), 'user2' : $('#user2').val() }
As for your PS, check out Firebug and Webkit developer tools.
You actually don't even need the serialize function. If you just select your form, all form elements will be passed. This way if you just add another form element, like another textbox, it will all be passed in your ajax call.
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form"),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});
the ones you should always set are url,success and data if needed, please read The Documentation for more information.