I have written a page so i can create a friendship between users. But my Problem is that jquery wont post the parameters.
I need some help, to fix that issue.
My Code:
//currentURL -> e.g: firstname.lastname
$('#friendRequestButton').on("click",function(e){
if(currentURL != "" && typeof(currentURL) != "undefined"){
$.post("sendFriendRequest.php",{user1:$.cookie("user-id"),user2:currentURL})
.done(function(data) {
console.log(data); // Here I get the same page(in HTML-format).. as result in the console.
});
//$('#friendRequestButton').attr("disabled","true");
}
});
If you need more details, let me know.
My PHP-Code:
<?php
if(isset($_POST['user1']) && isset($_POST['user2'])){
$user1 = $_POST['user1'];
$user2 = $_POST['user2']
die("OK!");
}else {
die("NOO!");
}
?>
EDIT: I changed the way you mentioned with e.preventDefault();
<?php
$friends = false;
if(!$friends){
?>
<center>
<button class="submit" id="friendRequestButton">Ask for friendship</button>
<br />
<br />
<button>Send Message!</button>
</center>
<script>
$(document).ready(function(e){
$('#friendRequestButton').on("click",function(e){
console.log(e.target);
e.preventDefault();
if(currentURL != "" && typeof(currentURL) != "undefined" && $.cookie("user-id") != "" && typeof($.cookie("user-id")) != "undefined"){
$.post("sendFriendRequest.php",{user1:$.cookie("user-id"), user2:currentURL},function(data){
console.log(data);
}
);
//$('#friendRequestButton').attr("disabled","true");
}else {
console.log("NOOOOO");
}
});
});
</script>
<?php
}
?>
Without seeing the html it is a guess, but judging by the name of your element you are using a button. Probably that button submits the form the "normal" way, causing your page to reload and you to not see the results of your ajax call.
If that is the case, you need to prevent the default event for the button press (submitting the form in this case):
$('#friendRequestButton').on("click",function(e){
e.preventDefault();
// the rest of your code
use your ajax request like this-
$.post("sendFriendRequest.php",{user1:$.cookie("user-id"),user2:currentURL}),function(data){
console.log(data);
});
I found the ISSUE:
I'm SOOOO Stupid:
I have written the filename like this: sendFriendRequest..php (two dots)
It should be: sendFriendRequest.php
So thanks everyone for helping!! :D
Related
I am having a page with a form on it that should use AJAX to save and load data to a file.
JavaScript
This is the java script I am using:
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
$.get( "showForm.php", { loadConfig: this.text} )
.done(function( data ) {
$('#configFormContainer').html(data);
});
});
HTML for a-tags
The class .configFile in the second function refers to a list of a-Tags. When I click on of of those, the script successfully loads the content from a file and displays it. This is the html for the mentioned a-Tags:
<div class="list-group">
<a href="#" class="configFile>config.json</a>
<a href="#" class="configFile>config_1504987517.json</a>
</div>
This part is working fine: The javascript-function is triggered. In showForm.php the config file is loaded. It is re-building the complete form with the content from the file.
HTML for the form
Whats not really working is the trigger on the submit-function. This is the form-html
<form id="saveConfigForm" method="POST">
<a bunch of form elements />
<button name="submit" class="btn btn-success" type="submit" id="saveConfig">Speichern</button>
</form>
Whats the problem
So, whats happening now:
When I load the page initially, I click the submit-Button and get the alert. This trigger .submit() is working.
When I click one of the a-tags to load a config-file, the file is being loaded without refreshing the page. This trigger .click() is working, too.
After that: When I click the submit-button, the page is being reloaded. The trigger .submit() is not working.
And after this "unwanted" reload of the page, the .submit()-trigger is working, again.
I have no clue what it is wrong here. Hope someone can help
cheers
Though this isn't your whole code set, I took what you posted and made a page. I could click either of the .configFile links, then click the submit button and I get the alert.
However I did close both class attributes of the .configFile elements with a ". I don't know if that's the difference. But, if it isn't then it's something that's occurring after the ajax request which of course I can't simulate with this code.
<html>
<body>
<div class="list-group">
config.json <!-- //added " to end of class attribute -->
config_1504987517.json <!--//added " to end of class attribute -->
</div>
<form id="saveConfigForm" method="POST">
<a bunch of form elements />
<button name="submit" class="btn btn-success" type="submit" id="saveConfig">Speichern</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
if (window.XMLHttpRequest)
{
// AJAX for IE7+, Chrome, Firefox, Safari, Opera
xmlhttp = new XMLHttpRequest();
} else {
// AJAX for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
$('#configFormContainer').html(xmlhttp.responseText);
}
}
xmlhttp.open("GET","showForm.php?loadConfig=" + this.text, true);
xmlhttp.send();
});
});
</script>
</body>
</html>
The other thing that would be curious to me: Open the browser's developer console and paste in your submit binder again:
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
If your submit works after that, I'd suggest either binding the click event again after the new html is rendered. Or, binding the event to $(document) like:
$(document).on('submit', '#saveConfigForm', (e) => {
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
As a final note, I'm not trying to augment your code any more than necessary to help with the specific issue you're having. As another user commented, it would be cleaner to use the jQuery functions since you're using jQuery. But I don't take that as part of your question.
I kind of found out whats causing the problem: The ajax-call returns the html-form and put it to the form-container.
After this, the trigger to that form is gone, because the trigger was connected to the form, that I am overwriting with the ajax-data.
Quick'n'dirty
It will work, when I reset the trigger like that. But this looks more like quick'n'dirty
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
$.get( "showForm.php", { loadConfig: this.text} )
.done(function(data) {
$('#configFormContainer').html(data);
// re-init the trigger on "submit" here
// ------------------------------------
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
});
});
});
Clean-Fix
I needed to adjust the the showForm.php. If it's being called from the ajax-method, it will only return the form elements, not the form itself.
If it is being called from the scratch, it returns the complete form.
Furthermore, the java script now replaces the content of the form-element, not it's container. This way the trigger does not get lost.
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
$.get( "showForm.php", { loadConfig: this.text} )
.done(function(data) {
$('#saveConfigForm').html(data);
});
});
});
Just for the sake of completeness, this is the main part of the showForm.php now:
<?php
if (!isset($_GET['loadConfig']))
{
// do not return the complete form to prevent losing the trigger on it
echo '<form id="saveConfigForm" method="POST">';
}
echo '<a bunch of form elements />';
if (!isset($_GET['loadConfig']))
{
echo '</form>';
}
i have a simple form: when i submit it without javascript/jquery, it works fine, i have only one insertion in my data base, everything works fine.
I wrote some jquery to have result in ajax above the input button, red message if there was an error, green if the insertion was done successfully. I also display a small gif loader.
I don't understand why when i use this jquery, two loaders appear at the same time and two insertions are done in my database.
I reapeat that when i comment the javascript, it works fine, i'm totally sure that my php is ok.
$('#addCtg').submit(function () {
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I really don't understand why it doesn't work, because i use the 'return false' to change the basic behaviour of the submit button
Basic php just in case:
<?php
require_once('Category.class.php');
if (isset($_POST['name'])) {
$name = $_POST['name'] ;
if ($name == "") {
echo '<div class="error">You have to find a name for your category !</div>' ;
exit();
} else {
Category::addCategory($name) ;
echo '<div class="succes">Succes :) !</div>' ;
exit();
}
} else {
echo '<div class="error">An error has occur: name not set !</div>';
exit();
}
And finnaly my function in php to add in the database, basic stuff
public static function addCategory($name) {
$request = myPDO::getInstance()->prepare(<<<SQL
INSERT INTO category (idCtg, name)
VALUES (NULL, :name)
SQL
);
$r = $request->execute(array(':name' => $name));
if ($r) {
return true ;
} else {
return false ;
}
}
I rarely ask for help, but this time i'm really stuck, Thank you in advance
You're calling: $('.messages') - I bet you have 2 elements with the class messages. Then they will both post to your server.
One possible reason could be because you are using button or submit to post ajax request.
Try this,
$('#addCtg').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
There is 2 input type="text". First, user input 1st input text area with id="ncr_no". Then, cursor is in 2nd input type "text" with id="itm_cd". Now, I want to make, how the two input by user, when cursor is in 2nd input type, posted to other php (get_ncrnoitmcd.php) by javascript? That's the code.
<script type="text/javascript">
$(document).ready(function() {
$("#itm_cd").keyup(function (e) {
$(this).val($(this).val().replace(/\s/g, ''));
var itm_cd = $(this).val();
if(itm_cd.length < 1){$("#user-result3").html('');return;}
if(itm_cd.length >= 1 ){
$("#user-result3").html('<img src="image/ajax-loader.gif" />');
$.post('get_ncrnoitmcd.php', {'itm_cd':itm_cd}, function(data) {
$("#user-result3").html(data);
});
}
});
});
</script>
Thank a lot.
This is the way you can send the 2 values to server on 2nd element keyup after validation. Whats the problem that you are facing? I also added ncr_no in the post request.
<script type="text/javascript">
$(document).ready(function() {
$("#itm_cd").keyup(function (e) {
$(this).val($(this).val().replace(/\s/g, ''));
var itm_cd = $(this).val();
if(itm_cd.length < 1){
$("#user-result3").html('');
return;
}else if(itm_cd.length >= 1 ){
$("#user-result3").html('<img src="image/ajax-loader.gif" />');
$.post(
'get_ncrnoitmcd.php'
,{'itm_cd':itm_cd,'ncr_no':$('#ncr_no').val()}
,function(data) {
$("#user-result3").html(data);
}
);
}
});
});
</script>
I want to get available or not available, Mr. #joyBlanks
<?php
//connection.php
if(isset($_POST["itm_cd"],$_POST["ncr_no"]))
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
$itm_cd = strtolower(trim($_POST["itm_cd"]));
$itm_cd = filter_var($itm_cd, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
$results = mysqli_query($connecDB,"SELECT itm_cd,ncr_no FROM sqc_ncr WHERE itm_cd ='$itm_cd' AND ncr_no ='$ncr_no'");
$itm_cd_exist = mysqli_num_rows($results);
if($itm_cd_exist) {
die('<!--img src="image/available.png" /--> <i>Available in database</i>');
}else{
die('<!--img src="image/not-available.png" /--> <i>Not Available in database</i>');
}
mysqli_close($connecDB);
}
?>
I've not used , and used && and not used http_x_requested, but available or not available in html not shown.
<td><input type="text" class="input" name="itm_cd" id="itm_cd" onBlur="updateItemName()" required /> <span id="user-result3"></span></td>
I have one checkbox on my form working with the database for active(1) and inactive(0) users to access via admin panel. All is working fine but the problem is its not keeping the record for the checboxes when the checkbox is checked or unchecked after refreshing/reloading the page. i want them to be remembered even after admin logout and login again. can any one help me out ?
Thanx in advance
Here is HTML :
<td><input type='checkbox' class='user_status'
id='user_status_<?php echo $data['user_reg_id']; ?>' value='' name = 'user_status'
onclick="userId(<?php echo $data['user_reg_id']; ?>)" />
Here is JS :
<script>
function userId(user_reg_id){
$(document).ready(function(){
var link = "<?php echo base_url();?>" ;
var st = $('#user_status_'+user_reg_id).is(":checked") ? 0 : 1;
$.post(link + "administration/um/user_status", {user_reg_id:user_reg_id, user_reg_status:st, ajax : 1}, function(data){
alert (st); //showing status 1 and 0 on alert
if (st == 1){
$("#user_status_").prop(":checked", true)
} else {
$("#user_status_").prop(":checked", false)
};
});
});
}
</script>
store checkbox value in database using ajax when you click on it..
also fetch from database checkbox value if checkbox value is 1 than checked ...otherwise uncheck :)
Since you need the data to be persistent, I would suggest using HTML5 localStorage. Depending on how persistent, you may need to save it in a database. I haven't tested this code and have not actually done this. It's meant to get you close to a working solution.
function isChecked(user_reg_id){
$(document).ready(function(){
$('#user_status_'+user_reg_id).on('click', function () {
if(localStorage && localStorage.getItem(user_reg_id)){
localStorage.removeItem(user_reg_id);
}else{
$('#user_status_'+user_reg_id).prop('checked', true);
}
}
});
}
I have this JS which gets a XML response from a service, its a True or a False, well the script should catch the submit and get the response from the service.
The problem is that I see that its not working because when I do the submit, I see the XML response on IE (6/7/8), when the script should have catched it and validated the XML response.
<div id="eventForm" style="display:none;">
Event.observe('formDataPersonal', 'submit', function(event) {
$('formDataPersonal').request({
onSuccess: function(t) {
var xml = t.responseXML.documentElement;
var stateNode = '';
var msgNode = '';
if (navigator.appName == "Microsoft Internet Explorer"){
stateNode = xml.childNodes[0].nodeValue.toLowerCase();
msgNode = xml.childNodes[1].nodeValue;
}else{
stateNode = xml.childNodes[0].textContent.toLowerCase();
msgNode = xml.childNodes[1].textContent;
}
if (stateNode == 'true'){
$('transparentDiv').style.display='none';
$('popup').style.display='none';
validateIntegrationPopup();
}else{
var error = msgNode;
if (error != ''){
$('interfase').innerHTML = error;
}
}
}
})
});
</div>
I would be grateful for the help.
I think the problem may be that 'IE' does not see the submit event so it ends up just submitting the form normally:
See: https://rails.lighthouseapp.com/projects/8994/tickets/4411-railsjs-on-bodyobservesubmit-but-submit-doesnt-bubble-in-ie
This is an old question, but I managed to get it as my second result in a Google search, so:
You're not stopping the submit event from going through to the browser, which is why the form is submitting even though the event handler attached to it. Add in an event.stop():
<div id="eventForm" style="display:none;">
Event.observe('formDataPersonal', 'submit', function(event) {
event.stop();
$('formDataPersonal').request({
// .... code ....
});
});
</div>