$.post is not working in combination with $J = jQuery.noConflict(); - javascript

I am having a problem with posting data from javascript to php.I am using the $.post method, though due to conflicts with wordpress I am alos using $J = jQuery.noConflict().
Therefore consequently I have the following, in javascript:
$J = jQuery.noConflict()
x=1
$J.post('/the directory',{x: x}, function(data){
});
alert($J.cookie("y"));
In php I have:
if(isset($_POST['x']))
{
setcookie("y", 1);
}
else{
setcookie("y", -1);
}
Every time I get to see that y = -1, indicating that x in php is not found. What am i doing wrong?
What did I try so far, which all did not work:
Connecting the post to different events (when submit is pressed, or when page is loaded)
Putting the alert ($J.cookie("y")) between the brackets which are behind the function (data)
Trying to remove the J after the $ or adding them up front in php
I am a bit afraid that the problem of the post is because I added $J = jQuery.noConflict(). Though I used many other functionality and then I did not have any problem, do you maybe know the solution or can you help me into the right direction? Thanks in advance!

The entire premise is faulty, cookies are part of the HTTP header being sent with every request, and to receive new cookies you would have to receive a new header, which would require a pageload.
You can't do an ajax request and set a cookie on the server, and then expect it to be accessible in javascript on the clientside without actually reloading the page and receiving the new and modified headers containing that cookie.

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

window.location.replace strange behavior

So I'm having this issue where I lose all my data on the first window.location.replace try (The second time i reload the same page everything seems to work fine)
I have searched around and haven't found anything like this
Here is the code so I can explain my issue more toroughly:
$(document).ready(function() {
$('#login_form').on('submit', function(event){
event.preventDefault();
// Retrieve form data
var formData = {
'index' : $('input[name=user]').val(),
'password' : $('input[name=pass]').val()
};
//convert formData from JS object to PHP understandable
var formData1=jsObj2phpObj(formData);
var url= 'login.php';
//sending with post in ajax to register.php
$.post(url,{formData1:formData1})
.done(function(data){
if(!(data["Log_success"])){
alert("Log failed")
}
else
{
window.location.replace('http://localhost/CPPv2/admin_commented/index.html#home');
var draw_stringholder="";
draw_stringholder+=data["user_index"]+data["user_email"];
document.getElementById("myPanel").innerHTML=draw_stringholder;
}
}
So what my function does is that it sends data to a PHP page and recieves JSON encoded data back. The first time I submit the form I seem to recieve no network data back (I think it's because of the window.location.replace removing it) but after refreshing the page and submiting the form again everything works fine (The Index and email are written inside myPanel element).
I have tried using window.location / window.location.href ... (I think i tried every other function there is) and they just don't send me anywhere like they're not working at all. The if(!(data["Log_sccuess"])) part always works (so the client - server communication works fine).
It's also important to say that im using JqueryMobile-1.4.4 (also tried their redirect method didn't work)
To sum it up I would like to change my current page link to a other one without losing the server generated data. (Since Im bassicaly staying on the same page just changing the Id part of it). I can fix my issue by refreshing the page after I have logged in (sending server request after log in) but that doesn't seem like the right way to do it.
Instead of window.location.replace I used $.mobile.changePage( "#ulr", { transition: "slideup"} );

Why am I getting this Internal Server Error in the Laravel Framework?

I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

hide variables passed in URL

We've been working on a web application and we've just about got it finished up, but there's one thing that bothering us (although by no means is it going to stop production.)
When we call one of the pages (index.html), we sometimes have to pass it a variable in the URL (searchid). So we get a page like http://domain.com/index.html?searchid=string.
We'd ideally like to not show the ?searchid=string, but I'm not sure how we'd do that.
My group doesn't own the index.html page (but we are working with the group that does), so I don't know how much we'd be able to do with anything like .htaccess or similar.
I was thinking about POSTing the variable, but I don't know how to receive it with just HTML and jQuery. Another person in my group thought that after the page loaded we could remove it from the URL, but I assume we would need a page refresh which would then lose the data anyway.
I'm trying to avoid XY problem where the problem is X and I ask about Y, so what's the right way to remove the variable from the URL?
You can use the History API, but it does require a modern browser
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
More information here:
Manipulated the browser history
Your question seems to indicate that the target page is not and will not be powered by some server-side script. If that's the case, I'd suggest changing the querystring to a hash, which has the advantage of being directly editable without triggering a page-load:
http://yourdomain.com/page.html#search=value
<script type='text/javascript'>
// grab the raw "querystring"
var query = document.location.hash.substring(1);
// immediately change the hash
document.location.hash = '';
// parse it in some reasonable manner ...
var params = {};
var parts = query.split(/&/);
for (var i in parts) {
var t = part[i].split(/=/);
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
}
// and do whatever you need to with the parsed params
doSearch(params.search);
</script>
Though, it would be better to get some server-side scripting involved here.
It's possible to rewrite the URL using JavaScript's history API. History.js is a library that does this very well.
That being said, I don't think there's any need for removing the query-string from the URL, unless you're dynamically changing the contents of the page to make the current query-string irrelevant.
You could post the data, then let the server include the posted data in the page, e.g.:
echo "<script> post_data = ".json_encode($_POST)." </script>";
This works cross-browser.

Categories

Resources