Can't process simple form submitted by jQuery ajax - javascript

My form:
<form id="new-protocol-form" method="post" role="form">
<textarea name="text"></textarea>
</form>
My jquery ajax:
$('#submitProtocol').click(
function() {
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function() { alert{'ok'} },
error: function() { alert('error'); }
});
}
);
My newProtocol.php:
<script>
alert(<?php echo $_POST['text']; ?>);
</script>
Alert window with 'ok' text triggered by ajax 'success' method is shown, but I can't get alert window with $_POST['text'] value from newProtocol.php file. No error in javascript console.

You need to use $_POST['text']. You're using parentheses where you shouldn't be.
In addition, since you're using AJAX you probably don't want to navigate to the other page. Your alerts in your success function will never fire if you don't prevent the default behavior.
newProtocol.php
<?php
echo $_POST['text'];
?>
jQuery
$('#submitProtocol').click(function(event) {
event.preventDefault(); // stop the default click behavior
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function(data) {
console.log(data); // show the text being returned
},
error: function() { console.log('error'); }
});
}
);
Also, quit using alert() for getting return values and trouble-shooting.

First, $_POST is not a function, it's an array. So it should be $_POST['text']. Also,
<script>
alert(<?php $_POST('text'); ?>);
</script>
will not create an alert like you expect since an async request does not run any javascript in the target page.
Since you're trying to test if the AJAX is working, the best way is to check what was the date returned from that request. Example:
//...
success: function(data) { console.log(data) },
//...

Related

Javascript function returning with a hash in the url despite returning false

I have this link that is supposed to delete an entry and refresh a div via ajax. However, for some reason it isn't working at all and its just shifting the page up and adding a # to the url.
If I add an alert to output the id and user_id, it shows up and no # is added to the url.
This is the code
<script>
function removeExistingBranch(id,user_id){
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/RemoveUserBranch/'); ?>",
data:'id='+id+,
'&user_id'+user_id,
beforeSend: function () {
$('.loading').show();
},
success: function(data){
// $( "#existing_branch_container" ).load( "<?php echo site_url($this->data['controller']);?>/LoadUserBranches" );
$('.loading').fadeOut("slow");
},
});
return false;
}
</script>
Remove
Could someone take a look and see if I am missing something?
You have syntax error in the ajax call. Change it
data:'id='+id+,'&user_id'+user_id,
to
data:'id='+id+'&user_id'+user_id,

Yii2 Ajax Submission not working

Iam new to Yii2 and Ajax
I want to add multiple job for a work ,for that I pass id to WorkJobs Controller
This is my code for ajax submission
<?php
$this->registerJs(
'$("body").on("beforeSubmit", "form#w1", function() {
var form = $(this);
if (form.find(".has-error").length) {
return false;
}
$.ajax({
var jobid = "<?php echo $id;?>";
url: form.attr("work-jobs/create&id="+jobid),
type: "post",
data: form.serialize(),
success: function(errors) {
alert("sdfsdf");
// How to update form with error messages?
}
});
return false;
});'
);
?>
But it's not working ,I don't know what's wrong in my code ,please help ...........
change your code like below
<?php
$url=Yii::$app->urlManager->createUrl(['work-jobs/create','id'=>$id]);
$this->registerJs(
'$("body").on("beforeSubmit", "form#w1", function() {
var form = $(this);
if (form.find(".has-error").length) {
return false;
}
$.ajax({
url: "$url",
type: "post",
data: form.serialize(),
success: function(errors) {
alert("sdfsdf");
// How to update form with error messages?
}
});
return false;
});'
);
?>
Building off jithin's answer, make the following changes to your $.ajax() call
Make sure your URL is in quotes. It is a common mistake to forget to quote the URL when interspersing it with PHP. [jithin]
Unlike jithin's answer, you should do the following
instead of responding to the beforeSubmit event, handle the submit event. This would allow the Yii clientsoide validations do their job
the ajax.success callback takes data as the argument; not error, there's the ajax.failure callback for errors
Try using createAbsoluteUrl() in url like this:
url: "<?php echo Yii::app()->createAbsoluteUrl(\"work-jobs/create&id=\")"+jobid

Ajax form submit on current page

I want to submit a form by ajax and send it to my current page to prevent a refresh.
This my HTML:
<form id="suchForm" method="post" action="<?=$PHP_SELF?>">
<input type="text" id="suche" name="suche" placeholder="Suchen"/>
<input type="submit style="display:none;" />
</form>
By the way the submit button is hidden, so I am submitting the form by pressing return on my keyboard.
This is my PHP Script:
if ( $_SERVER["REQUEST_METHOD"] == 'POST' ) {
$suche = $_POST['suche'];
if (!empty($suche)) {
<?php echo $suche ?>
}
}
And finally, this is my current Ajax script:
var frm = $('#suchForm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
The form is submitting by Ajax successfully. The Problem: The Ajax Script prevents a refresh of the site, so nothing is shown by the PHP script (<?php echo $suche ?>). Do you have any solution to send the form with Ajax, preventing the refresh (cause some javascript should happen after the submit) and show the PHP echo?
Try replacing alert('ok'); with the code to display the ajax response. Something like this should work -
var frm = $('#suchForm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$('<NAME_OF_YOUR_CONTAINER_TO_DISPLAY_RESPONSE>').html(data);
}
});
ev.preventDefault();
});
If $suche is not empty, php will echo it. So if you could view the page at the time, you would see what you expect, but in this case, you have AJAX doing the submit for you, so AJAX is the one who can "see" that. If you want to display what AJAX can "see", then simply do whatever you want inside success: function()... that received the data.
You could alert(data) instead of alert("OK") to get more clues.

Ajax call request in CodeIgniter with CSRF enabled

I am using an ajax call to save value of a radio button through hidden field in database using ajax call, used an alert to see if its working, and it is.
The URL I mentioned in the ajax call is redirecting it to a controller but I used an alert to see if its working, but its not working. Can't locate what's the issue.
Here is the code of ajax call in view:
<script type="text/javascript">
$('#save').click(function(){
var hint=$('#hidfield').val();
alert('Oops, your response is '+hint);
$.ajax({
url: '<?php echo base_url();?>welcome/save_answer',
type: "post",
dataType: "html",
data:{hint:$hint, <?php echo $this->security->get_csrf_token_name();?>: "<?php echo $this->security->get_csrf_hash();?>"},
success: function(data) {
}
});
});
</script>
Here is the controller:
function save_answer()
{
alert('You Can Do It !!');
$data = array(
'hint'=>$this->input->post('hint')
);
$this->base_model->save_answer($data);
}
Here is the model:
function save_answer($data)
{
$this->db->insert('questions',$data);
}
Please suggest some way out.
You cannot used javascript "alert()" inside controller.
instead of "alert('You Can Do It !!');" use "die('You Can Do It !!');" to debug, and check in to your console.

Calling AJAX is not working onclick of button

I am calling an API from AJAX,
When I am Calling AJAX like this,
$(function (){
$.ajax({
type:'GET',
url :"/tournament",
dataType: 'json',
success: function(data) {
console.log('success',data);
},
error:function(exception){
alert('Exception:'+exception);
}
});
});
This is working fine without any errors but when I am using this..
$('#btnadad').on('click',function (){
alert("ok");
$.ajax({
type:'GET',
dataType: 'json',
url :"/tournament",
success: function(data) {
console.log('success',data);
},
error:function(exception){
alert('Exception:'+exception);
}
});
});
This popups "error" alert,
can anybody help me whats the error?
HTML Body is Like this,
<form>
<h2>
<font color="#FFFFFF">
<br><br><input type="text" name="name" placeholder ="Tournament Name"><br>
<table>
<?PHP
//print_r($teams);
for ($i = 0; $i < $count; $i++) {
?>
<tr>
<td><input type="checkbox" name=<?php echo $taemId[$i] ?></td>
<td><?php echo $teamname[$i] ?></td>
</tr>
<?php
}
?>
</table>
<button id="btnadad">ADD</button>
</form>
<script src ="/js/myjs.js"></script>
here I am calling one API and Displaying the Checkboxes Dynamically.
I am checking The Console...when I am clicking button ,the alert box is popping up and in networks tab tournament path's status is cancelled .when I am clicking it on to see the response it shows fail to load response data.
I have Tried calling this function in same html file in tag but it is also not working.
<script>
function getOnClick()
{
alert("ok");
$.ajax({
type: 'GET',
url: "http://harshal:8888/tournament",
success: function(data) {
alert("no error in alert");
console.log('success', data);
},
error: function() {
alert("error in alert");
}
});
}
and calling it on button's onclick Event ut it also gives me the same result
Thanks For the Help Friends,your Efforts matters a lot to me,I am feeling glad to tell you that I just found the answer for this the below code makes it happened ..
$('#btnadad').on('click',function (e){
alert("ok");
$.ajax({
type:'GET',
url :"/tournament",
dataType: 'json',
success: function(data) {
console.log('success',data);
},
error:function(exception){alert('Exeption:'+exception);}
});
e.preventDefault();
});
$ajax error function takes 3 parameters. Jquery ajax error
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred.
try changing like this
$('#btnadad').on('click',function (){
alert("ok");
$.ajax({
type:'GET',
dataType: 'json',
url :"/tournament",
success: function(data) {
console.log('success',data);
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
I got the same issue. If you use onclick, do not use a form. In local environment, it is working, but when you go to production, the ajax request is cancelling. The solution is removing the form tag and adding a div tag.

Categories

Resources