JQuery, function does not see text field value - javascript

please don't judge my JS skills, I'm complete beginner in it. =))
So I have a function that register user, But I want to make "create_sample_user" button to fill text fields with some data. This way people can quickly check the website, without typing names, email and so on...
But the problem is: Register button works fine when I type username and all other fields by my self. But Doesn't work(I assume it just doesn't 'see' the values of the text fields) when I fill them with "create_sample_user" button.
function create_sample_user() {
var button = $("#create-sample-user");
button.click(function() {
var ranNum = 1 + Math.floor(Math.random() * 100);
var uname = 'Sample_'+ranNum;
$("#id_username").val(uname);
$("#id_email").val(uname+'#'+uname+'.com');
$("#id_password").val(uname);
$("#id_password2").val(uname);
});
}
function register_user() {
$("#register-user").click(function() {
$.ajax({
url: "/registration/register_user/",
type: "POST",
dataType: "text",
data: {
username : $("#id_username").val(),
email : $("#id_email").val(),
password : $("#id_password").val(),
password2 : $("#id_password2").val(),
},
success: function(data) {
parsed_data = $.parseJSON(data);
if (data) {
alert("User was created");
window.location = parsed_data.link;
}
else {
alert("Error");
}
}
});
});
}
THE ANSWER:
whole thing didn't work because of one character in this line of code:
`var uname = 'Sample_'+ranNum;`
For some reason _ character was the problem, and AJAX didn't want take it.
in other words:
var uname = 'Sample'+ranNum;
This line would do the trick :=)

Okay, replace your create_sample_user() method with this:
$(document).ready(function() {
var button = $("#create-sample-user");
button.click(function() {
var ranNum = 1 + Math.floor(Math.random() * 100);
var uname = 'Sample_'+ranNum;
$("#id_username").val(uname);
$("#id_email").val(uname+'#'+uname+'.com');
$("#id_password").val(uname);
$("#id_password2").val(uname);
});
}​);​
Also, try removing the function register_user() function wrapper.
This should do it. It should pop up the success alert box as well (I changed your AJAX URL to use the AJAX echo for jsFiddle):
http://jsfiddle.net/MQ6Cq/4/
UPDATES (since you posted your code - I will update this with bugs as I find them):
You have two $(document).ready() calls now - delete the first one (THIS WAS EDITED)
You have have to remove the lines function register_user() { and the closing brace from around the register user click handler
I made a tiny update to my earlier fiddle, just in case it helps with testing, and changed the request type to "GET". Open your browser's console (F12), right-click and turn on logging for XMLHttpRequests. Then run it and you will see that the AJAX is successfully transmitting the data. I don't know what is wrong with your other stuff but I don't have a server that I can test it on and I'm not getting enough feedback to know what's going on after you try each suggestion (or even if you're trying them). I just hope this helps you solve your problem.
Good Luck! :)

Your code should work. Here's a jsfiddle (simplified version of it)
If you look at the console, you'll see the data is well formatted.
The only thing I see in your code is that create_sample_user() is not called so the click event isn't applied to the button. But I guess you've just omitted to put it in the question
create_sample_user();
$('#register-user').click(register_user);
function create_sample_user() {
var button = $("#create-sample-user");
button.click(function() {
var ranNum = 1 + Math.floor(Math.random() * 100);
var uname = $("#id_username").val('Sample_'+ranNum);
$("#id_email").val(uname.val()+'#'+uname.val()+'.com');
$("#id_password").val(uname.val());
$("#id_password2").val(uname.val());
});
}
function register_user() {
data = {
username : $("#id_username").val(),
email : $("#id_email").val(),
password : $("#id_password").val(),
password2 : $("#id_password2").val(),
}
console.log(data);
}

$("#create-sample-user").click(create_sample_user);
$('#register-user').click(register_user);
function create_sample_user() {
var ranNum = 1 + Math.floor(Math.random() * 100);
var uname = $("#id_username").val('Sample_' + ranNum);
$("#id_email").val(uname.val() + '#' + uname.val() + '.com');
$("#id_password").val(uname.val());
$("#id_password2").val(uname.val());
}
function register_user() {
data = {
username: $("#id_username").val(),
email: $("#id_email").val(),
password: $("#id_password").val(),
password2: $("#id_password2").val(),
}
console.log(data);
}

Related

Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.
The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.
Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.
What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)
What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
url: "save.php",
method: "POST",
data: { name: name.value, email: email.value, telephone: telephone.value },
success: $("List").load(" List")
});
}
Thank you in advanced and if I need include further info don't hesitate to ask.
From this comment
as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam
I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)
I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.
Thanks!
(Won't let me mark as answered until 2 days)
I would first create an AJAX call inside a function which runs when the page loads to populate the list.
window.onload = populatelist();
function populatelist() {
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'populate'},
success: function(data) { $("#list").html("data"); }
});
}
Note: #list refers to <div id="list> and your list should be inside this.
I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
success: function() { populatelist(); }
});
}
list.php should look like this:
<?php
if($_POST['function'] == "populate") {
// your code to get the content from the database and put it in a list
}
if($_POST['function'] == "update") {
// your code to update the database
}
?>
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:
PHP:
function doLoadMails(){
//initialize empty variable
$mails;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("");
}
//some select, insert, whatever
$sql = "SELECT ... ... ... ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row, j is counter for rows
$j =0;
while($row_a = $result->fetch_assoc()) {
//for each row, fill array
$mails[$j][0] = $row_a["name"] ;
$mails[$j][1] = $row_a["mail"] ;
$mails[$j][2] = $row_a["language"] ;
$j++;
}
}
//if $mails has results (we added something into it)
if(isset($mails)){
echo json_encode($mails);/return json*/ }
else{
//some error message you can handle in JS
echo"[null]";}
}
and then in JS
function doLoadMails() {
$.ajax({
data: { /*pass parameters*/ },
type: "post",
url: "dataFunnel.php",
success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
console.log(data); //you can check what you get
if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
}
});
Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.
In your solution, you will probably need to echo the return code of the INSERT request.

redirect after alert message not working

this is a snippet of a js file>
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList',
type: 'POST',
data: {id: id, userT: usertype},
success: function(html){
$('[data-id='+id+']').parents('tr').remove();
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
as you can see there is an alert message after deleting a user from a list.
I want to refresh the page after ok on alert message is pressed so i added the line>
window.location.reload();
but it's not working, why is this? how can i fix it?
I've been trying to use alternative to this like
location.href = '....';
window.location = '/some/url';
but nothing seems to work!
this is in my admin.php, the code for deleting user from the database:
public function deleteUserFromList(){
if ((isset($_POST['id']) && (isset($_POST['userT'])))){
$rowId = $_POST['id'];
$userType = $_POST['userT'];
$result = array();
if($userType == 'front'){
$front = UserManager::getInstance()->getUser($rowId);
UserManager::getInstance()->deleteItem($front);
}else{
$back = UserBackManager::getInstance()->getUser($rowId);
UserBackManager::getInstance()->deleteItem($back);
}
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}
}
In order to simulate redirect in your browser try to:
Javascript way:
window.location.replace("http://stackoverflow.com");
jQuery way:
var url = "http://stackoverflow.com";
$(location).attr('href',url);
Try this and let me know it it works for you or not.
EDIT:
Inside ajax success. Try to close modal window and try to replace method.
EDIT 2:
Put this part of code inside of your document ready block and check is it fired or not if it is fired it means your form is reloading correctly.
$( window ).unload(function() {
alert( "Bye now!" );
});
Elaborating on #charlietfl's comment, could you try something like this?
Return the count from the ajax script and insert it into your page:
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList', // this returns the user count as data
type: 'POST',
data: {id: id, userT: usertype},
success: function(data){
$('[data-id='+id+']').parents('tr').remove();
$('#countDisplayElement').text(data); // insert new count into current page
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
That would eliminate the need to refresh the page entirely and be a bit more friendly to use.

Use the result of an ajax request as a variable

I would like to know how I can use the result of an ajax request as an "object". I'll try to explain. I have an ajax request that get a number, every 2 seconds, to an xml file. Then I render it into my html.
Here is my js:
var url = window.location.pathname.split('/');
var id = url[3];
setInterval(function() {
$.ajax({
type: "GET",
url: "http://myxml",
success: parseXml
});
}, 2000);
function parseXml(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
$(".DubScore").html($(this).attr("count"))
}
});
}
and my html:
<div class="DubScore"> </div>
It works find, I have a count displayed to my page.
What I want to do, is to take this number and be able to do whatever I wan't with it in my html. For example, name it "Score", and be able to do "Score" + 2 , and things like that.
I hope my question is clear enough. Thank you for your help.
You can parse the attribute value and store it in a global variable :
var score;
function parseXml(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
score = parseInt($(this).attr("count"), 10);
}
});
}
Afterwards, you may do, for example,
score += 2;
$(".DubScore").html(score);

ajax field insert without loading second page bug

So I went through this tutorial http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/ and instead of using php I created my own classic asp page, but one thing is bugging me when trying to put spaces in the input boxes they do not show up for example if I put bill gates in the name field it shows up as billgates
any ideas
$(".btn22").bind("click", function() {
var name = $("input#yourname").val();
if (name === "") {
$("input#yourname").focus();
return false;
}
var email = $("input#youremail").val();
if (email === "") {
$("input#youremail").focus();
return false;
}
var message5 = $("#limitedtextarea").text();
if (message5 === "") {
$("#limitedtextarea").focus();
return false;
}
var sku5 = $("#sku5").val();
var dataString = 'yourname='+ name + '&youremail=' + email + '&message=' + message5 + '&sku5=' + sku5;
$.ajax({
type: "POST",
url: "actions/newreview.asp",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<br><br><p class='big red'>Thanks for the review.</p>")
.hide()
.fadeIn(1500, function() {
$('#message');
});
}
});
return false;
});
});
'asp looks like this
name = request.form("yourname")
email = request.form("youremail")
sku = request.form("sku5")
comment = request.form("message")
then inserts names into a database, but it has already gotten rid of the spaces before this point
You'll have to post your markup here for us to tell what's going on for sure, but have you set the input type to type='text'?
looks like you are doing your own encoding of the form data. Not sure if that's the problem but it could be. jQuery includes a utility that does this for you.
dataString = $("#JqAjaxForm").serialize();
reference: http://api.jquery.com/serialize/
Some other comments:
you may wish to produce a javascript object, rather than just use form encoding. In this case jQuery will serialize it into json, if you use dataType:json on the post() method.
use Javascript in your classic ASP page. It may make things a little simpler for you, to use the same language on client (browser) and server.
figured it out just added name = escape(name) add the %20 in and then take it out to add spaces in my asp code
thanks everyone

How can I pass a function variable in jquery?

This is my html form I am using.
<label>Your Username:</label><input id="username" name="username" type="text" onchange="return ajax ('username');" />
This is my ajax checking file in php.
if ($_REQUEST['username']) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
And my jquery ajax request...
function ajax (input) {
var val = $('#'+input).val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: val,
},
function (response) {
$('.error, .success').hide();
setTimeout(function(){
$('.loading').hide();
finishAjax(input, response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#'+id).after(response).fadeIn(2000);
}
On my form I call the ajax request with the variable username.
In my ajax.php the correct validation of the username takes place if the request is named username.
I would like to display the variable input in place of username in the jquery code so I can use this script for other validations and pass the variable as email, or password and the script will still run as the value of input will be what it needs to be.
If that makes sense.
Thanks for your time.
var data = {};
data[input] = $('#' + input).val();
$.post("ajax.php", data, function() {...
and
finishAjax(input, response);
check input arg wat ll u get then proceed.....
remove semicolon near to
{username: $('#' + input).val(),}
as ,{ username: $('#' + input).val()},
u ll get o/p
You're declaring val to be the value of "input", but never using it. All the usages of username should have access to that variable val, so use it. Unless I'm misunderstanding your question, something like this (only changed one line):
function ajax(input) {
var val = $('#' + input).val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: val,
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
Before you call $.post create an empty object.
var data = {};
Use the parameter of the function as the index for the object.
data[input] = val;
In your $.post call use that object instead of the anonymous object literal.
$.post("ajax.php", data, function ...);
If you do things the way you're describing, though, you need to make sure you manage all these parameters you pass in properly. Are you sure that your PHP script is able to handle all the different possible values you may pass into the ajax function?

Categories

Resources