pass two different variables in javascript? - javascript

this is my javascript of first page
<script>
function MessageDetailsById(id)
{
$("#active"+id).css({"color":"red"});
var http = new XMLHttpRequest();
var url = "Ajax.php";
var adm = "<?php echo $admno; ?>";
var params = "Id="+id;"adm="+adm;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//alert(http.responseText);
}
}
http.send(params);
window.location.href="#";
}
</script>
this is the coding of ajax.php
<?php
include("model.php");
$DB=new database;
if(isset($_POST["Id"]))
{
$DB->updateMassageTitleStauts($_POST["Id"],$_POST["adm"]);
}
else
{
header("Location:index.php?ajaxmas=wHgfghks^^%&fnjfskjdfb");
}
?>
i want to send one variable of php and another is id of a div... how to send two parameters and recieves them on other side ??? please correct this code in details i am not expert ???

For the post data encoding:
var params = "Id=" + id + "&adm=" + adm;
Use & for separator.

Related

I want to make a cart with php and js with the js sending a post request

<script>
function cart(func,id){
let url = "<?= SITEURL ?>Home/cart/" + func;
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"value": id
}));
}
</script>
case 'cart':
require_once "modelProduct.php";
$model = new Product();
$idItem = $_POST['value'];
if($aParam[2] == 'add'){
if(isset($_SESSION['cart'])){
array_push($_SESSION['cart'],$idItem);
} else {
$_SESSION['cart'] = array();
array_push($_SESSION['cart'],$idItem);
}
} else if($aParam[2] == 'remove'){
if (($key = array_search($idItem, $_SESSION['cart'])) !== false) {
unset($_SESSION['cart'][$key]);
}
}
$category= $model->getById($idItem);
$aData['data'] = $products->getListaWhere("product_id = {$idItem}");
require_once "site/productsView.php";
break;
From what I saw this should send post request to site/Home/cart/func and there what would happened would be the ID would be added to the session['cart'] and the page would refresh but instead nothing seams to be happening

How can I pass data from client to server use raw AJAX?

Hello I have already search but they often use jquery ajax to pass data from js to PHP(server-side). but for my project it has a bunch of pure js code so I should use raw AJAX to pass data.
For example, if I want to send a variable "Imgname" that value = 13 and want to echo in php page.
this is my try
<script>
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert('send to server successfully');
}
};
xmlhttp.open("POST", "test2.php", true);
xmlhttp.send("Imgname=13");
}
</script>
in test2.php
<?php
$temp = $_POST['Imgname'];
echo $temp; /////output should be 13
?>
but error Undefined index: Imgname in C:\xampp\htdocs\test2.php on line 2
You need to make sure that you're sending the correct content-type:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Try sending the header:
var http = new XMLHttpRequest();
var url = "test2.php";
var params = "Imgname=13";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);

Post data using XMLHttpRequest to laravel 5.2 controller as request

I have done posting/updating successfully with javascript XMLHttpRequest() to php $_REQUEST like:
function ajax_edit(e_id){
var edit_form = document.getElementById('edit_form'+e_id);
var e_name = document.getElementById('name'+e_id).value,
e_email = document.getElementById('email'+e_id).value,
e_contact = document.getElementById('contact'+e_id).value,
e_status = document.getElementById('status'+e_id).value;
xmlhttp.open('GET', 'hello-world.php?edit=yes&id='+e_id+'&name='+e_name+'&email='+e_email+'&contact='+e_contact+'&status='+e_status, true);
xmlhttp.send();
$('#edit'+e_id).modal('hide');
return false;
edit_form.reset();
}
And my php work was like:
if(isset($_REQUEST['edit'])){
$name = mysqli_real_escape_string($conn, strip_tags($_REQUEST['name']));
$email = mysqli_real_escape_string($conn, strip_tags($_REQUEST['email']));
$contact = mysqli_real_escape_string($conn, strip_tags($_REQUEST['contact']));
$status = mysqli_real_escape_string($conn, strip_tags($_REQUEST['status']));
$edit_sql = "UPDATE users SET name = '$name', email = '$email', contact = '$contact', status = '$status' WHERE id = '$_REQUEST[id]'";
$run_edit = mysqli_query($conn, $edit_sql);
}
Now I am trying to apply the same process to another Laravel 5.2 project but don't know how to do, specially the url (hello-world.php?edit=yes) part from where I will send data to my controller as request.
So far I have done with this:
function submit_form(edit_id){
xmlhttp = new XMLHttpRequest();
var edit_form = document.getElementById('edit_form'+edit_id);
var url = "{{ URL::to('updatelabdetails'); }}";
var edit_labname = document.getElementById('labname'+edit_id).value,
edit_pcname = document.getElementById('pcname'+edit_id).value;
alert(edit_pcname);
var params = "labname='+edit_labname+'&pcname='+edit_pcname";
alert(params);
xmlhttp.open('GET', url+"?"+params, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && http.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
return false;
}
But only able to output till alert(edit_pcname); part.
My Route:
Route::post('updatelabdetails', 'LoginController#updateLabDetails');
My Controller:
public function updateLabDetails(Request $request){
$post = $request->all();
var_dump($post);
die();
}
After submitting its going to some url like /showlabdetails? with MethodNotAllowedHttpException error.
Thanks in advance.
Please update your submit_form function like this
function submit_form(edit_id){
var edit_labname = document.getElementById('labname'+edit_id).value,
edit_pcname = document.getElementById('pcname'+edit_id).value;
var http = new XMLHttpRequest();
var url = "updatelabdetails";
var params = "labname='+edit_labname+'&pcname='+edit_pcname";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
Your laravel roure isn't correct you've registered POST route and accessing the GET one.
Change Route::post('updatelabdetails', 'LoginController#updateLabDetails'); to Route::get('updatelabdetails', 'LoginController#updateLabDetails');
you need to add token in your request as said in the laravel documentation. see this link https://laravel.com/docs/5.4/csrf

PHP POST and GET JSON-Data [duplicate]

This question already has answers here:
handle json request in PHP
(4 answers)
Closed 6 years ago.
i try to do a very simple Webserver witch can send and get JSON Data.
JavaScript:
var username = document.getElementsByName('username')[0].value;
var antwort1 = document.getElementsByName('frag1')[0].value;
var antwort2 = document.getElementsByName('frag2')[0].value;
var antwort3 = document.getElementsByName('frag3')[0].value;
//JSON
var jsondata = {"data" :[
{"name": username},
{"antwort1":antwort1},
{"antwort2":antwort2},
{"antwort3":antwort3}]};
var url = "https://...../apps/server.php";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", url, true );
xmlHttp.send(JSON.stringify(jsondata));
console.log(xmlHttp.responseText);
alert(xmlHttp.responseText);
PHP:
<?php
$json_data;
if( $_GET["json"]) {
echo $json_data;
exit();
}
/*
if(!isset($_POST)){
//$json_data = json_decode($_POST["data"]);
echo "test POST";
exit();
}
*/
if(!isset($_POST)){
$json_data = file_get_contents('php://input');
echo $json_data;
exit();
}
?>
My main Problem is how can i send JSON to my php server. Ando how can i check this. Finaly i just want to save the Json Data and send it back.
Send JSON data from Javascript to PHP?
I try it like in the link above.
UPDATE: like rick
JavaScript: Two Button one for GET one for POST
function btn1() {
alert("btn1");
var url = "https://....../apps/server.php?json=null";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false ); // false for synchro nous request
xmlHttp.send( null );
alert(JSON.stringify(xmlHttp.responseText));
console.log(xmlHttp.responseText);
};
function btn0() {
alert("test");
var username = document.getElementsByName('username')[0].value;
var antwort1 = document.getElementsByName('frag1')[0].value;
var antwort2 = document.getElementsByName('frag2')[0].value;
var antwort3 = document.getElementsByName('frag3')[0].value;
//alert(username+" "+antwort1+" "+antwort2+" "+antwort3);
//JSON
var jsondata = {"data" :[
{"name": username},
{"antwort1":antwort1},
{"antwort2":antwort2},
{"antwort3":antwort3}]};
//alert(jsondata.data[0].name);
var url = "https://...../server.php";
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
};
xmlHttp.open( "POST", url, true );
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("jsonData="+JSON.stringify(jsondata));
};
PHP
<?php
$json_data = "";
if( $_GET["json"]) {
echo $json_data;
exit();
}
if(!isset($_POST)){
$json_data = $_POST["name"];
echo $json_data;
exit();
}
?>
For the POST part it's esier to use application/x-www-form-urlencoded so you can treat the POST data as if it's a form.
For the response you have to setup a callback cause your call is async.
try something like that
var url = "https://...../apps/server.php";
var xmlHttp = new XMLHttpRequest();
xmlHttp .onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
};
xmlHttp.open( "POST", url, true );
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("jsonData="+JSON.stringify(jsondata));
For the php
if(!isset($_POST)){
$json_data = $_POST["jsonData"];
echo $json_data;
exit();
}
It's 10 years than I don't write a line in PHP but I hope the concept is clear.

my php can't receive the 'post' variabe I am sending via ajax

Here is my javascript:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
hanapin.send(reqdata);
hanapin.onreadystatechange = function() {
if (hanapin.readyState == 4 && hanapin.Status == 200) {
document.getElementById('province').innerHTML=hanapin.ResponseText
}
}
window.alert(targeturl);
window.alert(reqdata);
}
I know the function is receiving the data because I used the alert.
but on php:
<?php
$findwat = $_POST['condo'];
echo $findwat;
?>
even when I open the php file using a separate link it won't echo the variable
An example using jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
$.post("testajax.php", {condo:proptype}, function(data){
// data is the result received from php
alert(data);
});
}
A mandatory header field for http post request is Content-length. change your code to:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hanapin.setRequestHeader("Content-length", reqdata.length);
hanapin.setRequestHeader("Connection", "close");
hanapin.send(reqdata);
hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} }
window.alert(targeturl);
window.alert(reqdata);
}
also a better solution is to use jquery to handle ajax

Categories