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
Related
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 Wanna access the hidden values in ajex posted in a div
<input type="button" value="button 1" class="btn">
<div id="div"><div>
<script>
$.ajax({
url:"btn2.php", success:function(data){
$('#div').html(data);}
});
$( "#table" ).on( "click", ".upd", function() {
alert("button is wrking");
});
</script>
PHP
echo"<input type='button' value='button 2' class='btn'>
<input type='hidden' value='dishonest' id='hdn'>";
can any one help me on this.. i have no idea what to do ...
basically i want value of hidden
var h=$('#hid').val();
but that doesn't work bcoz its posted later in div ...
You will get value from ajax success
success:function(data){
$('#div').html(data);
var h=$('#hid').val();
alert(h);
}
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
I am trying to make an Ajax call using JQuery to a servlet that returns a JSON object.
In the JSP page I have a form, at first I didn't know how the get the data from the form,
then I found .serialize.
I have the following JavaScript:
$(document).ready(function() {
$("#submit").click(function blabla() {
var formData = $('form').serialize();
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
});
});
});
The information comes from the following form:
<form method= post">
<div class="searchCiteria">
<div id="searchValueBlock1">
<div><span class="label">Case ID:</span><input type="text" name="messagecaseid" size="25"/></div>
<div><span class="label">Onderwerp:</span><input type="text" name="messagesubject" size="25" /></div>
<div><span class="label">Afzender:</span><input type="text" name="messagesender" size="25"/></div>
<div><span class="label">Ontvanger:</span><input type="text" name="messagereceiver" size="25"/></div>
</div>
<div id= "searchValueBlock2">
<div><span class="label">Datum:</span><input type="text" name="date1" size="25"/></div>
<div><span class="label"></span><input type="text" name="date2" size="25"/></div>
<div class="submit">
<input type="submit" value="Search">
</div>
</div>
</div>
</form>
When I use the action parameter in the form the servlet repondes like it should.
But I can't seem to get the Ajax call to work.
What am I doing wrong?
you must add the success param to ajax function
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
The default behavior of the submit button is to POST the form, which will redirect the user to a URL of the action attribute ond the form. When you don't(which you should...) have an action attribute it will reload the page. To prevent the page from reloading you need to prevent the default behavior by returning false at the end of your $("#submit").click function.
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.