Why the javascript code doesn't connect to the php file? [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed yesterday.
Improve this question
Javascript code
$(document).ready(function () {
//Add to cart function
$('.add_to_cart').click(function (e) {
//alert("add to cart");
e.preventDefault();
var product_id = $(this).val();
$.ajax({
method: "POST",
url: "functions/carthandler.php",
data: {
"product_id": product_id,
"scope": "add"
},
dataType: "dataType",
success: function (response) {
alert("success");
if (response == 401) {
alert("Login to continue");
}
}
});
});
});
PHP code with path 'functions/carthandler.php'
<?php
include('../includes/connect.php');
session_start();
if (isset($_SESSION['username'])) {
if (isset($_POST['scope'])) {
$scope = $_POST['scope'];
echo "<script>alert('success')</script>";
exit;
}
} else {
echo 401;
}
?>
I've checked whether js code connect to the php code using echo, but the php doesn't seem to have respond anything. I've also tried rechecking the indentation and everything and still not working.

Related

Can't access data in php file sent via jquery ajax [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to access some data in php file sent via jquery ajax method
but I get an error of Undefined Index.
sender.php
$('#slot1').click(function(){
var selectedDate = $('#selectedDate').html();
var timeSlot = $('#timeSlot1').html();
var hm = timeSlot.slice(0, 5);
var seconds = ':00';
var time = hm + seconds;
$.ajax({
url: 'insertBookings.php',
type: 'post',
data: {date: selectedDate, timeslot: time},
async: false,
success: function(data) {
alert(data);
}
})
})
reciver.php
<?php
$date = $_POST['date'];
echo date;
?>
Consider testing with the following.
$('#slot1').click(function() {
var selectedDate = $('#selectedDate').text().trim();
var timeSlot = $('#timeSlot1').text().trim();
var selectedTime = timeSlot.slice(0, 5) + ":00";
$.ajax({
url: 'insertBookings.php',
type: "POST",
data: {
"date": selectedDate,
"timeslot": selectedTime
},
async: false,
beforeSend: function() {
console.log("Sending Date: " + selectedDate + ", Time: " + time);
},
success: function(data) {
console.log("Received: ", data);
},
error: function(xhr, status, error) {
console.log("Error:", status, error);
}
});
});
No major changes, yet I switched from .html() to .text(). The former will gather more than just the text if there is anything. Since you did not provide a Minimal, Reproducible Example, this is a precaution to ensure you're not capturing incorrect items before sending them.
I also added some extra Ajax code to help see each part as it happens.
In your PHP, you have a syntax error too. You are missing a $ before date.
<?php
$date = $_POST['date'];
echo $date;
?>

What is wrong js and php objects [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
In test.php i have this code
<?php
if (isset($_POST['user'])) {
echo "hi";
}
exit; ?>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var user = {
'name': 'Wayne',
'country': 'Ireland',
'selected': new Array(1, 5, 9)
};
var userStr = JSON.stringify(user);
$.ajax({
url: 'test.php',
type: 'POST',
data: {user: userStr},
success: function(response){
//do whatever.
}
});
</script>
</head>
</html>
I changed it, but isset($_POST['user']) = false because my page is empty so why?
All this code is in test.php
You are not printing / visualizing the actual response of the ajax.
<?php
if (isset($_POST['user'])) {
$user_string = $_POST['user'];
var_dump($user_string);
$user_asarr = json_decode($user_string, true); // associative array
var_dump($user_asarr);
exit();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var user = {
'name': 'Wayne',
'country': 'Ireland',
'selected': new Array(1, 5, 9)
};
var userStr = JSON.stringify(user);
$.ajax({
url: 'test.php',
type: 'POST',
data: {user: userStr},
success: function(response){
console.log(response); // check out your console!
}
});
</script>

The check does not work:- if (isset ($_PHP["form_name"])) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
There are several forms for queries in the file, you need to do a form check, if you do not do this, all forms with queries are executed, as for me it is not correct. Here with the help of if (isset($_POST ['form_name'])) I do a check, but does not exit. What is the problem?
<form id="form" method="POST">
<input type="text" name="telephone[]">
<input type="text" name="telephone[]">
<input type="hidden" name="form_name" value="form_ex">
<button type="submit" name="update" id="btn_post_phones" value="button_value">Update phone</button>
</form>
if (isset($_POST['form_name'])) {
var_dump ('true -->');
echo "<pre>";
var_dump(json_decode($_POST["phones"], true));
} else {
var_dump ('false-->');
echo "<pre>";
var_dump(json_decode($_POST["phones"], true));
}
//string(8) "false-->"
//array(2) {
// [0]=>
// string(6) "345345"
// [1]=>
// string(6) "345345"
//}
$('#form').submit(function(event) {
var arrPhones = new Array();
event.preventDefault();
$('input[name="telephone[]"]').each(
function() {
arrPhones.push($(this).val());
});
var data='phones='+JSON.stringify(arrPhones);
$.ajax({
type: 'POST',
url: 'regist.php',
dataType: 'json',
data: data,
// data: $('input[name="telephone[]"]').serialize,
beforeSend: function(){
console.log('before ' + data);
},
success: function(response){
console.log(response);
}
});
});
1.Remove var data='phones='+JSON.stringify(arrPhones);
2.instead of data: data, write data:{'phones':JSON.stringify(arrPhones)},
3.Instead of if (isset($_POST['form_name'])) {...} use if (isset($_POST['phones'])) {...}

jQuery / Ajax: How to pass JS variable to specific PHP function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to PHP and never used Ajax before so I hope someone can help me with this.
I have a separate functions.js file that stores all the JS I use for the pages of a website.
So far all the exchange with the db is done with PHP directly on the pages which works fine so far but now I have a scenario where I need to initiate this from the JS file.
My thought was I could create a separate PHP file (ajax.php) that hosts functions just for such purposes and then pass data via Ajax from the JS file to this PHP file.
So far I have the following but since there are multiple functions on the ajax.php file I am not sure how to pass this to the specific function I need.
Also, I am not sure if the Ajax call I have is set up correctly.
Can someone help me with this and maybe also explain your answer in a few words ?
Basically, here I want to pass the JS variable "itemID" to the PHP function fetchTransMain where this should be used for the variable $itemID (the variable $trans is generated in PHP).
Update: I would also need to know how to get the result from the PHP function back in JS. I didn't find an approach for this yet, perhaps with an Ajax GET call ??
What I have in my functions.js file:
var itemID = "someID";
$.ajax({
url: "ajax.php",
type: "post",
cache: "false",
data: itemID,
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
});
...and on my ajax.php file:
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
echo $val["trans"];
}
}
}
Many thanks in advance,
Mike
You have to define data as an object:
$.ajax({
url: "ajax.php",
type: "post",
cache: "false",
data: {itemId: itemID},
success: function(data) {
console.log(data);
alert("success");
},
error: function(){
alert("failure");
}
});
And then:
$itemId = $_POST['itemId'];
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
echo $val["trans"];
}
}
}
I strongly suggest you to read some tutorial about ajax and PHP because there are so many aspects involved in this question that we can't explain them all in one answer. Anyway what you want to do is very common, you have a value in your browser that you want to save on your server.
The first part is almost correct:
$.ajax({
url: "ajax.php",
type: "post",
cache: "false",
data: {valueName: itemID},
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
});
Just pay attantion to the data parameter, you should pass an object there with a name. That name is the name that you'll use on PHP to retrieve the value.
Then on server side:
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
echo $val["trans"];
}
}
}
$valueFromClient = $_POST['valueName'];
fetchTransMain($trans, $valueFromClient);
Here you have to use $_POST since we have choose type: "post" on the client side.
Hope this helps

refreshing php content inside div when input onchange [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a simple <input> and when user writes there something I need to refresh php inside div so it will look like some.php?key=thevaluefrominput. How would I do that? I guess I need to use query but I'm not sure how.
I want something like this when you write something to Type to find tags it changes the the tags bellow.
Thanks for the answers.
This sounds like a job for AngularJS :)
However this is jQuery solution:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape($.trim($('#myinputfield').val())),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
});
});
If you mean that while user types (before submission), div content changes? Then remove
$('form').submit(function (e) {
e.preventDefault();
and instead put
$('#myinputfield').keydown(function () {
There is a setInterval method that I mentioned in comment, so the first chunk of code I posted, replace it with this one:
$(function () {
var old_val = '';
var curr_val = '';
setInterval(function () {
curr_val = $.trim($('#myinputfield').val());
if (old_val != curr_val) {
old_val = curr_val;
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape(curr_val),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
}
}, 2000);
});
It checks if value of the field changed every 2s, please replace amount in ms (2000) if you like.

Categories