Hello I have change password using Ajax (this is a short version of the code):
var password = document.querySelector('[name="password"]').value;
action = 'http://localhost:8012/market2/market2/public/account/query/';
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.open("post",action + password, true);
xmlhttp.setRequestHeader("X-CSRF-TOKEN", document.getElementById('token-csrf').value);
xmlhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "false") {
document.getElementById("error_password").innerHTML = "You actually password is wrong!";
return false;
} else {
document.getElementById("error_password").innerHTML = "OK";
return true;
}
}
}
xmlhttp.send();
}
And my csrf-token:
<input type="hidden" name="_token" id="token-csrf" value="{{ csrf_token() }}">
I don't know did I correct add parameter X-CSRF-TOKEN to my script. First I have error ajax 419 (unknown status) so I added X-CSRF-TOKEN and now I have error 500 (Internal Server Error). I also tried this: Laravel 5.5 ajax call 419 (unknown status)
Edit Post:
Is't my query method:
public function queryPass($pass) {
$user = Auth::user();
$current_password = $user->password;
if(Hash::check($pass, $current_password)) {
$updatePassword = App\User::where('id', $user->id)->update(['password' => bcrypt($pass)]);
echo "true";
} else {
echo "false";
die;
}
}
And route:
Route::get('account/query/{pass?}', 'UsersController#queryPass');
First problem was that he missed use Illuminate\Support\Facades\Hash; at the top of his controller, he used use Hash;, second thing when we resolved that was that, he was returning a boolean from inside a controller, when he is supposed to return an object which implements __toString method or a string, so he returned a correct response in this case a string "true" and "false"
Related
I have an .htacess which is now working perfectly, on this page:
http://www.lebmotors.com/new/pror I have an ajax pagination file prorajax.php
clicking it it gets to index.php
$pag1->setContainerPage("http://www.lebmotors.com/new/prorajax"); This turns to an ajax link, but clicking it reached homepage index.php instead
This is the link generated by pagination class
<a href='#' onclick='Submit_To_Ajax(\"$curentpage?xc=8&page=1$queriess\");'>
<< </a>
This is the ajax function:
function Submit_To_Ajax(page)
{
xmlHttp = AjaxHttpObject();
if (xmlHttp==null)
{
alert("Your browser does not support AJAX !!!");
return;
}
else
{
}
xmlHttp.open("GET", page, true);
xmlHttp.onreadystatechange=StateChanged;
xmlHttp.send(null);
}
function StateChanged() {
if (xmlHttp.readyState == 4)
{
document.getElementById('AjaxDiv').innerHTML=xmlHttp.responseText;
}
else
{
document.getElementById('AjaxDiv').innerHTML='<img src="img/loading.jpg">';
}
}
RESOLVED This was the reason in pagination.inc.php
href = "#" removing this resolves the issue
I have a form in my Cordova app:
<form id='transport' method='POST' action='' enctype='application/json'>
<input type='hidden' id='data' name='data' value='' />
</form>
and I sent to server (pure js):
postdata = '{';
postdata += '"first_name": "Jon",';
postdata += '"last_name": "Snow"';
postdata += '}';
document.getElementById('data').value = postdata;
document.getElementById('transport').action = 'http://testserver.com/add_user/';
document.getElementById('transport').submit();
but the data variable is empty when received on server.
On server I'm using Codeigniter.
Works perfectly in a web scenario, why not in Cordova? I know there is not the cross-domain problem, and I have allowed all domains (*) in config.xml.
Thanks.
Fixed! Just remove te slash (/) at the end of the URL.
This is because Codeigniter - with this slash - is expecting another parameter (due to its nature url-based) and if there is not, all the variables inside the controller (such as POST data) are null.
So this:
postdata = '{';
postdata += '"first_name": "Jon",';
postdata += '"last_name": "Snow"';
postdata += '}';
document.getElementById('data').value = postdata;
document.getElementById('transport').action = 'http://testserver.com/add_user';
document.getElementById('transport').submit();
it's correct.
You can achieve this with pure JS by using xmlhttp.
This one omits the wrapping of the data variable, so you get first_name and last_name as their own parameters.
function addUser(first_name, last_name){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("successfully added user");
console.log(xmlhttp.response);//this is the response from the server
}
}
params = "first_name=" + first_name + "&last_name=" + last_name;
xmlhttp.open("POST", "http://testserver.com/add_user",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
You can also send the data as JSON like this:
function addUser(first_name, last_name){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("successfully added user");
console.log(xmlhttp.response);//this is the response from the server
}
}
xmlhttp.open("POST", "http://testserver.com/add_user",true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//Not sure if you need the Content-length here or not.
xmlhttp.send(JSON.stringify({"data"=>{"first_name"=>first_name, "last_name" => last_name}}));
}
I find this approach cleaner than using an invisible form when it isn't really needed.
I have registration form and i have created three function in jquery
First one is validate the form.
Second one is for checking the email uniqueness with ajax request.
Third one is for creating user this also with ajax request.
My flow on submit event is that first i am calling validation function and then on the response of that function i calling the function to check the email uniqueness on the response of this a an ajax request is done to create a user.
First one is validate the form.
function validateregForm()
{
if($('#u_name').val()=="" || !IsEmail($('#u_email').val()) || $('#u_pwd').val().length<6 || $('#c_pwd').val()!=$('#u_pwd').val())
{
if($('#u_name').val()=="")
{
$('#reg_error1').show();
}
if(!IsEmail($('#u_email').val()))
{
$('#email_msg').remove();
$('#reg_error2').show();
}
if($('#u_pwd').val().length<6)
{
$('#reg_error3').show();
}
if($('#u_pwd').val()!=$('#c_pwd').val())
{
$('#reg_error4').show();
}
return false;
}
else
{
return true ;
}
Second one is for checking the email uniqueness with ajax request.
function chkmail(email) {
var posting=$.post('http://localhost/tv100.info/index.php/user/chkmail',{u_email:$('#u_email').val()});
posting.done(function(data){
if(data=='success')
{
$('#email_error').css('display','none');
$('#email_msg').css('display','block');
return true;
}
if(data=='failure')
{
$('#email_msg').css('display','none');
$('#email_error').css('display','block');
return false;
}
});
}
Third one is for creating user this also with ajax request.
$('#regform').submit(function(event) {
var res=validateregForm()
event.preventDefault();
if(res)
{
var email=chkmail();
}
if(email)
{
$('#loading2').show();
var posting=$.post('http://localhost/tv100.info/index.php/user/create_user',$("#regform").serialize());
posting.done(function(data)
{
$('#loading2').hide();
if(data=="success")
{
$('#reg_panel').append('<span id="reg_msg">Registration successful Now You are logged IN</span>');
$('#overlay').fadeOut(300);
$('#login').html('Logout');
$('#sign_in').hide();
$('#cmmnt_field').show();
}
if(data=="failure")
{
$('#reg_panel').append('<span id="res_msg">Something Went Wrong try again Latter</span>');
}
});
}
});
Just telling the case
if(res)
{
var email=chkmail(); // for getting the result in var email, ajax will wait until the success
}
if(email) // In your case before completing the ajax request, javascript come to this line and won't return true. So it it always go to else part.
You can do the user creation on success of chkmail success part. It will work fine
Error in your first line of validateregForm() function,
change
if($('#u_name').val=="" || !IsEmail($('#u_email').val())
to
if($('#u_name').val() =="" || !IsEmail($('#u_email').val())
^ `.val()` here.
You need to learn about asynchronously and synchronously concepts. Ajax calls are usually Asynchronously. Simple set the paramter async as false of each ajax request and you will get the result. From documentation
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default).
If you need synchronous requests, set this option to false.
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
You need to use a callback to process the result of email validation
function chkmail(email, callback) {
var posting = $.post('http://localhost/tv100.info/index.php/user/chkmail', {
u_email : email
});
posting.done(function(data) {
if (data == 'success') {
callback(true);
} else if (data == 'failure') {
callback(false);
}
});
}
$('#regform').submit(function(event) {
var res = validateregForm()
event.preventDefault();
if (res) {
chkmail($('#u_email').val(), function(valid) {
if (valid) {
$('#email_error').css('display', 'none');
$('#email_msg').css('display', 'block');
$('#loading2').show();
var posting = $.post('http://localhost/tv100.info/index.php/user/create_user', $("#regform").serialize());
posting.done(function(data) {
$('#loading2').hide();
if (data == "success") {
$('#reg_panel').append('<span id="reg_msg">Registration successful Now You are logged IN</span>');
$('#overlay').fadeOut(300);
$('#login').html('Logout');
$('#sign_in').hide();
$('#cmmnt_field').show();
}
if (data == "failure") {
$('#reg_panel').append('<span id="res_msg">Something Went Wrong try again Latter</span>');
}
});
} else {
$('#email_msg').css('display', 'none');
$('#email_error').css('display', 'block');
}
});
}
});
This is my node.js function that uses res.write:
function: ping(){
res.write(JSON.stringify({"datatype":"ping"}));
setTimeout(ping, 30000);
}
This is the client, request written in prototype:
this.pushconnection = new Ajax.Request(pushserveraddress, {
method: 'get',
evalJSON: 'false',
onInteractive: this.pushconnectionInteractive.bind(this)
});
}
pushconnectionInteractive: function(response) {
}
The problem is that response.responseText will grow with every res.write that comes through.
Example:
1st ping() received: response.responseText = {"datatype":"ping"}
2nd ping() received: response.responseText = {"datatype":"ping"}{"datatype":"ping"}
3rd ping() received: response.responseText = {"datatype":"ping"}{"datatype":"ping"}{"datatype":"ping"}
I'm not sure if node.js is re-sending the data, or if prototype is storing the data. What I need to do is have response.responseText = the last data sent without using res.end();
You're probably calling this.pushconnection more than once.
If you instantiate this.pushconnection as it's own Ajax Object and continue to use the same ajax object then your response will grow.
Try this instead:
this.pushconnection = function (pushserveraddress) {
return new Ajax.Request(pushserveraddress, {
method: 'get',
evalJSON: 'false',
onInteractive: this.pushconnectionInteractive.bind(this)
});
}
Then you can call this by saying:
var ajax = this.pushconnection("example.com");
every response add to previous one, to get last object sent if u use that php function :
(1st add headers)
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('connection: keep-alive');
(2 send data)
function send_message($data_array) {
echo json_encode($data_array).PHP_EOL;
ob_flush();
flush();
}
in your js (Prototype): to get last response
new Ajax.Request(sUrl, {
onInteractive:function(xhr){
var lastString = xhr.responseText.split("\n");
var lastObjectSent = lastString[lastString.length-2].evalJSON();
if(lastObjectSent.bValid){
if(parseInt(lastObjectSent.bValid,10) === 1){
this.status="finished";
loadPage('done.php');
}else{
setNotification(oResult.sText,"Failure",5000);
}
}else if(lastObjectSent.progress){
$('duplicatePassDates').down('.bar').setStyle('width:'+lastObjectSent.progress+'px');
}
},
onSuccess:function(xhr){
if(this.status!=="finished"){
this.onInteractive(xhr);
}
},
when I Implemented chatting Function , I use Ajax to send messages between file to another .
so ,
it is working well on local host .
but , when I upload it in to remote server it doesn't work.
can U tell me ,why ?
is an Ajax need Special configuration ?
Ajax code :
function Ajax_Send(GP,URL,PARAMETERS,RESPONSEFUNCTION){
var xmlhttp
try{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e) {
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e){
try{
xmlhttp=new XMLHttpRequest()
}
catch(e){
alert("Your Browser Does Not Support AJAX")
}
}
}
err=""
if (GP==undefined) err="GP "
if (URL==undefined) err +="URL "
if (PARAMETERS==undefined) err+="PARAMETERS"
if (err!=""){alert("Missing Identifier(s)\n\n"+err);return false;}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if (RESPONSEFUNCTION=="") return false;
eval(RESPONSEFUNCTION(xmlhttp.responseText))
}
}
if (GP=="GET"){
URL+="?"+PARAMETERS
xmlhttp.open("GET",URL,true)
xmlhttp.send(null)
}
if (GP="POST"){
PARAMETERS=encodeURI(PARAMETERS)
xmlhttp.open("POST",URL,true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.setRequestHeader("Content-length",PARAMETERS.length)
xmlhttp.setRequestHeader("Connection", "close")
xmlhttp.send(PARAMETERS)
}
}
Two points really,
Firstly, If the URL is on a different domain, default security model in your browser might stop that working.
Secondly, have a look at JQuery, this bulk of code would be reduced to 2 or 3 lines.
Have a look here: http://docs.jquery.com/Tutorials