Ajax Jquery Call for On Submit Not Working - javascript

Despite adding the prevent default option on submit, the code is not being redirected to try.php and on submit the values are being displayed on the browser like it does by GET method. I have been on this for hours now. Kindly Help!
$.ajax({
url: "try.php",
cache: false,
type :"POST",
data : {action:'John'},
success : function( data ) {
$("#show_here").val(data);
}
});
});
});

Try this if it works:
$('.please').submit( function(e) {
e.preventDefault();
//var act = $("input[name='v_year_name']").val();
$.ajax({
url : "try.php",
cache: false,
type :"POST",
data : {action:'John'},
success : function( data ) {
$("#show_here").val(data);
}
});
});

check entered url/path is correct.
$(document).ready(function(){
$('.ajaxform1').submit( function(e) {
$.ajax({
url : "try.php",
cache : false,
type :"POST",
data : {action:'John'},
success : function( data ) {
$("#show_here").val(data);
}
});
}); });

Related

Ajax request fails

I'm doing a contact form and I'm trying to use AJAX. I've followed some youtube guide, but the code didn't work for me. I believe the problem is with the datosEnviados object, but I don't know how to fix it. I tried using parse function but it didn't work either.
The error I get is the following
SyntaxError: Unexpected token < in JSON at position 0 (...)
The code of my JS function is:
function ejecutarAjax(event) {
var datosEnviados = {
"nombre":$('#nombres').val(),
"email":$('#email').val(),
"comentario":$('#comentario').val()
}
$.ajax({
type : 'POST',
url : '../php/enviar_contacto.php',
data : datosEnviados,
dataType: 'json',
encode : true
})
.done(function() {
alert("ok");
})
.fail(function(jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText);
});
event.preventDefault();
}
Is there anything wrong with my syntax when defining datosEnviados or is it something else?
Thanks in advance
Try this
function ejecutarAjax(event) {
event.preventDefault(); //This should be at top
var datosEnviados = {
//Try with replace "nombre" to nombre(Remove "")
number : $('#nombres').val(),
email : $('#email').val(),
comentario : $('#comentario').val()
}
$.ajax({
type : 'POST',
url : '../php/enviar_contacto.php',
data : datosEnviados,
dataType: 'json',
encode : true
})
Alternative
function ejecutarAjax(event) {
event.preventDefault(); //This should be at top
$.ajax({
type : 'POST',
url : '../php/enviar_contacto.php',
data : {
nombre : $('#nombres').val(),
email : $('#email').val(),
comentario : $('#comentario').val()
},
success: function(data){
//Your code goes here
}
})
Hopefully, this will work

preventDefault() and 2 functions

On my website users can add a text dynamically and remove it dynamically (via AJAX).
The problem is when users want to add a text and remove it immediately.
The suppression isn't realized (submit of deletion form is not detected).
$(document).ready(function() {
$(function(){
/* ADD A TEXT */
$("#formAdd").submit(function(evt) {
evt.preventDefault();
var text = $(this).find("textarea").val();
if (text) {
var url = $(this).attr('action');
form = $(this).serialize();
$.ajax({
type : "POST",
url : url,
dataType : "json",
data: {
"form" : form,
"form-type" : $(this).find(':submit').attr("name")
},
success: function(data){
document.getElementById("visualisation").html = text;
},
statusCode: {
400: function() {
alert("error");
}
}
});
}
});
/* REMOVE A TEXT */
$('#formDelete').submit(function(e) {
alert("CHECK !");
var idText = $(this).find('#text_visualisation').val();
form = $(this).serialize();
$.ajax({
type:"POST",
url: $(this).attr('action'),
dataType : "json",
data: {
'form' : form,
"form-type" : $(this).find(':submit').attr("name"),
},
success: function(data) {
$("#text").remove();
$("#modal_deleteForm").modal('hide');
},
statusCode: {
400: function() {
alert("error");
}
}
});
return false;
});
});
});
So the alert("CHECK !"); is not realized when I want to delete a text just after added this text. Why ?
I find the solution after a lot of hours of research... The probleme isn't preventDefault() but innerHTML (you couldn't now it, I'm sorry).
But I don't understand why use innerHTML can blocked jquery submission of form...
Thank's

how can I access the data that I just encoded using "_serialize" in Cakephp

I have this function in my UsersController. I created this JSON response by using the _serialize key:
public function test() {
$arrEmail = $this->User->find('first');
$this->set('foo', $arrEmail);
$this->set('_serialize', array('foo') );
}
Now in the client side, in my phonegap application, I am trying to access this data. So I put the following:
<script>
$( document ).ready(function() {
alert(1);
$.ajax({
url : "http://localhost/database/users/" + 'test.json',
async : false,
cache : false,
crossDomain: true,
dataType : 'json',
type : 'post',
success : function(result) {
alert('success');
alert(JSON.stringify(result));
},
error : function(xhr, status, err) {
//con failed
alert(err+' '+xhr+' '+status);
}
});
});
</script>
The alert gives me the following .
Now I need to access to the username and the other attributes. I tried result.attributename but i always get undefined as a response.
EDIT:
`result.foo.User.id` solved the issue.

Jquery display message while php processing

I'm using jQuery ajax call to post process a form.
I want to display a loading message or image while the form is processed and when the action is completed to display a complete message.
How can I do it?
This is my jQuery code.
$s('body').on('click', '#group-update', function() {
var formInputs = $s('input').serializeArray();
var groupId = $s(this).data('group');
var error = $s('#modal .info');
var tr = $s('#dataT-attrgroup').find('tr.on_update');
formInputs.push({
name: 'id',
value: groupId
});
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
success: function(data) {
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
}
});
});
Before ajax function display your loader and inside the success function from your ajax hide it.
As you can see in my example i inserted $('.loader').show(); and $('.loader').hide();
$('.loader').show();
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
success: function(data) {
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
$('.loader').hide();
}
});
According to the PHP docs:
The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.
You should take a look at : https://github.com/blueimp/jQuery-File-Upload/wiki/PHP-Session-Upload-Progress
I think this will definitely help you out!
Display your message just before launching $.ajax();
And close it in the success (and error) callback functions.
example :
$s('body').on('click', '#group-update', function() {
var formInputs = $s('input').serializeArray();
var groupId = $s(this).data('group');
var error = $s('#modal .info');
var tr = $s('#dataT-attrgroup').find('tr.on_update');
formInputs.push({
name: 'id',
value: groupId
});
var dlg = $s('<div/>').text('your message').dialog();
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
error:function() {
dlg.dialog('close');
},
success: function(data) {
dlg.dialog('close');
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
}
});
});
If you go through ajax section of jquery documentation you will notice some more method like success ie error, beforesend, complete etc. Here is the code snippet.
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
beforeSend : function(){
// load message or image
},
success: function(data) {
// write code as per requirement
},
complete : function(){
// load complete message where you previously added the message or image, as a result previous one will be overwritten
}
});

Jquery - Remove Tags and add Tags dynamically using [aehlke] multitags plugin

I am using tagit plugin (https://github.com/aehlke/tag-it "Tagit Plugin aehlke") and auto-complete feature. I have to change tags based on the selection made using the auto-complete feature.
It worked for the first selection but not for the second one .
I removed the existing tags - using 'removeAll" in tagit plugin and did tagit() - doesn't work ??
This is my code :
<script>
$(document).ready(function() {
var allKeyWordsString=" ";
$.ajax({
url : some url,
type : 'GET',
//data : "query="+$("#query").val(),
async : false,
cache : false,
contentType : "application/x-www-form-urlencoded",
processData : false,
success : function(returndata) {
allKeyWordsString = returndata.success;
alert("keywords are "+ allKeyWordsString);
}
});
var sampleTags = allKeyWordsString.split(',');
$("#keyWordForm").autocomplete({
source: sampleTags,
minLength : 3,
select: function(event,ui){
var selectedKeyWord = ui.item.value;
var services = " ";
$.ajax({
url : 'some url',
type : 'GET',
data : "query="+selectedKeyWord+" services",
async : false,
cache : false,
contentType : "application/x-www-form-urlencoded",
processData : false,
success : function(returndata) {
services = returndata.success;
alert(" ajax call response is "+services);
}
});
if ($('#servicesForm').val().length != 0){
$('#servicesForm').tagit('removeAll');
}
document.getElementById("servicesForm").value=services;
$('#servicesForm').tagit();
}
});
return false;
});
</script>
Please help
To add tag, you can use method createTag:
$("#myTags").tagit("createTag", "brand-new-tag");
Similarly, method removeTagByLabel is for removing a tag:
$("#myTags").tagit("removeTagByLabel", "my-tag");
You can find above methods in the documentation: https://github.com/aehlke/tag-it/blob/master/README.markdown

Categories