Ajax function call not working - javascript

I am trying to learn Ajax function calls in jquery. But I could not get the expected output. My code is below
The HTML and Script File is stored in the file 'addevent.php'
HTML Code:
<form id="addinfo">
Year: <div class="styled-select">
<select id="year">
<option>2017</option><option>2018</option>
<option>2019</option><option>2020</option>
</select>
</div>
Team:<div class="styled-select">
<select id="team">
<option>UG</option><option>PG</option>
</select>
</div>
<button class=btn name="add_event" id="add_event" />Add Event
<span id="result"></span>
</form>
</body>
</html>
Script Part:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: 'checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
}
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
The code in the file checkevent.php is below
header("Content-Type: application/json", true);
$db = new PDO('mysql:host=localhost;dbname=register;charset=utf8mb4', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$year =$_POST['year'];
$team =$_POST['team'];
$table=$team.$year;
try
{
if ($db->query("SHOW TABLES LIKE '" . $table . "'")->rowCount() > 0)
{
$r=array("result"=>"already stored");
echo json_encode($r);
}
else
{
$r=array("result"=>"continue");
echo json_encode($r);
}
}//end of try
catch(PDOException $e)
{
$r=array("result"=>"error");
echo json_encode($r);
}//end of catch
?>
Please Note: I have stored the file 'addevent.php' (HTML+Script) in the location 'registration/view/'
The checkevent.php file is stored in the location 'registration'
I tried to check if the button click function for add_event button is working by placing an alert inside it. But it doesn't work.
My expected output is if the table exist the span should display 'already stored' else it should say 'continue'
P.S: I am new to using these ajax call,so sorry if this seems silly. Please help to understand these concepts clearly.
Thanks in advance

You change this line :
url: 'checkevent.php',
By this :
url: '../checkevent.php',
Type F12 and inspect your ajax Call in the console to see if everything is OK

EDIT
OK got it. You missed a comma between success and error callbacks, which broke your Javascript...
Please change script to this and it should work:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: '/registration/checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
},
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
You have a <button> element inside a form. The default type of a button is type="submit" and therefore the form is submitted before the button onclick listener works. Also you need to close a button element with </button>
Try to change it from
<button class=btn name="add_event" id="add_event" />Add Event
to
<button type="button" class=btn name="add_event" id="add_event" >Add Event</button>
As for the ajax URL, if you are running it from a page located in 'registration/view' and you're calling a page located in 'registration', you need to change the url to something like: url: '/registration/checkevent.php'
because the php file isn't located in the same place as the script that's calling it.
Good luck

Related

Jquery Ajax is not working with Codeigniter

I am a ajax beginner, Here I am trying to show a text box value in same page using Ajax.
My Controller code:
<?php
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
$this->load->view('ajaxtest');
$fullname = $this->input->post("fullname");
echo $fullname;
}
}
?>
Here is my view code:
<head>
<script src="<?php echo base_url();?>assets/js/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post">
<input type="text" id="fullname"/>
<input type="button" value="getinfo" id="getinfo"/>
<span id="mytext"></span>
</form>
</body>
When I click on the button getinfo, I want to show the text inside the text box as span text. But now it shows nothing..
Updated:
After experts' opinion, I edited some text(see my edit note), Now When i click on the button, it shows again a textbox and a button.. !!
Did you set the base_url variable with a link on the Javascript?
Because your post url contains this variable and you need set this to make it work. So initialize the variable with the base_url link.
See the corrected example below . Set your domain instead of the yourbaseurl.com
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Your base_url variable seems to be undefined in your JavaScript.
One simple approach to get the base URL is to echo it out in a hidden input, and then grab the value of that input in your JS code:
HTML
<input type='hidden' id="baseUrl" value="<?php echo base_url(); ?>" />
JS
var base_url = $('#baseUrl').val();
$.ajax({
type: "POST",
url: base_url + "/merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
// ...
you are passing in textbox as parameter from your ajax to controller and trying to get POST data with name fullname. That wont work, since you passed in the name of parameter as textbox, access that in your post, as :
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
//you dont need to load view so comment it
//$this->load->view('ajaxtest');
$fullname = $this->input->post("textbox"); //not fullname
echo $fullname;
}
}
js
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function() {
var fullname = $("#fullname").val();
alert("Fullname:" + fullname); //do you get this alert
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: fullname},
cache:false,
success:function(data){
alert("Response:" + data); //do you get this alert
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Try using this:
<base href="<?=base_url();?>">
<script src="assets/js/jquery-latest.min.js"></script>
And this in ajaxtest:
$this->load->helper('url');
And also Comment out this:
// $this->load->view('ajaxtest');
Might be a little late with this response - but someone might find this while searching for a solution.
I was having the same issues with Codeigniter and JQuery ajax/post response. I could not get this to work no matter what I tried.
In the end, it turned out to be php_error that was causing the problem. Once I removed it, everything worked fine with my post/response.

Post variables to php file and load result on same page with ajax

I have tried searching quite a bit but can't seem to make anything work.
I am trying to make a form that sends info to a PHP file and displays the output of the PHP file on the same page.
What I have so far:
HTML:
<html>
<form id="form">
<input id="info" type="text" />
<input id="submit" type="submit" value="Check" />
</form>
<div id="result"></div>
</html>
JS:
<script type="text/javascript">
var info= $('#info').val();
var dataString = "info="+info;
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
});
</script>
PHP:
<?php
$url = '/api.php?&info='.$_POST['info'];
$reply = file_get_contents($url);
echo $reply;
?>
When I set the form action to api.php, I get the result I am looking for. Basically what I want is to see the same thing in the "result" div as I would see when the api.php is loaded.
I cannot get any solutions to work.
Your click event is not stopping the actual transaction of the page request to the server. To do so, simply add "return false;" to the end of your click function:
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
return false;
});
Additionally, you should update the type="submit" from the submit button to type="button" or (but not both) change .click( to .submit(
Thanks everyone for your help, I have it working now.
I was doing a few things wrong:
I was using single quotes in my php file for the URL and also for the $_POST[''] variables.
I needed to add return false; as Steve pointed out.
I did not have a "name" for the input elements, only an ID.
I think Your code evaluate dataString before it is filled with anything. Try to put this into function of $.ajax. The code below.
/* ... */
$('#submit').click(function (){
$.ajax({
var info= $('#info').val();
var dataString = "info="+info;
/* ... */

Using AJAX/Jquery to Replace div

I am trying to set the content of an empty div after an AJAX call with the data message. I also wired the function to my CHtml::submitButton, which should call the function when clicked, but nothing is happening. Any suggestions?
<div id="myResult">
</div>
JavaScript:
function successMessage(){
$.ajax({
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
PHP:
echo CHtml::beginForm(array('myForm'), 'get', array('form'));
echo '<div class="row form">';
echo '<div class="row buttons">';
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
echo '</div>';
echo '</div>';
Your problem relies in the following line:
$('myResult').html(data);
Here, you are trying to do a jquery selection to an element, which you are not using in your html (this is only possible via pollyfils). So you have to select the element by its ID:
$('#myResult').html(data);
And another thing i've seen, what is the url where you are doing the request?
<script>
function successMessage(){
$.ajax({
type: "GET",
url: "/please/add/an/url/",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
</script>
first of all, when you are using onclick function like this :
<input type="submit" onclick="successMessage()">
you should use this instead:
<input type="submit" onclick="successMessage();result false;">
but when you are already using jquery, then better approach is:
$( document ).ready(function() {
successMessage(){
// your ajax goes here
}
$('#myResult').click(function(e){
e.preventDefault();
successMessage();
});
});
Then you need to repair your successMessage function. You see, the data you are setting there are not the data, that are coming out as an output. If you need ajax then you probably want to get the result from some php script on some other url. Then you should do it like this :
function successMessage(){
$.ajax({
type: "GET",
url : 'index2.php',
dataType: "json",
data: { mydata: '<div> Replace div with this content</div>'},
success: function(data){
$('#myResult').html(data);
}
})
}
Then you need a php file named index2.php which can look like this :
<?php
echo json_encode($_GET['variable']);
?>
And i dont know if this your line :
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
also put the </form> tag after the form to close it.
This should work for you. I tried it and it works fine.
Try this:
$.ajax({
url: "test.html",
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('#myResult').html(data);
}
})
selector jQuery incorrect in response ajax. and define Url in ajax.

combine jQuery click handler with php header on same button

I have a button that is now inside a little form:
<form name="picSubmit" method="post">
<button class="btn btn-block btn-default" id="upload"><?php echo $lrow[10]; ?> <span class="glyphicon glyphicon-forward"></span></button>
</form>
then my code on top of the page:
<script language="JavaScript" src="js/cameraUserScript.js"></script>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
header('Location: view-subscribe');
}
?>
This is some javascript/jQuery ajax code to send the content inside a <div> and a picture that i have taken to a php page where i use this content to get some data out of my database and to rename and save that picture into a folder
document.getElementById("upload").addEventListener("click", function(){
var dataUrl = canvas.toDataURL();
var idVal = $('.hiddenId').html();
$.ajax({
type: "POST",
url: "incl/camsave.php",
data: {
imgBase64: dataUrl,
idVal: idVal
}
}).done(function(msg) {
console.log('saved');
});
I added a click event on that submit button ID so that when i click this script has to run. It works in Chrome, but because in Chrome you allways have to click the trust button if you use mediahandling i want to use Mozilla but there it isn't working... Does it has something to do with the combination of the submit button and the click event?
Thanks for the help!
I'm not sure why you're mixing vanilla JS and jQuery here, but you can likely solve this by changing your code to this -
$('#upload').click(function() { // you can use jQuery here too
var dataUrl = canvas.toDataURL();
var idVal = $('.hiddenId').html();
$.ajax({
type: "POST",
url: "incl/camsave.php",
data: {
imgBase64: dataUrl,
idVal: idVal
}
}).done(function(msg) {
console.log('saved');
});
});

jQuery ajax form doesn't work

I tried many ways to create a simple jquery ajax form but don't know why it is not submitting and/or returning the notification.
Here is my code:
Javascript
...
<script type="text/javascript" src="assets/js/jquery1.11/jquery-1.11.0.min.js"></script>
...
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
HTML
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<a type="submit">Sign up!</a>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
PHP
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
return json_encode($return);
Solved:
There were three problems. And different users solve each of these problems.
In PHP, you must "echo" the return array instead of "return"
At first, you should use a submit button instead of an anchor in the form
In the input, you must set both "id" and "name"
If any of these users want, you can edit or add a new answer with these details, and the points are yours.
You need to do 3 things.
First, wrap your jQuery codes inside $(document).ready() function,
<script type="text/javascript">
$(document).ready(function()
{
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
});
</script>
Second, Add a submit button to your form. Also you are missing the name attribute for the email input field. That causes the error in the php file.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="signup" value="Sign Up!"/>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
Third, echo the results since you are using AJAX to submit the form. return will not have any effects.
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
echo json_encode($return);exit;
I checked and it's working fine.
Hope this helps :)
The problem is in your form.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
The php code needs to echo instead of return.
just like this:
echo json_encode($return);
Also, your form needs a submit button - type="submit" on an <a> tag doesn't trigger the browser's functionality for handling <form>s
Finally, you need to ensure that your special submit handler is loaded at just the right time -- which, if it is included at the bottom of the page, right before the footer, it should be just fine. However, you can ensure this by wrapping it in
$(document).ready(function(){
//[...]
});
doesn't your a type="submit" need to be an input instead? or a button
I am trying to call webmethod in a ajax using jquery in asp.net, but sometimes it works well and sometimes it doesn't.
Here is my ajax code :
$.ajax({
type: "POST",
url: "frmTest.aspx/fncSave",
data: "{}"
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
cache: "false", //True or False
success: function (response)
result = response.d;
if (result != "") {
alert(response);
}
},
Error: function (x, e) {
alert("err");
return false;
}
});
Here My Server Side Code :
<WebMethod()>
Public Shared Function fncSave() As String
Dim sResult As Int16
Try
Dim obj As New ClsCommon()
sResult = obj.Save()
Catch ex As Exception
ex.Message.ToString()
End Try
Return sResult
End Function
$(this) in the "ajax" function is not the form.
So just try:
$('#form_signup').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
type: 'POST',
url: 'signup.php',
data: $this.serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
I admit i didn't check the rest of the code, im pretty sure thats the problem.
Of course if the problem still goes, just "f12" and check console and network for server request and headers, make sure all the params are there.
Hope that helped

Categories

Resources