Welcome,
I am weak in javascript
I created code that does the following work:
When clicking on the preferred product icon, the data (product number, user, etc.) will be sent to the database
Everything is working fine.
The problem is that when I click on the heart sign again, it does not send again (delete favorite).
I hope the problem is clear.. I want the JavaScript code to run more than once and not stop at one use
if($('#shopping-form').length){
var o = new Object();
var form = '#shopping-form';
var authintication_us = $('#shopping-form .authintication_us').val();
var authintication_tbs = $('#shopping-form .authintication_tbs').val();
var p_id = $('#shopping-form .p_id').val();
var typ = $('#shopping-form .typ').val();
$('#AddPv').click(function(){
event.preventDefault();
var fybtn=document.getElementById("AddPv");
if(authintication_us == '' || authintication_tbs == '' || p_id == '' || typ == '')
{ return false; }
$.ajax({
url:"like.php",
method:"POST",
data: $(form).serialize(),
success:function(data){
$('#AddPv').addClass('active');
fybtn.setAttribute("id","RemPv");
},
error:function(){
return false;
}
});
});
$('#RemPv').click(function(){
event.preventDefault();
var fybtn=document.getElementById("RemPv");
if(authintication_us == '' || authintication_tbs == '' || p_id == '' || typ == '')
{ return false; }
$.ajax({
url:"like.php",
method:"POST",
data: $(form).serialize(),
success:function(data){
$('#RemPv').removeClass('active');
fybtn.setAttribute("id","AddPv");
},
error:function(){
return false;
}
});
});
}
When it sends data (send favourite) it switches the identifier to the one with which I can delete the data (delete favourite
this is my html code:
<span class="fav-btn" id="AddPv" > <i class="fas fa-heart"></i> </span>
As for the rest of the data, it will receive it from pre-existing inputs
The code really works..but the problem is that I couldn't make it work more than once..you can give me an example of how likes and dislikes work like on Facebook so that I can solve the problem myself
Related
I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});
Current Scenario :
Right now I have a form in which you can edit and save each records of input fields. i.e. firstName, lastName, email etc..
I do not get any errors and everything is working fine.
Requirement :
Now what I want to save & edit firstName and lastName input fields together instead is to edit and save firstName and lastName input field separately.
Right now they are all different input id's.
Question :
How can I achieve this by calling the same class for firstName and lastName if I want to edit them at the same time with a button ?
Is this a way to do it ? Thanks...
Code :
$("#inputFirstName,#inputLastName,#inputEmailAddress,#inputPassword,#inputZipCode").on('keypress',function(e){
if(e.which == 13) {
var field = $(this).attr("id");
var data = {};
data['ajax']=true;
data[$('#'+field).attr('name')]=$('#'+field).val();
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][firstName]') {
$('#userfirstname').text($('#'+field).val());
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][lastName]') {
$('#userlastname').text($('#'+field).val());
}
});
$('#'+field+'-edit').show();
$('#'+field+'-save').hide()
$('#'+field).attr('disabled',true);
}
});
first of all. save on every keypress is bad and will exhaust your server.
I recommennd you use onChange or make a submit button
submit button is a better solution.
lets assume that we have this html:
<form id="updateForm">
<input type="text" id="firstN" name="firstName" data-val="Ris" value="Ris">
.
.
.
<input type="button" value="submit" id="goBtn">
</form>
first set a data-val equal to the value
then in your javascript
$("#goBtn").click(function(){
var data = {};
data["ajax"] = true;
$("#updateForm input").each(function(){
var $this = $(this);
var type = $this.attr('type');
if(type != "button" && $this.val() != $this.attr("data-val"))
data[$this.attr("name")] = $this.val();
});
if(data.length > 0){
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
} else {
$.each(data, function(index, value){
$('updateForm input[name="'+index+'"]').attr("data-val", value);
});
}
// then do things
});
}
});
first it checks every input for changes (data-val is holding the original value) and it adds it to data if there is any changes at all it calls the ajax and if it was successful it updates the data-vals of each changed value else it leave it for another submission
I need use the changes only, not all the text, to provide server resources and service user.
see Code Mirror: Get Text Around Changes
HTML:
<textarea id="code">script.js</textarea>
JavaScript:
var id = document.getElementById("code");
var options = {mode:'javascript'};
var editor = CodeMirror.fromTextArea(id, options);
editor.on("change",function(cm,change){
$.ajax({
url:'update.php',
method:'POST',
data:{
save:true,
file:'script.js',
update:change
},
success:function(data){
console.log(data);
}
});
});
PHP:
if(isset($_POST['save']) && $_POST['save'] === true){
if(isset($POST['file']) && file_exists($POST['file'])){
$file = file_get_contents($POST['file']);
if(isset($POST['update']) && !empty($POST['update'])){
$change = #json_decode(#json_encode($_POST['update']));
//here how to use data from $change to update file script.js?
}
}
}
!!
I have a jquery ajax post and when a user inputs some text and presses enter in a textbox this ajax will trigger and show the value of text box in a <pre> html element. http://jsfiddle.net/LQg7W/2133/ obviuosly this jsfiddle does not show anything because I haven't put the ajax post inside it. But when the user writes nothing and presses enter this ajax is triggered and returns something. But how can I catch the empty strings from user?
This is located in my view:
if(e.keyCode == 13) {
var currentLine = $('#terminal').text();
var inputData = $(e.currentTarget).val();
$('#terminal').text(currentLine + "\r\n" + inputData + "\r\n"); //show the current and previous value
$("#textInput").val(" $> ");
AjaxPost(inputData);
}
and this ajax post is in model:
AjaxPost : function(dataAttribute, view, cacheId) {
console.log(cacheId);
var that = this;
if(dataAttribute === ""){
view.showMessage( " " , true);
}
$.ajax({
type : "POST",
url : "/api/user" ,
datatype : "application/json",
contentType: " text/plain",
data : dataAttribute,
success : function(data) {
console.log(data);
},
error : function(error) {
},
My problem is that my input data has default value of "$>" so I cannot check this condition if (inputdata === "" ) because it is always full! Have any ideas?
if the input value defaults to "$>" then you only need to check that too, and return to avoid the ajax call:
if(dataAttribute === "" || dataAttribute === "$>") {
view.showMessage( " " , true);
return;
}
var m = inputdata.match(/\s*\$\>\s*/)
if (inputdata === m[0]){
console.log('empty')
}
else{
console.log('not empty')
}
How can I make cancel button in javascript prompt box to do nothing like the cancel button on confirmation box instead of sending "null" values?
Or is it possible to remove the cancel button from the prompt box so there is only "ok" button left?
This is what I have tried but it still sends the null to value to my PHP file.
function AskQuestion(data)
{
var id = getUrlVars()["id"];
console.log(data);
if(data.key[0].status == "ok") {
var reply = prompt(data.key[0].REPLY, "");
var index = data.key[0].IND;
if(reply != "" && reply !== null) {
//do nothing
}else{
jQuery.ajax({ type: "POST",
url: serviceURL + "message.php",
data: 'id='+id+'&arvo='+reply+'&index='+index,
cache: false,
success: AskQuestion});
}
} else {
window.location = "page.html"
}
}
You've got your test on the return value the wrong way around. As it is you // do nothing when the user enters text, and call ajax when they don't. Change
if(reply != "" && reply !== null) {
// do nothing
to
if(reply == null || jQuery.trim(reply).length == 0) {
// do nothing
A few ideas:
reply = jQuery.trim( prompt(...) || "" );
if( reply ){
jQuery.ajax(...)
}
You can just return to exit the function