Submit form for php without refreshing page - javascript

I've search for many solution but without success.
I have a html form;
<form id="objectsForm" method="POST">
<input type="submit" name="objectsButton" id="objectsButton">
</form>
This is used for a menu button.
I'm using jquery to prevent the site from refreshing;
$('#objectsForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function () {
alert('success');
}
});
});
In my php file I try to echo text to the body of my site;
<?php
if (isset($_POST["objectsButton"])){
echo '<div id="success"><p>objects</p></div>';
} else {
echo '<div id="fail"><p>nope</p></div>';
}
?>
I know the path to my php file is correct, but it doesn't show anything? Not even the "fail div".
Does anyone has a solution for me?
Thanks in advance!

The success function takes two parameters. The first parameter is what is returned from the php file. Try changing it to:
success: function (xhr){ alert(xhr);}

Based in your php source..
$.ajax({
type: 'post',
dataType: "html", // Receive html content
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function (result) {
$('#divResult').html(result);
}
});

PHP scripts run on the server, that means any echo you do won't appear at the user's end.
Instead of echoing the html just echo a json encoded success/ failure flag e.g. 0 or 1.
You'll be able to get that value in your success function and use jQuery to place divs on the web page.
PHP:
<?php
if (isset($_POST["objectsButton"])){
echo json_encode(1); // for success
} else {
echo json_encode(0); // for failure
}
?>
jQuery:
var formData = $('#objectsForm').serializeArray();
formData.push({name:this.name, value:this.value });
$.ajax({
type: 'post',
url: '/php/objects.php',
dataType: 'json',
data: formData,
success: function (response) {
if (response == 1) {
alert('success');
} else {
alert('fail');
}
}
});
EDIT:
To include the button, try using the following (just before the $.ajax block, see above):
formData.push({name:this.name, value:this.value });
Also, have the value attribute for your button:
<input type="submit" name="objectsButton" value="objectsButton" id="objectsButton">

Related

Send js value to php controller by ajax

I have this button
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
And this button related to this
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
I'm using this script to send value of button to my php controller
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable,
success: function (data){
}
});
}
When I use alert, the result of javascriptVariable is correct and I want it in my controller so I'm trying in my controller to do this:
if(isset($_POST['activation']))
{
$name = $this->input->post('myname');
var_dump($name);
}
But I get null value, what is the wrong?
When you pass data from the browser via AJAX only the data you pass in the data: parameter is sent to the PHP script.
So if you want to test for activation in the PHP script you must actually send that parameter
Also see the amendment to the data: parameter creation below. Its easier to read and a lot easier to code correctly when passing more than one parameter as you dont have to remember &'s and + concatenation.
function handleButton(obj) {
obj.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {activation: 1, myname: obj.id}, // add parameter
success: function (data){
alert(data);
}
});
}
Now the PHP will see 2 parameters in the $_POST array activation and myname
if(isset($_POST['activation']))
{
$name = $_POST['myname'];
var_dumb($name);
}
Or if you are using a framework which I assume you are
if(isset($this->input->post('activation')) {
$name = $this->input->post('myname');
var_dumb($name);
}
EDIT:
Spotted another issue your button has an attribute type="submit" this will cause the javascript to run AS WELL AS the form being submitted in the normal way.
Remove the type="submit" attribute and to be doubly sure that the form will not be submitted as well as the AJAX add a call to preventDefault(); as well before the AJAX call
Since the php script is conditioned by a second POST variable [if(isset($_POST['activation']))], you should post that as well.
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable+'&activation=1',// <-- RIGHT HERE
success: function (data){
alert(data);
}
});
}
SIDE NOTE: you could also echo instead of dump the variable:
if(isset($_POST['activation']))
{
echo $this->input->post('myname');
}
Try this in your ajax function :
function handleButton(obj) {
var javascriptVariable = obj.id;
//alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {myname: javascriptVariable},
success: function (data) {}
});
}
And in your PHP script, you can do $_POST['myname'] to get it (maybe $this->input->post('myname') can work, you can test it)
Look two id
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
AND
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
For both html elements id is same.It can not be used with in the same page.This may cause a problem for you...

Using php response to populate front end Ajax

This should be a very easy question, but I cannot find the answer. I have a js file that is making an ajax request to a php file. i am then trying to use the response provided by php to update the front end, but the response is not in the correct format. I am getting back the whole echo statement when I look in the console. Pardon my ignorance here but I am quite new to php. I think there is an issue sending back an a href link and br in my php
$.ajax({
url: 'php.php',
}, function (data) {
console.log(data);
$('.container').html(data);
});
PHP
<?php
$output = 'This is<br>a<br>test<br><span>Test Here</span>';
echo $output;
?>
When all this has successfully worked I want to change my html to:
<div class="container">
This is<br>a<br>test<br><span>Test Here</span>
</div>
When using jQuery's $.ajax function you can use either of { success: function() {...} } or .done() promise:
$.ajax({
url: 'php.php',
success: function (data) {
console.log(data);
$('.container').html(data);
}
});
Or
$.ajax({
url: 'php.php',
success: function (data) {
console.log(data);
$('.container').html(data);
}
}).done(function( data) {
console.log(data);
$('.container').html(data);
});

Trying to display PHP echo in HTML with JSON

I'm trying to display two PHP echo messages from a seperate PHP file onto my HTML body page. Whenever you click the submit button the echo message should popup in the HTML page without redirecting me to the PHP page.
I need to connect to my two files through Javascript so I wrote a script attemtping to connect the HTML file with the PHP file.
My HTML:
<div id="formdiv">
<form action="phpfile.php" method="get" name="fillinform" id="fillinform" class="js-php">
<input id="fillintext" name="fill" type="text" />
<input type="submit" id="submit1" name="submit1">
</form>
</div>
phpfile.php:
$q = $_GET['fill'];
$y = 2;
$work = $q * $y;
$bork = $work * $q;
echo json_encode($work) ."<br>";
echo json_encode($bork);
Javascript:
$(".js-php").submit(function()
var data = {
"fill"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
$(".formdiv").html(
""
"Your input: ")
}
You attached your logic to .submit() event and if you don't prevent default action, the form will be submitted to server. You can prevent it that way:
$(".js-php").submit(function(e) {
// your code goes here
e.preventDefault();
});
You'll have to append the data to your div like this:
success: function (data) {
$(".formDiv").append("Your input: " + data);
}
As per your html you should try this below code :
If you want to replace the whole html inside the div having id="formdiv"
success: function (data){
$("#formdiv").html("Your input: "+data)
}
or
success: function (data){
$("#formdiv").text("Your input: "+data)
}
If you want to append data to the div having id="formdiv"
success: function (data){
$("#formdiv").append("Your input: "+data)
}
Add curly braces after $(".js-php").submit(function(e) and close it after your ajax ends.
Add e.preventDefault() before you call ajax so it will not redirect
you to phpfile.php
Add alert(data) inside your function called at success of ajax.
there is a syntax error n line $(".formdiv").html("""Your input: ");
Your updated code should look like.
$(".js-php").submit(function(e){
var data = {
"fill"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
alert(data);
}
}

can't pass php array to jquery

Not able to pass PHP encoded array to js.
index.php
echo '<script src="script.js"></script>';
$a=array(1,2,3,4,5);
echo json_encode($a);
?>
script.js:
$.ajax({
method: 'GET',
url: 'index.php',
dataType: 'json',
success: function (Data) {
alert("Success!" + Data);
},
error: function (Data) {
alert("Wrong");
}
});
I always got message - "Wrong".
You have not pass html tags in your json value generated from php
echo '<script src="script.js"></script>';
simply delete the code above. also, you have to parse your JSON string after your function is succssed, :
function (data) {
JSON.parse(data).forEach(function (x) {
alert(x);
});
}
use post method i think It work
method: 'POST',

jquery .ajax always returns error - data being added to database

I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});

Categories