How to achieve the same behaviour in Ajax - javascript

$usrname = $this->session->userdata('username');
$password = $this->session->userdata('password');
$data = array('userName'=>urlencode($usrname),'password'=>urlencode($password));
$data_string = json_encode($data);
$datanew = "loginemployee=". $data_string;
$method = 'post';
$format = 'application/json';
$this->rest->format($format);
$login_url = $this->login_url;
//print_r($login_url);
//exit;
$result = $this->rest->{$method}($login_url, $datanew);
Can anybody please assist me with this. This is actually a PHP script to login into a website, I need to achieve the same on my Cordova app which uses only HTML and JQuery, so please provide me info on how to do this.
$(document).ready(function(){
$('form#loginForm').submit(function() { // loginForm is submitted
var username = $('#username').attr('value'); // get username
var password = $('#password').attr('value'); // get password
alert(username);
var UserData= {"userName":username , "password":password};
var jsonString=JSON.stringify(UserData);
var datanew = "loginemployee=". $jsonString;
if(jsonString)
{
alert("encoded"+jsonString);
}
if (username && password) { // values are not empty
$.ajax({
type: "POST",
url: "http:// i know URL", // URL
contentType: "application/json; charset=utf-8",
dataType: "json",
// send username and password as parameters
data: datanew, // script call was *not* successful
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function (data) {
alert("success");
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
alert(data);
console.log(data);
$('form#loginForm').hide();
$("#loginResult").append('all good');
} //else
} // success
}); // ajax/ if
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});

You have done some mistakes in code and I listed those thing below.
Don't use $('#username').attr('value'). Instead of use $('#username').val(). Because $('#username').attr('value') return the value of the element while the html created. But $('#username').val() will return the current value. Same as change $('#password').attr('value') to $('#password').val(). For more information check this post.
Concatenation operator in javascript is + not .. And also u added a variable like $jsonString.
In your Server php code, if your using $_POST['loginemployee'] to retrieve the post values means don't use contentType: "application/json; charset=utf-8",. Because it will use the entire content including key as invalid json like loginemployee={"userName":"cloud","password":"cloudnine"}. If you need like that means u need to use file_get_contents('php://input') to retrieve the post content. But better don't use contentType in ajax. So you can able to easily get the post content using $_POST['loginemployee'].
And also if the reply is json means use dataType in ajax, else dont use that. For more information about contentType and dataType check this post.
So, I updated the code. Check and reply back if there is any issues. Hope it will work as your wish.
$(document).ready(function(){
$('form#loginForm').submit(function() { // loginForm is submitted
var username = $('#username').val(); // get username
var password = $('#password').val(); // get password
alert(username);
var UserData= {"userName":username , "password":password};
var jsonString=JSON.stringify(UserData);
var datanew = "loginemployee="+ jsonString;
if(jsonString)
{
alert("encoded"+jsonString);
}
if (username && password) { // values are not empty
console.log(datanew);
$.ajax({
type: "POST",
url: "http://url_to_post", // URL
// contentType: "application/json; charset=utf-8",
// If reply is json means uncomment the below line.
// dataType: "json",
// send username and password as parameters
crossDomain : true,
data: datanew, // script call was *not* successful
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function (data) {
alert("success");
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
console.log(data);
$('form#loginForm').hide();
$("#loginResult").append('all good');
} //else
} // success
}); // ajax/ if
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});

Related

AJAX POST group of form variables to PHP

I am trying to send a group of form parameters over to a PHP script for processing.
I've previously done something like this using $.post, but now I'm trying to get it done strictly by using $.ajax.
Here is the jQuery click event that is supposed to send all of the variables to the PHP script:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
Here is the PHP script, called railmbs.php:
<?php
if(isset($_POST['searchCriteria']))
{
$value = $_POST['searchCriteria'];
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($value['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($value['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($value['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Not sure what I am doing wrong. If I echo hello before the IF above, the console will output accordingly. But I cannot seem to get anything to echo from inside the IF.
Does anyone see my error?
You are not setting the "searchCriteria" variable.
Change this:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
to:
$('.searchSubmit').on('click', function()
{
var data = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: data, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
First of all. Why not to use $("form").serialize()? It would be much cleaner.
Secondary, you transfer data in root object, so to get you values, check $_POST array.
Instead of $value = $_POST['searchCriteria'] use $value = $_POST;.
This PHP code should work:
<?php
if(isset($_POST))
{
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($_POST['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($_POST['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($_POST['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Or modify your js to send data in searchCriteria object, like this:
var searchCriteria = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}};
You should check if you actually send post data using your browser developer tools or typing var_dump($_POST); at the beginning of your PHP script.
As far as i can see, you never actually set searchCriteria as post variable.
Currently your $_POST variable should contain the field import_bill, import_ramp and so on. Either change your if statement or your JavaScript object to {searchCriteria: {/*Your data here*/}.

[object Object]parsererrorSyntaxError: Unexpected token < in JSON at position 0

I am insert the data in mysql database using ajax on submitting this error will appaer .I am making this
in codeigniter framework. I am new bie to ajax.I am not able to figure out where am going wrong .Here is my code
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled', true); //set button disable
var url;
// if (save_method == 'add') {
url = "http://[::1]/sms/sms/forms/1";
// } else {
// url = "";
//// }
var radio=$('#radio').val();
var st_id=$('#st_id').val();
var branch_type=$('#branch_type').val();
bname=$('#bname').val();
bcode=$('#bcode').val();
baddress=$('#baddress').val();
var bcity=$('#bcity').val();
var zcode=$('#zcode').val();
var bstates=$('#bstates').val();
var bcountry=$('#bcountry').val();
var bpno=$('#bpno').val();
var bemail=$('#bemail').val();
var bweb=$('#bweb').val();
var Latitude=$('#Latitude').val();
var Longtitude=$('#Longtitude').val();
var noted=$('#noted').val();
var addedby=$('#addedby').val();
// ajax adding data to database
$.ajax({
type: 'ajax',
data: {st_id: st_id, branch_type: branch_type, bname: bname, bcode: bcode, baddress: baddress,
bcity: bcity, zcode: zcode, bstates: bstates, bcountry: bcountry, bpno: bpno, bemail: bemail,
bweb: bweb, Latitude: Latitude, Longtitude: Longtitude, noted: noted, addedby: addedby},
url: url,
method: 'post',
asysc: false,
dataType: 'json',
success: function (data) {
if (data.status) //if success close modal and reload ajax table
{
}
else {
}
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + textStatus + errorThrown);
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
//
}
});
my php code
$submit['sys_t_id']=$this->input->post('st_id');
$submit['t_id']=$this->input->post('branch_type');
$submit['name']=$this->input->post('bname');
$submit['code']=$this->input->post('bcode');
$submit['address']=$this->input->post('baddress');
$submit['city']=$this->input->post('bcity');
$submit['zip']=$this->input->post('zcode');
$submit['state']=$this->input->post('bstates');
$submit['country']=$this->input->post('bcountry');
$submit['contact_no']=$this->input->post('bpno');
$submit['email']=$this->input->post('bemail');
$submit['web']=$this->input->post('bweb');
$submit['latitude']=$this->input->post('Latitude');
$submit['longitude']=$this->input->post('Longtitude');
$submit['note']=$this->input->post('noted');
$submit['addedby']=$this->input->post('addedby');
$submit['addedon']=date('Y-m-d:H-m-s');
$insert = $this->Smsmodal->insert('branch_info',$submit);
echo json_encode(array("status" => TRUE));
I think you have server error! Use console.log(data) in you success function for see server output.

Debugging jquery handlers

This question is a followup of this one. I have created a simple example to check how code is executed within the handler. For the form
<form id="calendar_id" method="post">
Insert date: <input id="date_id" type="text" name="l_date" required>
</form>
I'm trying to retrieve the fields using the following javascript:
function get_form_data_uid($form) {
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function (n, i) {
indexed_array[n['name']] = n['value'];
});
indexed_array['uid'] = 'badbfadbbfi';
return indexed_array;
}
$("#calendar_id").submit(function (e) {
var uri, method, formId, $form, form_data;
// Prevent default submit
e.preventDefault();
e.stopImmediatePropagation();
uri = "/";
method = "POST";
formId = "#calendar_id";
$form = $(formId);
form_data = get_form_data_uid($form);
alert("form_data " + form_data);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
// Setting async to false to give enough time to initialize the local storage with the "token" key
async: false,
dataType: "json",
data: form_data
};
// Make the request
$.ajax(request).done(function (data) { // Handle the response
// Attributes are retrieved as object.attribute_name
console.log("Data from change password from server: " + data);
alert(data.message);
}).fail(function (jqXHR, textStatus, errorThrown) { // Handle failure
console.log(JSON.stringify(jqXHR));
console.log("AJAX error on changing password: " + textStatus + ' : ' + errorThrown);
});
});
However, the code within the handler is not executed (the alert is not shown). Why?
Edit:
The code works jsfiddle but not in firefox.
At least, you are calling a function get_form_data_with_token() which is not defined anywhere in your posted code. Perhaps you meant to call your get_form_data_uid().
Would have just made this a comment, but apparently cannot.

jQuery / AJAX success function if statement not working?

I have a section of code I am using to check if the desired username is available using a jQuery AJAX call:
function check_username()
{
// Set user_name to the current value of input #new_user_name
var user_name = document.getElementById('new_user_name').value;
// Ajax to check availability of username
$.ajax({
url: '_check_username.php',
type: 'post',
data: { 'user_name': user_name },
success: function(data) {
var does_it_pass_or_fail = data;
if ( does_it_pass_or_fail === "fail" )
{
alert( "Sorry, the username already exists. does_it_pass_or_fail = " + does_it_pass_or_fail ); );
}
else
{
alert( "That username is available! does_it_pass_or_fail = " + does_it_pass_or_fail ); );
}
}, error: function() {
// Not sure what to put here...
}
});
}
The script works as expected -- I check the MySQL database on _check_username.php, and I successfully return a "pass" if the name's available, or "fail" if the name is already taken, and store it in the JS variable does_it_pass_or_fail.
However, regardless of whether does_it_pass_or_fail contains "pass" or "fail", I ONLY get the response "That username is available!"
So, the AJAX / PHP / MySQL portion seems to be working fine, but this simple JavaScript if statement has me stumped!
try using this:you had some syntax error in your code close to alert.try logging error also.
function check_username()
{
// Set user_name to the current value of input #new_user_name
var user_name = document.getElementById('new_user_name').value;
// Ajax to check availability of username
$.ajax({
url: '_check_username.php',
type: 'post',
data: { 'user_name': user_name },
success: function(data) {
var does_it_pass_or_fail = data;
console.log(data);
if ( does_it_pass_or_fail === "fail" )
{
alert( "Sorry, the username already exists. does_it_pass_or_fail = " + does_it_pass_or_fail );
}
else
{
alert( "That username is available! does_it_pass_or_fail = " + does_it_pass_or_fail );
}
}, error: function(erro) {
console.log(error);
}
});
}
Use firebug to debug the ajax request.
place
console.log(data);
in the success function.
success: function(data) {
console.log(data)
}
This may help you in debugging your ajax issues.
Thank you all for leading me in the direction of further inspecting the AJAX call.
As it turns out, my '_check_username.php' script was returning a newline before returning "pass" or "fail" -- so, naturally, "\npass" is a different string than "pass". Once I realized this I was able to repair the script.

my javascript function dont display alert message when get data from database through ajax in mvc3 [duplicate]

This question already has an answer here:
javascript alert messages is not show in mvc3
(1 answer)
Closed 9 years ago.
I am working on a form in mvc3 and use form validations in javascript and ajax.
in my form i add code and description in database and before form submission want to check that code already exist in database or not.i get the code in javascript through ajax function call andd eturn data in json form. when i get the data i display error message in alert to user that code already exist. but my alert is not display.what can i do for it.
below is my javascript save button click function
$('#sve').click(function () {
//e.preventDefault();
var iscodeexis = CodeExistChk();
if (iscodeexis) {//
//***********************CODE TO SAVE DATA IN DATABASE***********************************
var person = { AcCode: $('#AcCode').val(), Descrip: $('#Descrip').val(), AddOn: dd };
$.ajax({
url: '/Home/Save?action=Sve',
type: "POST",
data: JSON.stringify(person),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
// $('#message').html('Record saved successfully' + result).fadeIn();
alert("Record saved successfully");
},
error: function () {
// $('#message').html('Error Occurred').fadeIn();
alert("Record not saved successfully");
}
});
}//end of is valid function chk
else
return false;//if isvalid function return false then save button also return false
}); //end button clcik function
function CodeExistChk() {
subA = $('#AcCode').val().trim();
// ===========================check whether code exist already or not
if (subA.length === 10) {
str1 = "select AcCode from Account where AcCode='";
str2 = str1 + subA + "'";
GetCodeData(str2); //check whether code exist or not
strRes = strRes.substring(1, strRes.length - 1);
if (strRes.length > 0 && strRes != "") //if code exist then return false and not allow to enter code
{
alert('Code already exist cannot insert record');
return false;
}
}
//===============================
}
below is getcodedata function which use in above code to get code from database
//===============FUNCTION TO GET CODE FROM DATABASE TO USE IN JS FILE==========
function GetCodeData(Str) {
var p = {
StrSql: Str
};
$.ajax({
url: '/Home/GetGenVal',
type: 'POST',
// contentType: 'application/x-www-form-urlencoded',
dataType: "JSON",
contentType: "application/json; charset=utf-8",
processData: false,
crossDomain: false,
traditional: true,
data: JSON.stringify(p),
cache: false,
// success: callback
success: function (data) {
//$("#Descrip").val(data);
// ResSubCode = data;
strRes = null;
strRes = data;
return strRes;
}
});
}
waiting for early solution.
Whoa, I see a some mistakes in this code.
At first, never construct your sql queries on client side to execute them. What if I modify the query to be a "delete from"? Bye bye database!
I would simply edit your logic and use a [RemoteAttribute] MVC3/4 feature to call a controller action and return simply a true or false.
Check it here: Remoteattribute test usage
You cannot be wrong!
Vincenzo.

Categories