I am new to Ajax and I have already seen this question but I am having this issue in chrome console
http://s2.postimg.org/6vdhlvyh5/Capture.jpg
Here's the php code...
$rs1 = [
'error' => $blank_err,
'url' => "http://localhost/experimental/view.php"
];
echo json_encode($rs1);
exit;
Here's Ajax code...
$.ajax({
type:"POST",
url:"validate_signin.php",
datatype:"JSON",
data:{
femail:femail,fpass:fpass,submit_signin: true
},
success:function(resp){
if (resp.error !== "") {
$("#err").html(resp.error);
} else {
window.location.href=resp.url;
}
and due to wrong backslashes it's not redirecting
I even tried using
$url=$_SERVER["HTTP_HOST"]."/experimental/view.php";
in php page and sending back to ajax with json_encode($rs1);
You can use JSON.parse for parsing the response and then redirecting as
success:function(resp){
var data = JSON.parse(resp);
if (data.error !== "") {
$("#err").html(data.error);
} else {
window.location.href=data.url;
}
I recommend, you can use jQuery.ajax() for this. this is easy to use and control ajax functionality. Follow this link http://api.jquery.com/jquery.ajax/
Related
I have read a lot on codeIgniter ajax response. I have and modified my ajax script multiple times yet codeIgniter does not return the json response although I see the response when debugging with firefox developer browser under the network tab of web console. here's what i have written
AJAX script
$("#class_id").change(function(){
var class_id = $("#class_id").val();
alert(class_id);
alert("<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id");
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id",
dataType: 'json',
data: {class_id: class_id},
success: function(response) {
$("#res").html(reponse.class_id);
}
});
return false;
});
controller
function set_class_id()
{
if ($this->session->userdata('teacher_login') != 1)
redirect(base_url(), 'refresh');
//echo "dsdsd".$this->input->POST('class_id');
if (!empty($this->input->POST('class_id')))
{
$page_data = array('class_id' => $this->input->POST('class_id'));
//$response["JSON"] = json_encode($page_data);
$response = array('class_id' => $this->input->POST('class_id'));
echo json_encode($page_data);
$this->load->view('backend/index', $page_data);
}
}
Have you tried using
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
Also, check th output class for more info Codeigniter Output Class
So I figured a way out. using just php, I sent the class_id to the controller using a submit button then checked for the response on the page to enable the subject dropdown. Although i haven't figured why the ajax isn't working yet. thanks guys for your inputs
I wanna make header location like stackoverflow system has. After posting, it will load the page based on lastinsertid. I tried to use php, it works, but I wanna change it using ajax jquery because of its single page. Could I use ajax jquery in this case? how to make it work?
here's the code :
PHP
if($sumn>0 && $sump>=0) {
echo "banned";
}
else if($sumn==0 && $sump<=3) {
echo "oot";
}
else{
$insert=$db_con->prepare("INSERT INTO tb_post (id_user,title,description,created_date) VALUES(:id_user,:title,:description,NOW())");
$insert->bindParam(":id_user",$id_user);
$insert->bindParam(":title",$title);
$insert->bindParam(":description",$description);
$insert->execute();
$id_post=$db_con->lastInsertId();
if ($insert->rowCount()>0) {
$post = $db_con->prepare("SELECT * FROM tb_post WHERE id_post=:id_post");
$post->execute(array(":id_post"=>$id_post));
$row=$post->fetch(PDO::FETCH_ASSOC);
$title = clean_url($row['title']);
$detail ="../discuss/".$row['id_post']."/".$title;
header("location:$detail");
echo 'success';
}else {
echo 'fail';
}
ajax jquery
$.ajax({
url: 'create_process.php?page=send_post',
type: 'post',
data: 'title='+title+'&description='+description,
success: function(msg){
if(msg=='success') {
window.location='/'; //This the problem.. need to know how to use header location based on lastinsertid
}
else if(msg=='banned') {
$("#dis-mes").html('<div class="allert alert-danger">Banned</div>');
}else if(msg=='oot'){
$("#dis-mes").html('<div class="allert alert-danger">OOT</div>');
}else {
alert('failed');
}
}
});
instead of using a header, you should return the redirect url in the response.
the php response should be a json string like this :
{
status: "success",
url: "../discuss/".$row['id_post']."/".$title
}
in the javascript just check the content of msg.status and use msg.url in your window.location
If you still want to use headers, you can use this in your success function:
success: function(msg, textStatus, request){
if (msg == 'success') {
window.location = request.getResponseHeader('location'));
}
},
My application is behind a sign in, so when loading the data through ajax, I need to verify the user still has an active session. If the user does not have an active session, I return back with echo json_encode(array('TIMEOUT')); which outputs ["TIMEOUT"]. How do I read that response and send the user back to the sign in page?
In previous versions of DataTables, I was able to do the following:
"fnServerData": function ( sSource, aoData, fnCallback, result ) {
$.getJSON( sSource, aoData, function (json) {
if(json == "TIMEOUT")
{
window.top.location.href = "/sign_out?action=to";
return;
}
fnCallback(json)
} );
Under DataTables 1.10, fnServerData has been replaced by ajax (see docs and ajax.data). How do I accomplish the same thing with the new DataTables version? I feel like I am close, but it just isn't working...possible because I am doing something wrong attempting to parse the response (I never hit inside the if statement).
"ajax": {
"url": "/account/location_load",
"data": function (myJson) {
if(myJson == "TIMEOUT")
{
window.top.location.href = "/sign_out?action=to";
return;
}
return myJson;
}
}
After a day and a half working on it, I finally found a working solution using ajax.dataSrc (doc)
"ajax": {
"url": "/account/location_load",
"dataSrc": function (myJson) {
if(myJson == "TIMEOUT")
{
window.top.location.href = "/sign_out?action=to";
return "";
}
return myJson.data;
}
I don't know why this version allowed me to read myJson and the other didn't, but it works. The working PHP code ended up being echo json_encode('TIMEOUT');
I have to process a Simple log-in File. In Many Web Tutorials I have read that for any Ajax requests in jquery the callback function is function(data) and the data is returned by the server side script.
Well, my server side script is PHP. I wish to know how can I return data from PHP which will be stored in jquery's data and I can use conditional loops to process them.
Here is my jquery Code:
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, processLI );
function processLI(data) {
if (data == 'success'){
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
}
I am using simple return statement in my php file, which does not seem to work at all. here is the login.php file. I just posted the part necessary here.
$statement = $connection->prepare("SELECT * FROM users WHERE username = '$username'");
$statement->execute(array());
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result['password'] == $safepass) {
setcookie("Login", true);
echo 'success';
}
else
echo "Failure";
Try doing it like this, by placing the function as the parameter, and not by calling the function.
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, function(data){
if (data == 'success') {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
});
Use the echo statement to output data, if the login is successful echo 'success';
This is an answer about how to debug AJAX requests. First, use Chrome (or Safari, or Firefox with Firebug plugin installed), then open up the developer tools from the settings menu. In the network panel, you can see the request/response. It may not be a direct answer, but please - try to use the Chrome developer tools with the "Net Panel" to see request/response/cookies/headers.
This will save you the trouble of having to guess, it will show you the response verbatim. Then you can solve it next time ;) and the time after
Have you been able to see the request/response? If not, I suggest a simple
alert(JSON.stringify(data))
...from your callback function if you have issues using the Chrome debugger.
Try giving the dataType for post as 'html'
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.ajax({
url : 'login.php?'+querystring,
cache : false,
success : function(data) {
if(data == "success") {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
} else if(data == "failure") {
alert("Login Failed");
}
};
});
});
I have a jquery script that just runs fine on http://mysite.com
and looks like this:
Javascript:
$('#form_changePass').live('submit', function() {
//alert('form_changePass cliked');
$.POST("_ajaxCall.php", $(this).serialize(),
function(data){
var json = eval('('+data+')');
//alert(data);
if(json.message=='alert') {
$('div.info').hide();
$('div.alert').show().html(json.string);
}
if(json.message=='info') {
$('div.alert').hide();
$('div.info').show().html(json.string);
}
}
);
return false;
})
PHP script:
if ($_POST['formType']=="form_changePass") {
.....
.......
$arr = array( 'message' => 'info', 'string' => $INFO['updatePass']);
echo json_encode($arr);
}
Now when I move the domain into https the jquery script is not working anymore. I do not get any return value back. Nothing happens.
I also tried to change the POST to getJSON in the javascript and changed the $_POST to $_GET in the php script but it is still not working.
Anybody a idea?
http and https are considered different domains, so it is a cross domain issue. The fix is:
header('Access-Control-Allow-Origin: https://domain.com');
Add this to your php script. Or this only in development so you don't need to worry too much:
header('Access-Control-Allow-Origin: *');
.serialize serializes the form data as a string, so send them using a parameter instead.
$('#form_changePass').on('submit', function() {
//alert('form_changePass cliked');
$.POST("_ajaxCall.php", { formData: $(this).serialize() },
function(data){
var json = eval('('+data+')');
//alert(data);
if(json.message=='alert') {
$('div.info').hide();
$('div.alert').show().html(json.string);
}
if(json.message=='info') {
$('div.alert').hide();
$('div.info').show().html(json.string);
}
}
);
return false;
})
And stop using .live() methods, they have been deprecated now. Use .on() methods.