am struggling with what seems should be a simple, thing. Namely to update database entry for a user with a variable. Here is the code am using:
function UpdateDB(username){
alert(username);
//username="John";
$.ajax({
async: false,
dataType: 'json',
type: "POST",
url: "file.php",
data: {'username':username},
});
}
function is called onlick, and username is defined as :var username=document.getElementById("username").innerHTML;. Both are defined before function is called and should not cause any problems. Alert gives correct var value. Associated bit in external PHP file (file.php) is:
if(isset($_POST['username'])){
$username=$_POST['username'];
$query = "UPDATE users SET Country='USA' WHERE username='$username'";
if(mysqli_query($db, $query)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $query. " . mysqli_error($db);
}
}
However, Country entry does not get updated for a var username in the database. However it works fine if instead of using variable, i just uncomment //username="John";. What am i doing wrong?
Thank you.
Related
I tried to access an id from a URL "myfolder/mycontroller/mymethode/123" which I call into an AJAXcall.
I cannot access them, in "mycontroller" under the "mymethode". I tried to output $_GET, $_POST, $this->input->get(), $this->input->post(), but all array are empty.
In the Controller/mycontroller I have this
public function mymethode($listid=false)
{
echo "listid: $listid";
print_r($_GET);
print_r($_POST);
print_r($this->input->get());
print_r($this->input->post());
}
The Ajax call is this and is ok with Status 200.
$.ajax({
url: http://mydomein.com/myfolder/mycontroller/mymethode/123,
type: "POST",
method: 'post',
data: form + "&" + additional_data + csrfName + "=" + csrfHash,
dataType: 'json',
cache: false,
success: function(res){...
If I tried to open the URL directly, I have the same problem.
What can the reason for it be?
Use this (if this is not HMVC)
in route.php
# You may need first route since you're accepting null on method
$route['mymethode] = 'mycontroller/mymethode';
$route['mymethode/(:num)'] = 'mycontroller/mymethode/$1';
In AJAX
url: http://mydomein.com/mymethode/123,
Make sure your sites run without index.php
In controller
public function mymethode($listid=null)
I´ve searching but with no luck, i´ve tried implementing many things but nothing lead to success, so this is my scenario:
At certain point the user is in a view where after filling some fields, he has the ability to save or save and create.
The first one it is working ok, i´m posting with ajax to my controller method and returning a json response, but the user stays normally in the same view.
The second one(when he saves and create) i´m sending a variable to say exactly that, and because of that choice, the user must be directed to another view to "create" BUT i need the data that was previously saved to automatically fill some fields on the new form that is suppose to be created...so my code is:
my ajax:
$.ajax({
method: 'POST',
url: '/Cliente/insertEditCliente',
dataType: "json",
data: {"_token": "{{ csrf_token()}}", "mainId":$('#mainId').val(),values,"btnId":this.text},
success: function(response){
if(response.titulo != "Erro!"){
let dados = response['dados'];
window.location = '{{ route("formAngariacao",[null]) }}'+'/?dados='+dados;
}
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
// console.log(JSON.stringify(jqXHR));
// console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
in my controller method, i have that if statment to detect if it was just save or save and create:
if($request->post('btnId') == "Guardar"){
return response()->json(["titulo"=>"Ok!","mensagem"=>"Cliente Alterado com sucesso!","tipo"=>"success"]);
}
else{
return response()->json(["titulo"=>"Ok!","mensagem"=>"Cliente Alterado com sucesso!","tipo"=>"success","dados"=>$request]);
}
But now, in my blade view, i need to read that array "dados" which corresponds to the $request variable and has all the data i need.
How do i do that? and is this the best practice?
thanks for your time reagards.
Im new to ajax. I was trying to find the answer but was not lucky to find the corresponsing one. Basically I need to use an ajax to get some data and after that to put this data to the variable that later will be used as an attribute for the callback function with custom code.
This ajax part is just a method of myObject.
So, in the end I need this kind of functionality:
myObject.getData(url, callback(data) {
//my custom code of what I wanna do after ajax is complete
});
My code
/*
HERE COME SOME PROPERTIES AND OTHER METHODS WICH IS NOT THE CASE
*/
//This is where Im stuck
var getData = function getFromUrl($url) {
$.ajax({
type: 'get',
url: $url,
dataType: 'html',
success: function(html) {
$obj = html;//Im lost on this step!
},
});
};
P.S. Im trying to find an async way (without using async:false). Hope its possible
First I encountered many problems. My first problem was No Access-Control-Allow-Origin, most websites dont allow you to just scrap get their data for security reasons. Luckily someone already made a proxy: http://cors.io/ . Second problem is that you cant embed http on https, so I cant use jsfiddle to show you this working, it works on my local enviroment. After you get the raw html you have to parse it, you can do it with full regex, or you can power yourself with jquery like I'm doing on this example. What we're doing is checking stackoverflow.com and getting the amount of featured questions with .find(".bounty-indicator-tab").first().html(); But once you have the full html you can get any data you need.
var getData = function getFromUrl(url) {
$.ajax({
url: 'http://cors.io/?' + url,
crossDomain: true,
dataType: 'html',
success: function (html) {
var match = $(html).find(".bounty-indicator-tab").first().html();
console.log(match);
return match;
},
error: function(e) {
console.log('Error: '+e);
}
});
};
url = 'http://stackoverflow.com/';
data = getData(url);
//You cant use data yet because its working async
Here is my code below that works, but passess only the first parameter. But I need two. I think JSON should be used for that purpose. I've tried, but still have no luck. Here is my working code that sends name. This function does NOT pass password
var name = $('#name').attr('value');//the value from input type name
var password = $('#password').attr('value');//the value from input type password
$.ajax({
type: "POST",
url: "index/success",
data: "name="+ name +"&password="+ password,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
From the other side I use method
$model->values ( $_POST );
so that
$model->name is defined and is what I actually sent.
But,
$model->password is empty.
P.S. Password should be crypted, I know that. That's a simplified example just to ask about using JSON.
Try
data: { name: name, password : password} ,
and let jQuery worry about encoding that for the request.
I'm working on a simple login form. When the user clicks on the Login button, I want to send the post values to my controller, validate them against my database (using a model) and return a value. Based on that value, I want to either send the user to the member area, or display an error message on my form. This error message has a class 'error' and is hidden by default. I want to use jQuery's show() to show it when the credentials are wrong.
My form has two textfields, one for the email address, other one for the password and a submit button. However, I have never really worked with Ajax except for VERY basic things like a simple loader, so I'm not sure what to do next.
$("#btn_login").click(
function()
{
// get values
var email_address = $("#email_address").val();
var password = $("#password").val();
// post values? and ajax call?
//stop submit btn from submitting
return(false);
}
);
I assume I have to use jQuery's ajax() method here, so I was thinking of working off this example:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
However, I'm not really sure how to get my post values (those two vars) in the data: thingy.. Or should I take another road here? This seems like something I'll never forget how to do once I learn it, so if someone can help me out I'd be grateful. Thanks a lot.
All you need to do is create a key/value pair with the values and assign it to the data parameter and jQuery will do the rest.
//create a js object with key values for your post data
var postData = {
'email' : email_address,
'password' : password
};
$.ajax({
type: "POST",
url: "some.php",
data: postData , //assign the var here
success: function(msg){
alert( "Data Saved: " + msg );
}
});
With this, you should be able to access the data with Codeigniters input
EDIT
I've set up a test fiddle here : http://jsfiddle.net/WVpwy/2/
$('#dostuff').click(function(){
var email_address = $("#email_address").val();
var password = $("#password").val();
var postData = {
'email' : email_address,
'password' : password,
'html' : 'PASS'
};
$.post('/echo/html/', postData, function(data){
//This should be JSON preferably. but can't get it to work on jsfiddle
//Depending on what your controller returns you can change the action
if (data == 'PASS') {
alert('login pased');
} else {
alert('login failed');
}
});
});
I just prefer .post, but what you used is an equivalent.
Basically your controller should echo out data. Not return. You need to send a string representation of your data back so your script can (evaluate if json) and act on it
Here's a good example as a starting point : http://www.ibm.com/developerworks/opensource/library/os-php-jquery-ajax/index.html
just modifiy a little bit the url of your ajax :
$.ajax({
type: "POST",
url: "some/myfunction",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Make sure your url point to the function you want inside your controller. For example: "myfunction" inside the controller some (in the file Some.php)
To access to your post variables inside the controller function do not try to put parameters to myfunction but :
class Some extends CI_Controller
{
......
public function myfunction()
{
$name = $this->input->post('name');
$location = $this->input->post('location');
}
......
}
You can definitely use your method, but a shorthand method is this:
$.post("some.php",{name:"John",location:"Boston",email:email_address,password:password},function(data,textStatus) { //response from some.php is now contained in data });