Ajax just opens PHP file - javascript

I have a form I am trying to submit via ajax from PHPAcademy's tutorial found here
Basically the form needs to submit via ajax, simple enough. But when I try do that, it just opens the PHP file in the browser. PLEASE HELP!
here is the ajax code:
$('form.login_settings').submit(function(){
var that = $(this),
url = '../login_settings_submit.php',
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
I have tried using e.preventDefault(); but with no luck
I have also tried changing the initial function from
$('form.login_settings').submit(function(){
to
$('form.login_settings').on('submit', function(){
What am I doing wrong?

It's pretty easy friend:
Java Script Code:
$(function() {
$('form.login_settings').submit(function(e){
e.preventDefault();
var that = $(this),
type = that.attr('method'),
data = that.serialize()
$.ajax({
type: type,
url: '../login_settings_submit.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
});
use jQuery .serialize method to parametrize form data and write code inside
$(document).ready(function(){
//
}); or
$(function(){
//
});
and if you wanna check ajax error then you can use
,error : function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connected.\nPlease verify your network connection.');
} else if (jqXHR.status === 404) {
alert('The requested page not found. [404]');
} else if (jqXHR.status === 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
after success method. It's good to check ajax error always when you are in production.

Related

Error part in jQuery is missing

I build following JavaScript part and everything works fine. But I'm not sure if the code is completely right. Because in my script I only use success: function() but I don't use error. Is it a MUST to have error in a jQuery AJAX call?
Currently I'm catching the errors in my php controller function and echo them in the success part.
$(document)
.ready(function() {
var groupName = '';
var groupid = '';
$(".grp")
.click(function() {
$('.text-danger')
.html('');
groupName = $(this)
.data('groupname');
groupid = $(this)
.attr('id');
$('.text')
.html(groupName);
$('#dataModal')
.modal({
show: true
});
});
jQuery(".grpval")
.click(function(e) {
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
, });
jQuery.ajax({
url: "{{ route('request_group') }}"
, method: 'post'
, data: {
'Gruppe': groupid
}
, success: function(data) {
if (typeof data.successsuccess != 'undefined') {
jQuery('.alert-success')
.show();
jQuery('.alert-success')
.html('<p>' + data.successsuccess + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else if (typeof data.successdberror != 'undefined') {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + data.successdberror + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else {
jQuery.each(data.errors, function(key, value) {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + value + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
});
}
}
});
});
});
EDIT: Here is the function from my Controller:
public function setGroupRequest(Request $request){
$validator = \Validator::make($request->all(), [
'Gruppe' => [new ValidRequest]
]);
$groupid = $request->input('Gruppe');
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
try{
$groups_request = new GroupRequest();
$groups_request->idgroups = $groupid;
$groups_request->iduser = Auth::id();
$groups_request->request_active = 1;
$groups_request->save();
$db_status = 'success';
}catch(\Exception $e){
$db_status = 'error';
}
if($db_status == 'success'){
return response()->json(['successsuccess'=>'Record is successfully added']);
}else{
return response()->json(['successdberror'=>'DB Error! Values could not be saved.']);
}
}
Error handling is required as you never know different things on the internet might result in failure of request for example,
Network failure.
Lost database connection
Unauthorised access/access denied
Any variable being not defined
There is nothing wrong in your way of writing PHP error in success, but writing it in $ajax error callback function is preferred as it helps in separating error & success logic.
In fact you can add a jquery error callback function as well to your $ajax which will handle all the errors originating from above mentioned internet failures.
You can add error function, which will receive any type of error coming from backend.
jQuery.ajax({
url: "{{ route('request_group') }}",
method: 'data: {
'Gruppe': groupid
},
success: function(data) {
//code here
},
error: function (jqXHR, exception) {
//error handling
}
})
In your PHP file,
if ($query) {
echo "success"; //whatever you want to show on success.
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}
This way you can catch PHP error as well as any internet Network errors in your jquery ajax.

How to define a variable after process in ajax?

I use an ajax process to modify user's state on an index.php file.
It works but I would like to color my div function of the user's state
My code:
function recupstatut() {
$.post('recup.php', function(data) {
$('.cont2').html(data);
var content = document.querySelector('#cont2');
var status2 = content.innerHTML;
if (status2 == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
});
}
setInterval(recupstatut, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="cont2" id="cont2">
</div>
The condition always applies the else state:
content.style.backgroundColor = "#f44336";
I think the problem comes from var status2 =
How can I fix this?
HTML
<div class="cont2" id="cont2"></div>
SCRIPT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
function recupstatut() {
$.post('recup.php', function(data) {
console.log(data);
var status2 = data.trim();
console.log(status2);
$('.cont2').html(status2);
if (status2 == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
});
}
setInterval(recupstatut, 1000);
</script>
what went wrong is that you imported jquery file after calling the function
so make the import in top of calling your function
your mistake was that you made the import after calling the function, that is why you got undefined error.
As you say you echo string in your page then you can check this one directly from the data as per below code.
Script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$(function(){
function recupstatut() {
$.post('recup.php', function(data) {
$('#cont2').html(data); // If the data return from the php page as a string then you can compare it directly.
if (data == "En-ligne") {
$('#cont2').css("backgroundColor","#4CAF50");
} else {
$('#cont2').css("backgroundColor","#f44336");
}
});
}
setInterval(recupstatut, 1000);
});
</script>
HTML:
<div class="cont2" id="cont2"></div>
function recupstatut(){
$.post('recup.php',function(data){
console.log(data);
$('.cont2').html(data);
var status2 = data;
if (status2 == "En-ligne") {
$('#cont2').css("backgroundColor","#4CAF50");
} else {
$('#cont2').css("backgroundColor","#f44336");
}
});
}
setInterval(recupstatut,1000);
nothing appear in my div now with the console.log...
THere many ways to accomplish this. You can use the $.post() function by sending the $.post as a variable. Example:
// Fire off the request to /form.php
request = $.post({
url: "recup.php",
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
Or (i recommended) use the $.ajax({}) function as this way:
// Fire off the request to /form.php
$.ajax({
url: "recup.php",
type: "post",
data: { //specify data to be sent },
beforeSend:function(){
/* before sending the data to the other page
may be a loader to show waiting animation
*/
},
success:function(status){
/* this will check the response received from the previous page
and the determine the below conditions
*/
if (status == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
}
});

jQuery AJAX post returns 403 error

I have the following script for AJAX to do login, but with some passwords that contain characters like "!##" it will return 403 error and will not submit to the PHP.
$(document).ready(function () { // When the document is ready
$('#login').click(function (e) { // We attach the event onchange to the select element
e.preventDefault();
var form_info = "";
$('#login_form *').filter(':input').each(function(){
if(this.value !== ""){
form_info += this.name;
form_info += "=";
form_info += encodeURIComponent(this.value);
form_info += "&";
}
});
form_info += "function_name=login";
var form = $('#login_form').serialize() + "&function_name=login";
$.ajax({
url: "function_ajax.php", // path to you php file
type: "post", // We want a POST request
dataType: 'html',
data: form_info,
statusCode:
{
404: function () {
alert('Could not contact server.');
},
500: function () {
alert('A server-side error has occurred.');
}
},
error: function ()
{
alert('A problem has occurred.');
},
beforeSend: function ()
{
alert(form_info);
alert(form);
},
complete: function ()
{
},
success: function (data) { // The function to execute if the request is a -success-,
if(data === "1"){
if (document.referrer !== "") {
window.location.href = document.referrer;
}
else{
window.location.href = "some_domain"
}
}
else if (data === "2")
{
alert("invalid");
}
else {
alert("empty");
}
}
});
});
});
You will find that I'm trying both ways to encode each element and the serialize just to check if I'm getting the same result, and I'm getting the same result, but still, it's getting this error.
If I try to encode the whole serialize, then I will not get the error but in PHP, the $_POST array will have the first key as the data I'm sending with no value.
encodeURIComponent($('#login_form').serialize()) + "function_name=login"
then the $_POST will be like
array(
[email=email#gmail.com&password=pass123!##&function_name=login]=>
)
which will not be useful for me.

server response in ajax goes in error function instead of success

I have seen many solution for the above question but none of them falls in my category. My server is responding with correct json. Not able to figure what is exactly causing the issue. I get status as 0 and status text as error . Its disgusting . Issue is in deleteimage() function. There mi8 be issue in a way i am handling event.If anyone can figure out it would be good.Almost a day gone after this. Help is appreciated.
$(document).ready(function() {
//grab all form data
var form = $('#get_design_form');
form.submit(function(event) {
event.preventDefault();
var x = true;
if(category_id.value == '0'){
alert("Please select category.");
category_id.focus();
x=false;
return x;
}
if(design_no.value == ''){
alert("Please enter design no.");
design_no.focus();
x=false;
return x;
}
if (x) {
$('#send').attr("disabled",true);
$('#lm').show();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success : function(data) {
var result = data;
if(result.response_code=='101'){
$('#failure').show();
$('#success').hide();
$('#failure').text("Error Occured.Try again");
}else if(result.response_code=='102'){
$('#failure').show();
$('#success').hide();
$('#failure').text("Design no. does not exist.");
}else{
$('#con2').show();
$('#con1').hide();
$('#category_name').val(result.design_details.category_id);
$('#des_no').val(result.design_details.design_no);
//$('#image').attr('src','downloadImage?image_name='+result.design_img);
for(i=0;i<result.design_details.list_design_img.length;i++){
var html='<img id="'+result.design_details.list_design_img[i].design_img_path.split(".")[0]+'" src=downloadImage?image_name='+result.design_details.list_design_img[i].design_img_path+' style="vertical-align:middle;" width="100" height="100">';
var html1='<span style="cursor:pointer;" onclick="javascript:deleteimage(\'' + result.design_details.list_design_img[i].design_img_path + '\',\'' + result.design_details.category_id + '\',\'' + result.design_details.design_no + '\')">X</span>';
$('#img_div').append(html);
$('#img_div').append(html1);
}
}
$('#lm').hide();
$('#send').attr("disabled",false);
}
});
}
});
//return false;
$('#send').attr("disabled", false);
$('#lm').hide();
});
<script type="text/javascript">
function deleteimage(image_name,category_id,design_no)
{
alert("hii"+image_name+","+category_id+","+design_no);
var answer = confirm ("Are you sure you want to delete?");
if (answer)
{
$.ajax({
url: "http://192.168.0.2:8080/JaydeepSarees/deleteOthersDesignImgPath",
data: jQuery.param({image_name: image_name,category_id: category_id,design_no: design_no}) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
type: "post",
success: function (data) {
alert("hii");
var result=data;
alert(result.response_code);
if (result.response_code == 100) {
alert(result.response_code);
$("#"+image_name).remove();
}
},error: function (jqXHR,exception) {
console.log(jqXHR);
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.'+jqXHR.statusText;
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
});
}
return false;
}
</script>
I needed to use an relative path when trying to send request to server where in i was using absolute path that was the reason i was getting status as 0.
url: "deleteOthersDesignImgPath"
instead of
url: "http://192.168.0.2:8080/JaydeepSarees/deleteOthersDesignImgPath",

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

Categories

Resources