JavaScript function doesn't work as per JSON response - javascript

I am encoding my returned response through JSON and trying to make it work as per the JSON Response's values.
Assume below values are what I am returning.
if ($upload = 1){
$response['status'] = 1;
$response['message'] = 'SUCCESS';
$response['success'] = 'false';
}else{
$response['status'] = 3;
$response['message'] = 'CATEGORY ASSOCIATED';
$response['success'] = 'false';
}
header('Content-type: application/json');
echo json_encode($response);
I will be retrieving it to my form and handle the action through the encoded responses.
$('#form').on('submit', function(e){
e.preventDefault();
var id = $('#id').val();
$.ajax({
type: "POST",
url: 'edit.php',
data: {cid:id},
success: function(response){
if(response.status = 1){
console.log('THE STATUS IS 1');
}
else if(response.status = 3){
console.log('THE STATUS IS 3');
}
}
});
});
The issue I am facing is I am getting both responses on browser's network tab. console prints status 1 but not status 3. Where am I making the mistake?

Try this.....
$('#form').on('submit', function(e){
e.preventDefault();
var id = $('#id').val();
$.ajax({
type: "POST",
url: 'edit.php',
data: {cid:id},
success: function(response,status){
if(status == 1){
const newres = JSON.parse(response);//parse the response
if(newres.status == 1)
console.log('The status is 1');
else if (newres.status == 3)
console.log('The status is 3');
}
else {
console.log('No response');
}
}
});
});
The json_encode($response); is a json format string, parsing makes it an object.

Related

Codeigniter & Ajax - Condition statement in javascript

Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.

how to return data php to ajax

I didn't understand how to get data from php by ajax.
Here is my javascript code :
$('#value').on('keyup', function(event){
event.preventDefault();
var form_data = $(this).serialize();
var sending = $("#sending").val();
var value = $("#value").val();
var recevied = $("#recevied").val();
$.ajax
({
type: "POST",
//async: true,
dataType : 'json',
url: "{{url('/calculate')}}",
data: {_token:"{{csrf_token()}}", sending:sending,value:value,recevied:recevied}
}).done( function(data){
//swal("Good job!", "Your personal information has been successfully updated!", "success")
$("#mainvalue").val(data)
console.log('Ajax was Successful!')
console.log(data)
}).fail(function(xhr, textStatus, error){
console.log(textStatus)
console.log(error)
});
});
here is my php code :-
public function index(Request $request)
{
$sending = $request->get('sending');
$value = $request->get('value');
$recevied = $request->get('recevied');
$relations = DB::table('tbl_relations')
->where('exid1',$sending)
->where('exid2',$recevied)
->select()
->first();
if ($relations != null) {
$rate = $relations->exrate2;
$mainvalue = $sending * $rate;
return $rate;
}else{
return $request->all();
}
}
How to restore $rate value into #mainvalue ?
well i guess you can try the following inside the php code :
$post = file_get_contents('php://input');

how to check that ajax returns true or false value using jquery

i'm building a signup form for my website i validate my signup page with jquery i want to do that when all the fields are filled with valid way then the signup page redirect or load and store the data in database...
1. first jquery code checks input fields
2. then in the jquery code there is a ajax call which check if the email already exist or not if the ajax call return true then data will be inserted in database if it return false the the page will not load and display the message that email is already exist
the problem in my code is that when the ajax call is true or false my page keep loading and insert the data in database but i want that if value is false page will not load.
here is my code
$.ajax({
type:'POST',
url:'email_validator.php',
data:{email:mail},
success:function (response){
var result = $.parseJSON(response);
if (result.status===false) {
$('#error').html("Email alreaday exist");
return false;
} if(result.status===true) {
return true;
}
}
});
and here is my email_validator.php
<?php
if(isset($_POST["email"])){
$result = array();
$email=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$email]);
if($STH->rowCount() == 1){
//echo "Email alreday exist";
$result["status"] = false;
}
else{
$result["status"] = true;
}
echo json_encode($result);
exit(0);
}
Try this:
$.ajax({
type:'POST',
url:'email_validator.php',
data:{email:mail},
success:function (response){
if (response.status === true) {
return true;
} else {
$('#error').html("Email alreaday exist");
return false;
}
}
});
In my opinion you should invoke the PHP API method to insert the new email directly inside the success function callback:
$.ajax({
type: 'POST',
url: 'email_validator.php',
data: {email: mail},
success: function (response) {
var result = $.parseJSON(response);
if (result.status === false) {
$('#error').html("Email already exists");
}
else (result.status === true) {
// -> Call here the PHP api method to insert the new email in the database
}
}
});
You can add async option to false and return outside the ajax call:
function testAjax() {
var resultStatus = "";
$.ajax({
type:'POST',
url:'email_validator.php',
async: false,
data:{email:mail},
success:function (response){
var result = $.parseJSON(response);
resultStatus = result.status;
if (result.status===false) {
$('#error').html("Email alreaday exist");
}
}
});
return resultStatus;
}
[UPDATE]
But you do not need to check this on client side. Yo can check if email exists in your email_validator.php and immediately write it to the database if it does not exist:
email_validator.php
<?php
if(isset($_POST["email"])){
$result = array();
$email=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$email]);
if($STH->rowCount() == 1){
//echo "Email alreday exist";
$result["status"] = false;
}
else{
$result["status"] = true;
// --> INSERT the new email into the database
}
echo json_encode($result);
exit(0);
}

how to pass ajax response value to another page?

I'm trying to send an AJAX response to a PHP file. Based on the response I would like to redirect to another page. If the response is success I would like to redirect to a 'thank you' page along with the parameter data.
How can I pass this transactionId to another page?
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
if (response == "success") {
window.location.href = 'http://www.google.com';
}
});
});
});
change your php output from
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
to
if ($result->success)
{
echo json_encode(array('status'=>'success','id'=>$result->transaction->id));
}
else if ($result->transaction) {
echo json_encode(array('status'=>'error','code'=>$result->transaction->processorResponseCode, 'text'=> $result->transaction->processorResponseText)));
}
else
{
echo json_encode(array('status'=>'error','text'=>$result->errors->deepAll()));
}
and change your js to the following
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
var data= $.parseJSON(response);
if (data.status == "success") {
window.location.replace('http://www.google.com?id='+data.id)‌​;
}else{
alert('Operation Failed');
if(data.code){
console.log('response code: '+data.code);
}
console.log('response text: '+data.text);
}
});
});
});
looking at your php code - it never returns success, it will return success!: somthing so this condition if (response == "success") is never true
you could use
if(response.indexOf("success") == 0)
or change the response in the php file
You can send the response variables you'd like by incorporating them into a query on the redirect.
For instance if you wanted to pass on foo to your redirected php domain.com/bar.php:
var url = 'domain.com/bar.php?foo=' + foo
window.location.href = url;
And then on the PHP page, you can use this data:
$bits = parse_url($url);
parse_str($bits['query'], $query);
echo $query['foo']

Message error its not showing using ajax via jQuery

Im trying to update data in a form via ajax with jQuery.
Im doing the update with sucess, but when I have empty fields Im not getting my error message saying: myModal('config_datas_errempty','alert','Fill al fields please');
And also if I write a wrong format for email I dont have any message too.
Do you see where might be the error? Because for me everyting seems fine and I already review the code many times!
My php:
switch ($action)
{
case 'data_update':
$d['adress'] = $_POST['adress'];
$d['phone'] = $_POST['phone'];
$d['fax'] = $_POST['fax'];
$d['email']= $_POST['email'];
if(in_array('',$d))
{
echo 'errempty';
}
else if(!valMail($d['email']))
{
echo 'erremail';
}
else
{
$updateData= $pdo->prepare("UPDATE config_data set adress=?, phone =?, fax=?, email=? WHERE id = ?");
$updateData->bindValue(1, $d['adress']);
$updateData->bindValue(2, $d['phone']);
$updateData->bindValue(3, $d['fax']);
$updateData->bindValue(4, $d['email']);
$updateData->bindValue(5, '1');
$updateData->execute();
}
break;
default: echo 'Error';
}
My jQuery:
$('form[name="config_data"]').submit(function(){
var forma = $(this);
var data = $(this).serialize() + '&action=data_update';
$.ajax({
url: url,
data: data,
type: 'POST',
beforeSend: function(){
forma.find('.load').fadeIn("fast");
},
success: function( datas ){
if(datas == 'errempty'){
myModal('config_datas_errempty','alert','Fill al fields please');
}else if((datas == 'erremail')){
myModal('config_datas_accept','accept','Sucess update');
}
},
complete: function(){
forma.find('.load').fadeOut("fast");
}
});
return false;
});

Categories