Using jQuery and Ajax to capture and send parameters in href - javascript

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;
}

Related

How do I run a php function and display the contents on page using javascript/jquery?

I have a php script which gets all my movies from a specific category and echos the html output using foreach loop placed inside of a function.
Instead of displaying the entire library at once I'd like to display it one category at a time by clicking a button (without page refresh) for example:
User clicks "Action" button:
<li>Action</li>
Which activates Action();
function Action()
{
jQuery.ajax({
type: "POST",
url: 'index2.php',
dataType: 'json',
data: {functionname: 'Movies', arguments: ['Action']},
success: function (returnData) {
data = returnData;
document.getElementById("Action").innerHTML = returnData;
console.log(data);
}
});
}
Action Div:
<a id="Action"></a></div>
<h3><span>Action</span></h3></center>
<div id="detail[19]">
</div>
The PHP function is Movies($var) when passing "Action" into it, it runs fine. So what do I do in order to get "Movies(Action)" to print to "detail[19]"
The PHP function:
function Movies($category){
$movies = glob('./uploads/Videos/Movies/'.$category.'/*/*.{mp4,m4v}', GLOB_BRACE);
global $images,$temp,$emtyImg,$actual_link,$dir,$rmvd;
foreach ($images as $image) {
$lookup[pathinfo($image, PATHINFO_FILENAME)] = $image;
}
foreach ($subs as $sub) {
$lookup2[pathinfo($sub, PATHINFO_FILENAME)] = $sub;
}
echo '<div id="detail['.$rmvd.']">';
include($_SERVER['DOCUMENT_ROOT']."/scripts/amzn.php");
foreach ($movies as $movie) {
*Lot's of useless code that echos div's with videos in them* }
echo '</div>';
$rmvd++;
}
I know I'm missing what I need for the PHP side and likely messed up the jquery bit. I'm at a loss at how to continue successfully.
You need to return a json object in php so that javascript can read it. For example:
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

how to make submit button both send form thru' PHP -> MySQL and execute javascript?

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>

Passing a php variable to another php file using ajax

I have some divs with class content-full which are created according to the data stored in a MySQL table. For example, if I have 3 rows there will be 3 divs.
When I click on any of the divs then the data associated with the ID for that div should be displayed inside div content-full. However, the content associated with the last div appears when I click on any of the divs because I am not passing any kind of variable ID that can be used to specify the clicked div.
<script type="text/javascript">
$(document).ready(function() {
$(".content-short").click(function() { //
$.ajax({
type: "GET",
url: "content.php", //
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
});
</script>
content.php
<?php
include "mysql.php";
$query= "SELECT Content FROM blog limit 1";
$result=mysql_query($query,$db);
while($row=mysql_fetch_array($result))
{
echo $row['Content'];
}
mysql_close($db);
?>
Is there an alternate way to do this or something that I need to correct for it to work?
Thanks
First off, you will have to pass actual data to the your PHP script. Let's first deal with the JavaScript end. I am going to assume that your HTML code is printed using php and you are able to create something like the following: <div class=".content-short" data-id="2" />:
$(".content-short").click(function() {
// get the ID
var id = $(this).attr('data-id');
$.ajax({
type: "post",
url: "content.php",
data: 'id=' + id
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
Next up is reading the value you passed in using the script:
<?php
include "mysql.php";
// Use the $_POST variable to get all your passed variables.
$id = isset($_POST["id"]) ? $_POST["id"] : 0;
// I am using intval to force the value to a number to prevent injection.
// You should **really** consider using PDO.
$id = intval($id);
$query = "SELECT Content FROM blog WHERE id = " . $id . " limit 1";
$result = mysql_query($query, $db);
while($row=mysql_fetch_array($result)){
echo $row['Content'];
}
mysql_close($db);
?>
There you go, I have modified your query to allow fetching by id. There are two major caveats:
First: You should not use the mysql_ functions anymore and they are deprecated and will be removed from PHP soon if it has not happened yet!, secondly: I cannot guarantee that the query works, of course, I have no idea what you database structure is.
The last problem is: what to do when the result is empty? Well, usually AJAX calls send and respond with JSON objects, so maybe its best to do that, replace this line:
echo $row['Content'];
with this:
echo json_encode(array('success' => $row['Content']));
Now, in your success function in JS, you should try to check if there a success message. First of, change dataType to json or remove that line entirely. Now replace this success function:
success: function(response){
$(".content-full").html(response);
}
into this:
success: function(response){
if(response.success) $(".content-full").html(response);
else alert('No results');
}
Here the deprecation 'notice' for the mysql_ functions: http://php.net/manual/en/changelog.mysql.php
You can look at passing a parameter to your script, generally like an id by which you can search in the db.
The easiest way to achieve this is by get parameters on the url
url: "content.php?param=2",
Then in php:
<?php $param = $_GET['param'];
...

javascript array in php using Ajax on submit not working

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.

JQuery, Ajax submit with Mysqli validation

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.

Categories

Resources