Ajax CodeIgniter form submit hide and show new view - ajax

I'm a newbie to ajax and trying to integrate it in to my CodeIgniter app. Basically, when the form is successful I would like the original template to be hidden and the new one shown? It currently displays both, how could I amend my code? Thanks in advance!
I have tried adding a redirect to my controller with no such luck :(
view:
$('#submit').click(function(){
$.post("<?php echo base_url(); ?>part-two",
$("form").serialize(),
function(result){
$("#error_message").html(result);
}, "html"
);
});
controller:
if($this->form_validation->run() == FALSE){
echo validation_errors();
} else {
echo "success";
$data['content'] = "part_two";
$this->load->view('template', $data);
}

OK, I think that I know what you want...
View html markup:
<div class="container">
<form id="form">
...
</form>
<div class="error_message">
</div>
</div>
Script:
$('#submit').click(function(){
$.post("<?php echo base_url(); ?>part-two",
$("form").serialize(),
function(result){
// clear the content and assing the result
$("#form").remove();
$("#error_message").html(result);
}, "html"
);
});

I cant help you so much. Would you please use firebug to see received data of post request ?
Since both are displaying so i think post request is okay. Problem is in your view file.

Related

CodeIgniter flashdata [flash:old:message] being displayed

I'm using CodeIgniter on OpenShift.
In my controller I'm using:
$this->session->set_flashdata('message', 'message X');
$this->load->view('viewpage');
In my view I'm using:
print_r ($this->session->userdata);
echo $this->session->flashdata('message');
Here are my observations:
first time through the controller/load view, I see nothing echoed with the
$this->session->flashdata('message');
I see this with the print_r:
[flash:new:message]=>message 1
second time through the controller/load view, I see "message 1" being echoed
I see this with the print_r:
[flash:old:message] =>message 1[flash:new:message]=>message 2
So what appears to be happening is that [flash:old:message] is being displayed instead of [flash:new:message]. If [flash:old:message] isn't set, then nothing is displayed.
Please help.
Cheers,
Mike
when you set a value in a flash data, you need to make a view refresh like:
controller.php
function do_somthing(){
$this->session->set_flashdata('index', 'text message');
redirect('controller/view', 'refresh');
}
controller/view.php
<div>
<?= (isset($this->session->flashdata('index'))) ? $this->session->flashdata('index') : ''?>
</div>
Flashdata is designed to be used moving from 1 page to another (redirects), you typically use it after a post, the return a success/failure message.
the reason for this:
[flash:old:message] =>message 1[flash:new:message]=>message 2
occurring is because flashdata is retained for 1 additional page load (so you can use $this->session->keep_flashdata() if required... as you are triggering flashdata by refreshing the page to generate these results its confusing things and not designed for use this way..
This really seems to be an issue occurring due to the way you are using flashdata than it displaying the incorrect data.
A working example of using flashdata is below (even without a redirect)
controller:
public function index()
{
if (!$this->input->post()) {
$this->load->view('playland/index');
}else{
if ($this->input->post('submit') == "submit") {
$data['firstname'] = $this->input->post('firstname');
$data['lastname'] = $this->input->post('lastname');
$this->session->set_flashdata('test', 'data posted');
$this->load->view('playland/retrieve', $data);
}
}
}
index view:
<html>
<body>
<?php print_r($this->session->userdata)?>
<form method="post" action="playland">
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
retrieve view:
<html>
<body>
<?php echo $this->session->flashdata('test') ?><br>
<p>
First Name:<br>
<?php echo isset($firstname) ? $firstname : '';?><br>
Last Name:<br>
<?php echo isset($lastname) ? $lastname : '';?><br>
</p>
Click to refresh the page
Return to original page
</body>
</html>

Cross Domain Ajax Issue

I have two files
1) index.php(picks data from the code editor and submits for processing via Jquery Ajax to exec.php)
2) exec.php (currently just transfer the data it recieved via index.php using jsonp)
Code of index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function test() {
var code = document.getElementById('code').value;
var code_data = "code=" + code;
alert(code_data);
$.ajax({
type: "POST",
crossDomain: true,
url: "http://code1.guru99.com/exec.php",
data: code_data,
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
alert("End of Test");
}
</script>
<form name="myform" id="myform" method="POST" class="code-box">
<textarea name="code" id="code"><?
$code='<?php
"Hello";
?>';
echo $code;
?>
</textarea> <!-- for add html tag in text area nad print the code-->
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="submit" value="Run" id="submit" onClick="test();"><!--<img id="ajax-loader" name="ajax-loader" src="/img/ajax-loader.gif" class="hidden" style="vertical-align:middle" />-->
</form>
<div name="label" id="label"> </div>
<div name="out" id="out"> </div>
Code of exec.php
<?php
$code=$_POST['code'];
$fp=fopen("file.txt","w"); // Storing the data into a file just to know that data is passed
fwrite($fp,$code);
fclose($fp);
header('Content-Type: application/jsonp');
echo $_GET['callback']."(".json_encode($code).");"
?>
The problem is data just does not pass into exec.php. I am not sure why...
The code is live at http://code.guru99.com/php/
Please help...
You cannot use AJAX to do this. Instead consider posting from a hidden Iframe using a regular FORM and setting the action to the URL you desire. You can still submit the form using JavaScript.
You can also listen to the onload event on the iframe to detect when your post has completed.
Alternately, you can use a server-side proxy.
The code syntax is correct.
May the problem could be with your server

Couldnt get CSRF to work with ajax (CI 2.1)

i am trying to get CSRF work with ajax in my CI 2.1 application.
i have searched about this and found few guidlines, but couln't resolve the problem
http://ericlbarnes.com/post/10728867961/codeigniter-csrf-protection-with-ajax
http://www.beheist.com/index.php/en/blog/csrf-protection-in-codeigniter-2-0-a-closer-look
http://aymsystems.com/ajax-csrf-protection-codeigniter-20
i have set two different tokens for two token values in the config
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'token01';
$config['csrf_cookie_name'] = 'token02';
$config['csrf_expire'] = 7200;
Here is my view, i am using form_open
<?php echo form_open("http://localhost/pis/user"); ?>
<div id="inputs">
<?php echo form_input($username);?>
<?php echo form_password($password);?>
</div>
<div id="actions">
<div style="float:left"><?php echo form_submit($submit);?>
<!-- <input type="button" value="Login" id="submit" name="submit" onclick="clicksubmit()" /> -->
</div>
</div>
<?php echo form_close();?>
I am using this javascript to make async call
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(
function(){
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
csrf_token_name: $("input[name=token01]").val()
};
$.ajax({
type: "POST",
url: "http://localhost/pis/user",
data: form_data,
success:
function(data){
$("#debug").html(data.message).css({'background-color' : data.bg_color}).fadeIn('slow');
}
});
return false;
});
});
</script>
When i run this i am getting a "500 Internal Server Error" along with the "An Error Was Encountered, The action you have requested is not allowed" as a response. Firebug shows the POST data parameters correctly.
eg: username=root&password=root&csrf_token_name=31961f17de5fa2df657ab1aba880f718
How ever if i removed the csrf, ajax request runs fine and i get 200 as response
Can anyone help me please?
Even better, you can just let jQuery serialize the form data for you:
var form_data = $(this).serialize();
This way you won't have to worry about inputs being renamed or more fields being added.

Ajax form submit. form submitted twice

I am working with cakePHP and in my view I have a form which has an ajax submit button. I rendered it using the cake helpers.
<form method="post" class="form-class" id="form-id" name="form1" style="display: none">
*[content for the form]*
<?php
echo $ajax->submit('Ok',
array(
'id'=> 'submit1',
'url'=> array('controller'=>'c','action'=>'action1'),
'complete'=> 'jsfunction()'
));
echo $form->button('Submit',array('id'=>'cancel','value'=>'Cancel','onClick'=>'clickCancel()'));
?>
</form>
When I click submit, the controller action is called twice. I searched stackOverlow if this question existed but couldn't find a valid solution. There are no syntax errors.
Help will be really appreciated. Thanks.
It sounds like the ajax event handlers aren't blocking the default behaviour.
Try setting the form's onsubmit behaviour inline to prevent it (as cake's helper does):
<form onsubmit="event.returnValue = false; return false;" method="post" class="form-class" id="form-id" name="form1" style="display: none">
I recommend checking out the FormHelper for some useful shortcuts around this.
This is the auto generated code:
$("#submit1367508668").bind('click', function(){
$.ajax({
async:true,
type:'post',
complete:function(request, json) {
getServerResponse(request)
},
url:'/recipients/add',
dataType:'json',
data:$(this).parents('form:first').serialize()});
blockUI();
})

ajax check if link is on website

I'm looking for a way to check if a link exists on a certain page. I know that this is possible with a ping, but I really don't know how to do this.
What I have is a list of links to other webpages, they should have a backlink to my page also. I want to check this, when the backlink is there, a text should appear, something like "ok" and when the result is negative, something like "no backlink"
I know the urls of the pages where my link should appear, in case you need to know that.
Any help would be great!
I have found a piece of code wich I think could be used to serve my needs. I self don't know how, but it would be great if anyone can help me with this.
This is the code:
<html>
<head>
<script language="javascript" type="text/javascript">
<!--
var ajax = new XMLHttpRequest();
function pingSite() {
ajax.onreadystatechange = stateChanged;
ajax.open('GET', document.getElementById('siteToCheck').value, true);
ajax.send(null);
}
function stateChanged() {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
document.getElementById('statusLabel').innerHTML = "Success!";
}
else {
document.getElementById('statusLabel').innerHTML = "Failure!";
}
}
}
-->
</script>
</head>
<body>
Site To Check:<br />
<input type="text" id="siteToCheck" /><input type="button" onclick="javascript:pingSite()" />
<p>
<span id="statusLabel"></span>
</p>
</body>
You can't natively use Javascript to parse external domains, I used a proxy page which sniffs the content and feeds it to the ajax callback.
My solution basically grabs the source of the site to check and sees if a string, which can be your site link matches. I would assume this should be sufficient rather than trying to parse and look for anchors, but you can be as thorough as you want ( parse the whole thing as a DOM element and look for href attribute value ).
Let me know if you run into any issues.
<?php
$query = isset($_POST['submitted']) ? true : false;
if ( $query ) {
$url = #file_get_contents( $_POST['site-url'] );
if ( $url && strlen( $url ) > 0 ) {
$checkFor = $_POST['check-for'];
$match = preg_match( '/' . $checkFor . '/', $url );
echo $match ? 'string (link) is found' : 'string not found';
} else {
echo 'could not connect to site..';
}
exit;
}
?>
<form action="" id="site-checker">
<div class="field">
<label for="site-url">Site to check:</label>
<input id="site-url" name="site-url" value="http://jquery.com">
</div>
<div class="field">
<label for="check-for">Check for:</label>
<input id="check-for" name="check-for" value="docs.jquery.com">
</div>
<input type="hidden" name="submitted" value="true">
<input type="submit">
</form>
<div id="result"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$('#site-checker').submit(function(e) {
e.preventDefault();
$.ajax({
url:'check.php',
type:'POST',
data:$('#site-checker').serialize(),
success:function(html) {
$('#result').html( html );
}
});
});
</script>
IMHO it would be better to perform this task in a server side script. Depending on your platform there might be functions for sending HTTP requests and HTML parsing which is what you need here. Javascript has cross domain restrictions which will prevent you from sending ajax requests to different domains than the one that is hosting the web page.

Resources