How can I submit a form dynamically where I run mysqli to check if an email exists. If it exists, echo an error ALL DYNAMICALLY.
I would like to run a jquery ajax submit but echo out php errors. I can submit but nothing will echo.
function DYNAMIC_CHECK(X)
{
$.ajax(
{
url:'<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>',
type:'POST',
data:X,
});
}
X is the formdata. It all works, but the PHP echo will not show up nor will any vars that are created and echoed out throughout the page as errors.
if(isset($_POST['REGISTER']))
{
$COUNT = mysqli_num_rows(mysqli_query($CON, "SELECT * FROM USER WHERE EMAIL='$EMAIL'"));
if($COUNT == 1) { $EMAIL_ERROR='EMAIL ALREADY EXISTS'; }
}
echo $EMAIL_ERROR;
Is this possible to dynamically show $EMAIL_ERROR?
You can use the shorthand function jQuery.post() which sends the serialized data of the form and returns the result into a variable.
$.post( "test.php", $( this ).serialize(), function ( data ) {
...what to do with data (returns the result of test.php)...
});
You can modify your ajax function to display result from the request.
$.ajax(
{
url:'<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>',
type:'POST',
data:X,
success: function(data) {
alert(data);
}
});
The echo of the request will be returned in the data variable in the success: function. Use the alert(data) to see what info is returned from the request.
Related
I've the following HTML link code
<div id="message"></div>
<a href="cats.php?id=60&color=brown&name=kitty" id="petlink">
Click here
</a>
using jQuery and Ajax and On click this link, I would like to send those parameters
id=60
color=brown
name=kitty
to a file find.php that will catch those parameters using $_GET as
<?PHP
$id = $_GET['id']; // 60
$color = $_GET['color']; // brown
$name = $_GET['name']; // kitty
// doing some searching in database
echo "yep found it"; // or whatever i would print
?>
and will respond back with whatever (like echo "yep found it") that would be shown up in between this div
<div id="message"></div>
I've read many tutorials but all was speaking about form data submissions but unfortunately i did not found for such case so any help will really appropriate it.
To create this you simply need to send an AJAX request from the click event of the a element. You can retrieve the querystring by reading the src property of the anchor, something like this:
$('#petlink').click(function(e) {
e.preventDefault();
$.ajax({
url: 'find.php',
data: this.src.split('?')[1],
success: function(response) {
$('#message').text(response);
}
});
});
as rory sad you need to give a click event to your a tag then
$('#petlink').click(function(e) {
e.preventDefault();
$.ajax({
type:'POST'
url: 'find.php&pets=1',
data: this.href.split('?')[1],
dataType:'json',
success: function(response) {
$('#message').text(response);
}
});
});
on your php file just add
if($_GET['pets'] == 1)
{
$id = $_POST['id']; // 60
$color = $_POST['color']; // brown
$name = $_POST['name']; // kitty
echo 'pets came';
exit;
}
I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
I am trying to use ajax for retrieving data from my server. I use cakephp and jquery.
The ajax code is as follows:
<script>
$(document).ready(function(){
$(".viewMode").click(function(){
$.ajax({
type: "POST",
url:"viewModeSwitching",
data: {
mobileViewCookie:12,
},
success:function(result){
// window.location.href = result;
}
}
);
});
});
</script>
...
<?php
echo "<br>";
echo $this->Form->button(__('Desktop View'), array('type' => 'button','class' =>"viewMode",));
echo "<br>";
?>
This works well, in firebug I see that the POST is sent with value mobileViewCookie=12.
The point is that my cakephp controllerfunction 'viewModeSwitching' cannot retrieve that data.
I checked $this->data, $this->params, $_POST, etc but no sign of the data that had been send in the POST message.
Any suggestions?
/Antoine
I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.
Below is my ajax call code. I want to send one data in .php file via ajax call and want to get two values from .php file. This two values I want to set in different 'input' tags whose id are 'course_name' and 'course_credit'.
Here my ajax call return correct value(real value from DB table) of 'course_name' input tag.
But 'MY PROBLEM IS' the value of input tag whose id is 'course_credit' shows 'success'. How can I get the correct value(real value from DB table) of id 'course_credit' ?
I have a 'select' tag which id is 'c_select'
HTML:
<input type="text" name="course_name" id="course_name" value=""/>
<input type="text" name="course_credit" id="course_credit" value=""/>
AJAX :
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
});
});
get_course_info_db.php
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name,$c_credit;
exit();
?>
AJAX code:-
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
$('#course_name').val(data[0]);
$('#course_credit').val(data[1]);
}
});
});
PHP code:-
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name.",".$c_credit;
exit();
?>
The success callback is Function( PlainObject data, String textStatus, jqXHR jqXHR ); http://api.jquery.com/jQuery.ajax/
php:
$data = array(
'name' => $c_name,
'credit' => $c_credit,
);
echo json_encode($data);
javascript:
success: function(data) {
var result = $.parseJSON(data);
$('#course_name').val(result.name);
$('#course_credit').val(result.credit);
}
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
second arguement is the status of http request, you have to encode the answer, i suggest you JSON
in your php
$c_credit = $all_course_data['c_credit'];
echo json_encode(array('name' => $c_name,'credit' => $c_credit));
exit();
and in your javascript
success: function(response,status){
var datas = JSON.parse(response);
$('#course_name').val(datas.name);
$('#course_credit').val(data.credit);
}
this is not tested, but this is the way to do it
I'd suggest using JSON to encode the data you fetch from the database.
Try changing your ajax call as follows:
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
dataType: 'json', // jQuery will expect JSON and decode it for you
success: function(reply_data){
$('#course_name').val(reply_data['c_name']);
$('#course_credit').val(reply_data['c_credit']);
}
});
});
And your PHP as follows:
include('db_connection.php');
// Escape your input to prevent SQL injection!
$c_id = mysql_real_escape_string($_POST['c_id']);
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
echo json_encode($all_course_data);
exit();
I haven't tested this but I imagine it'd work for you.