My original goal was to get a php file to execute on a button press. I used ajax. When the javascript was in the view, it worked.
However, I tried to switch the javascript to its own .js file and include it in the header. It doesn't work anymore. I am confused.
the model code:
public function insert_build($user_id)
{
$query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '$user_id')";
mysql_query($query) or die ('Error updating database');
}
Something interesting to note here is that when I include $user_id as a value, it completely negates my headertemplate. As in, it simply doesnt load. When I replace $user_id with a static value (i.e. '7') it works no problem.
This is my view code :
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<select name="buildID" class="buildClass">
<option value="0" selected="selected" data-skip="1">Build a Structure</option>
<?php foreach ($structures as $structure_info): ?>
<option name='<?php echo $structure_info['str_name'] ?>' value='<?php echo $structure_info['str_id'] ?>' data-icon='<?php echo $structure_info['str_imageloc'] ?>' data-html-text='<?php echo $structure_info['str_name'] ?><i>
<?php echo $structure_info['timebuildmins'] ?> minutes<br><?php echo $structure_info['buy_gold'] ?> gold</i>'><?php echo $structure_info['str_name'] ?></option>
<?php endforeach ?>
</select>
<div id="buildSubmit">
<input id ="btnSubmit" class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
Heres my .js file :
$(".button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php $this->structure_model->insert_build($user_id) ?>", //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
I am almost sure I know the problem: That structure_model->insert_build($user_id) ?> doesn't work when its outside the view. Though, I dont know the alternative.
I excluded the header file. I confirmed that the .js file is indeed being directed to the correct path.
Could someone please explain the correct way to do this? Thank you!
Did you move your javascript to a .js that is being directly accessed by the browser? I.E: If you view source, so you see the <?php ... ?> in the javascript code?
To me, it sounds as though the PHP is not getting parsed. If this is not the case, then can you please clarify.
If you need to include PHP variables in your javascript, you should use CI to generate the JS page for inclusion. You can even create a View that is purely JS and call it like a normal page.
Otherwise, if you want to seperate the JS from CI, you should reference JS variables instead of PHP. Then in your CI page somewhere, define them with a <script>var jsVar = <?php echo phpvar(); ?></script> tag.
When you move the js file to it's own file, php variables will not be accessible anymore. You can either move the js code back to your view file, or fetch the url through javascript. See below for example.
HTML:
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<input type="hidden" name="url" value="<?php $this->structure_model->insert_build($user_id) ?>" />
<!-- Rest of your code -->
</form>
</div>
Javascript:
$(".button").click(function(e){
var form_url = $(this).closest('form').find('input[name=url]').val();
e.preventDefault();
$.ajax({
type: "POST",
url: form_url, //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
Related
Updated: It still not work after I add "#".
I am new to ajax. I am practicing to send value to php script ,and get result back.
Right now, I met one issue which I can not show my result in my html page.
I tried serves answers online, but I still can not fix this issue.
My index.html take value from the form and send form information to getResult.php.
My getResult.php will do calculation and echo result.
How do I display result into index.html?
Hers is html code
index.html
<html>
<body>
<form name="simIntCal" id="simIntCal" method="post"
>
<p id="Amount" >Amount(USD)</p>
<input id="amount_value" type="text" name="amount_value">
<p id="annual_rate" >Annual Rate of Interest
(%)</p>
<input id="rate_value" type="text" name="rate_value">
<p id="time_years" >Time (years)</p>
<input id="time_value" type="text" name="time">
<input id="calculate" type="submit" value="Calculate">
</form>
<p id="amount_inteCal" >The Amount (Acount
+ Interest) is</p>
<input id="result" type="text">
</body>
</html>
ajax script :
<script>
$('#simIntCal').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'getResult.php',
data: $('#simIntCal').serialize(),
success: function (result) {
$("#result").text(result);// display result from getResult.php
alert('success');
}
});
});
</script>
getResult.php
<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
//do some calculation
$result=10;//set result to 10 for testing
echo $result;
}
?>
You are missing the '#' in front of your css selector for result.
$("result").text(result);// display result from cal.php
Should be
$("#result").text(result);// display result from cal.php
index.php
----php start---------
if(isset($_POST['name'])){
echo 'Thank you, '.$_POST['name']; exit();
}
----php end ---------
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function test(){
var formDATA = {'name': $('#input_name').val()}
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
$('#result').html();
}
});
}
</script>
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code.
Also don't forget to include your jquery resources.
In your html file where you want the result to display, you probably want to be using a div.
Currently your code is using an input field:
<input id="result" type="text">
And what you probably want is something like this:
<div id="result"></div>
Unless you were intending to have the result show up in an input field inside your form, and in that case, the input field isn't actually inside your form code.
I am using ajax to post data on the same page and trying to echo posted data with php with following script.
$('button').click(function(){
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function(){},
success: function(data){alert(data)},
error: function(err) {alert(err.responseText);}
})
})
and php script is :
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
my html is:
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
My problem is php does not echo posted data on page, but when i post form data on another php file which is same php script; php is able to echo posted data and ajax is alert that. please help me to resolve this issue. thanks
It's difficult to tell without seeing your entire PHP page as one listing, but from your description it sounds like your issue is either because of the way you are declaring your .click() event or the way you are posting to the page. The former is more likely.
The $.ajax() request will use an XMLHttpRequest object to POST to your PHP script. The PHP script should then take those values and generate the return string from the combination of the plain text in the script and the inserted echo'd values. This should then be received by the success method's callback function and alerted to your page as a blob of HTML text in the alert box.
Indeed, this is exactly what happens if I use the following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function() {},
success: function(data) {
alert(data);
},
error: function(err) {
alert(err.responseText);
}
});
});
});
</script>
</head>
<body>
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
</body>
</html>
However, if I comment out the lines for $(document).ready(function(){ and its corresponding end });, then nothing happens when I click.
So, try wrapping your .click() event definition in a $(document).ready().
I've been searching for a while but nothing I've found match what I need.
I've got a form with 2 variables (dropdownlist) to query a DB (PHP and SQL).
Names of my variables are : "province" and "candidat".
My result page is action.php with all the sql/php code for the results.
Everything is going very fine except that after clicking on the submit button, a new page is opening : action.php with the results of my request.
Now, I wish to display this results on the same page as my form (id = form). The id of the div to display results is"success" (<div id="success">). There is an action on my form : action="action.php", should I remove it ?
I know that I have to use AJAX method but nothing that I've found match my needs. The other point is that I wish to be able to make another query and display the new results in this area.
If you know the solution or a tutorial that fit my needs... MANY THANKS of your help !
Start here: http://api.jquery.com/jQuery.ajax/
And do something along the lines of this:
$.ajax({
url: "action.php",
cache: false
}).done(function( response ) {
alert( response );
$("#success").html(response); //put the response into a DIV with id="success"
});
I'd recommend being more specific with your HTML id's that you are using.
$(document).ready(function(){
var datastring = "your data that is pass for php file";
$.ajax({
url: "action.php",
data: datastring,
type: "post",
success: function(response) {
alert(response);
}
});
});
Here's the code :
PROVINCE
">
<?php
}
?>
</select>
CANDIDAT
<?php
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
?>
<option value="<?php echo $data['id_candidat']; ?>">
<?php echo $data['pren1']; ?> <?php echo $data['nom_candidat']; ?></option>
<?php
$id = $data['id_candidat'];
if ($id === $id)
{break;}
}
?>
</select>
<br/>
<input type="submit" class="submit" name="submit" value="ok" />
</form>
Content of action.php :
I am submiting a form to a php page using ajax in order to make a query.
The problem is that the $_POST is empty.
What am I doing wrong here?
Any ideas?
FORM
<div id="button_left">
<form>
<label>
<input type="text" class="search" size="30" style="margin-left:20px;" name="epitheto" id="epitheto" placeholder="Επίθετο" />
</label>
<label>
<input type="submit" value="Αναζήτηση" />
</label>
</form>
</div
FUNCTION
$(function () {
$('#button_left').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'people_name_query_final.php',
data: $('form').serialize(),
success: function () {
$("#pelates_last_name_query").slideDown("slow");
$("#pelates_last_name_query").load( "people_name_query_final.php");
}
});
});
});
PHP
if(isset($_POST['epitheto'])){
//some code
}
Add one argument to your success function:
success: function (response) {
$("#pelates_last_name_query").slideDown("slow");
$("#pelates_last_name_query").html( response);
}
and you will get response from php page....
P.S. Test php page should look like this (or whatever you want for response - you should ECHO something, send some output):
<?php
if(isset($_POST['epitheto'])){
print_r($_POST);
}
?>
so, vars are sent properly.... (i've tested it right now).
If your php page looks like code you atached/showed us - there is no any output, you didn't printed anything....
<form> element has submit event, <div> doesn't.
Change the first line to this:
$('form').on('submit', function (e) { // <-- change '#button_left' to 'form'
// (...) Code
}
I believe Amit might be correct. You are specifying the incorrect data to submit.
Change <form> to <form id="content">
Then change your JQuery code accordingly.
$('#content').on('submit', function (e) {//rest of your code//}
Another possible issue is that the scope on your URL is incorrect.
url: 'people_name_query_final.php', will work assuming the PHP script and JQuery are in the same directory.
Also, if you do print_r($_POST); exit; in your PHP script you see nothing?
Check the network tab on your browser developer tools to make sure the data is sent properly.
I have index.php with a form. When it gets submitted I want the result from process.php to be displayed inside the result div on index.php. Pretty sure I need some kind of AJAX but I'm not sure...
index.php
<div id="result"></div>
<form action="" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
</form>
process.php
<?php
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
?>
You really don't "need" AJAX for this because you can submit it to itself and include the process file:
index.php
<div id="result">
<?php include('process.php'); ?>
</div>
<form action="index.php" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
<input type="submit" name="submit" value="Submit">
</form>
process.php
<?php
// Check if form was submitted
if(isset($_GET['submit'])){
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
}
?>
Implementing AJAX will make things more user-friendly but it definitely complicates your code. So good luck with whatever route you take!
This is a jquery Ajax example,
<script>
//wait for page load to initialize script
$(document).ready(function(){
//listen for form submission
$('form').on('submit', function(e){
//prevent form from submitting and leaving page
e.preventDefault();
// AJAX goodness!
$.ajax({
type: "GET", //type of submit
cache: false, //important or else you might get wrong data returned to you
url: "process.php", //destination
datatype: "html", //expected data format from process.php
data: $('form').serialize(), //target your form's data and serialize for a POST
success: function(data) { // data is the var which holds the output of your process.php
// locate the div with #result and fill it with returned data from process.php
$('#result').html(data);
}
});
});
});
</script>
this is jquery Ajax example,
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
How about doing this in your index.php:
<div id="result"><?php include "process.php"?></div>
Two ways to do it.
Either use ajax to call your process.php (I'd recommend jQuery -- it's very easy to send ajax calls and do stuff based on the results.) and then use javascript to change the form.
Or have the php code that creates the form be the same php code that form submits to, and then output different things based on if there are get parameters. (Edit: MonkeyZeus gave you specifics on how to do this.)