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
Related
can anyone please help me with sending the below form using Ajax. All I want is to send it to the trolley1.php page for processing, no call backs or anything like that. Basically replicate the form but sending it with Ajax so the page does not go to the trolley1.php page. I have tried so many methods but have not been able to do this. Bill Gates or Steve Wozniak if you guys are reading this, please help
This gives me a console $.Ajax is not a function in the console
<script>
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
}
});
});
</script>
<?php
echo "
<div class='col-sm-3 mt-5'>
<form class='ajax' method='post' action='trolley1.php?action=add&id=$id'>
<div class='products'>
<a>$img</a>
<input type='hidden' name='id' value='$id'/>
<input type='hidden' name='name' value='$product'/>
<input type='hidden' name='price' value='$price'/>
<input type='text' name='quantity' class='form-control' value='1'/>
<input type='submit' name='submit' style='margin-top:5px;' class='btn btn-info'
value='Add to Cart'/>
</div>
</form>
You have one syntax error in your JS Code - see correct code
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
});
});
});
And you are using jQuery as additional javascript libary. jQuery uses $ to access the methods (e.g. $.ajax) Thats the reason why you get undefined as error.
So you need to load the libary first at the beginning of your page (inside <head>). E.g. directly from their CDN
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Then it should work for you
Play framework 2.4.x. A button is pressed on my home page that executes some code via Ajax, and returns its results beneath the button without loading a new page. The results wait for a user to input some text in a field and press "submit". Those results Look like this:
<li class="item">
<div>
<h3>Email: </h3>
<a>#email.tail.init</a>
<h3>Name: </h3>
<a>#name</a>
</div>
<div>
<h3>Linkedin: </h3>
<form class="linkedinForm" action="#routes.Application.createLinkedin" method="POST">
<input type="number" class="id" name="id" value="#id" readonly>
<input type="text" class="email" name="email" value="#email" />
<input type="text" class="emailsecondary" name="emailsecondary" value="" />
<input type="text" class="name" name="email" value="#name" />
<input type="text" class="linkedin" name="linkedin" value="" />
<input type="submit" value="submit" class="hideme"/>
</form>
</div>
<div>
<form action="#routes.Application.delete(id)" method="POST">
<input type="submit" value="delete" />
</form>
</div>
</li>
Along with some jquery that slides up a li after submission:
$(document).ready(function(){
$(".hideme").click(function(){
$(this).closest('li.item').slideUp();
});
});
However, since a form POST goes inside an Action that must a return an Ok(...) or Redirect(...) I can't get the page to not reload or redirect. Right now my Action looks like this (which doesn't compile):
newLinkedinForm.bindFromRequest.fold(
errors => {
Ok("didnt work" +errors)
},
linkedin => {
addLinkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
if (checkURL(linkedin.url)) {
linkedinParse ! Linkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
Ok(views.html.index)
}else{
Ok(views.html.index)
}
}
)
Is it possible to return Ok(...) without redirecting or reloading? If not how would you do a form POST while staying on the same page?
EDIT: Here is my attempt at handling form submission with jquery so far:
$(document).ready(function(){
$(".linkedinForm").submit(function( event ) {
var formData = {
'id' : $('input[name=id]').val(),
'name' : $('input[name=name]').val(),
'email' : $('input[name=email']).val(),
'emailsecondary' : $('input[name=emailsecondary]').val(),
'url' : $('input[name=url]').val()
};
jsRoutes.controllers.Application.createLinkedin.ajax({
type :'POST',
data : formData
})
.done(function(data) {
console.log(data);
});
.fail(function(data) {
console.log(data);
});
event.preventDefault();
};
});
This is an issue with the browser's behavior on form submission, not any of Play's doing. You can get around it by changing the behavior of the form when the user clicks submit.
You will first want to attach a listener to the form's submission. You can use jQuery for this. Then, in that handler, post the data yourself and call .preventDefault() on the event. Since your javascript is now in charge of the POST, you can process the data yourself and update your page's HTML rather than reloading the page.
What you need is use ajax to submit a form, check this: Submitting HTML form using Jquery AJAX
In your case, you can get the form object via var form = $(this), and then start a ajax with data from the form by form.serialize()
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
In order to accomplish this task, i had to use play's javascriptRouting
This question's answer helped a lot.
I'm not experienced with jquery so writing that correctly was difficult. For those that find this, here is my final jquery that worked:
$(document).ready(function(){
$("div#results").on("click", ".hideme", function(event) {
var $form = $(this).closest("form");
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();
var emailsecondary = $form.find("input[name='emailsecondary']").val();
var url = $form.find("input[name='url']").val();
$.ajax(jsRoutes.controllers.Application.createLinkedin(id, name, email, emailsecondary, url))
.done(function(data) {
console.log(data);
$form.closest('li.item').slideUp()
})
.fail(function(data) {
console.log(data);
});
});
});
Note that my submit button was class="hideme", the div that gets filled with results from the DB was div#results and the forms were contained within li's that were class="item". So what this jquery is doing is attaching a listener to the static div that is always there:
<div id="results">
It waits for an element with class="hideme" to get clicked. When it gets clicked it grabs the data from the closest form element then sends that data to my controller via ajax. If the send is successful, it takes that form, looks for the closest li and does a .slideUp()
Hope this helps
I am trying to take simple text from a form, pass it to my controller via ajax, and have that send to the data base.
View
<form method="POST">
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="rate" type="submit">
</form>
<script type = "text/javascript">
$(function(){
$("#rate").click(function(){
dataString = $("#email").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/trial/insert_into_db",
data: dataString,
});
});
});
</script>
The controller code and the model code work fine. I am almost sure that it is the ajax code that is not working.
Any information would be greatly appreciated!
Thank you.
One thing missing from your posted code is disabling the default form submission. There still could be other issues.
You don't specify an action so by default the action is the same url as the page.
<form method="POST">
You are doing AJAX but you have not disabled the default behavior with return false or event.preventDefault
$("form").submit(function(event) {
event.preventDefault();
// or
return false;
});
I prefer preventDefault() but the point is you need to prevent the default browser behavior.
Edit: This is how I would submit the form with AJAX.
If you had more than one form button to consider then
$("form").submit(function(e) {
e.preventDefault();
});
$("#rate").click(function(e) {
$.ajax({ ... });
});
But it's (marginally) easier to do it with one handler. I'd also stick the action on the form so the form still submits to the correct url if the javascript failed.
<form id="myform" action="<?php echo base_url();?>index.php/trial/insert_into_db" method="post">
Instead of handling the button click handle the form submission
$("#myform").on("submit", function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type = "post",
url = $(this).attr("action"),
data = formData
})
.done(function(result) {
// do something with the response
});
});
I have the following script:
<script>
/* attach a submit handler to the form */
$("#Submitter<? echo $count; ?>").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/*clear result div*/
$("#result").html('');
/* get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "<? echo Configure::read('Burl') . $cat['sub_cat_url']; ?>",
type: "post",
data: values,
success: function(){
$("#prod_add").show();
$("#prod_add").delay(2500).animate({opacity: 0},5000);
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
});
</script>
which works, the form is posted. But how do I get access to the post variables on the same page without refreshing? Are they stored in an JavaScript array or something?
this is my form:
<form method="post" id="Submitter<? echo $count; ?>">
<input type="hidden" name="CartAdd" value="1">
<input type="hidden" name="Productcode" value="<? echo $row['Titel']; ?>">
<input type="hidden" name="Description" value="<? echo $row['Omschrijving']; ?>">
<input type="hidden" name="Tumbnail" value="<? echo $row['Afbeelding']; ?>">
<input type="SUBMIT" value="Order Now" class="order_button">
I still don't understand whats the question is, but i will give it a try:
But how do I get access to the post variables on the same page without refreshing?
There is no concept like POST variables client side so i guess you mean the value of the form fields you post to the server?
Just access them by id/name:
var valueOfTumbnail = $('input[name="Tumbnail"]).val();
If you want to access the whole data which gets posted use form.serialize() like in your method:
var serializedData = $("form").serialize();
But i don't think that this is what you want.
EDIT:
Try to execute the code when the document was loaded and processed by the browser:
$(document).ready(function() {
// here your code...
});
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.